-
Notifications
You must be signed in to change notification settings - Fork 344
/
index.jsx
361 lines (328 loc) · 10.1 KB
/
index.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
/** External Dependencies */
import React, { memo, useCallback, useEffect, useState, useRef } from 'react';
/** Internal Dependencies */
import MainCanvas from 'components/MainCanvas';
import { ROOT_CONTAINER_CLASS_NAME } from 'utils/constants';
import Topbar from 'components/Topbar';
import Tabs from 'components/Tabs';
import ToolsBar from 'components/ToolsBar';
import {
HIDE_LOADER,
RESET,
SET_FEEDBACK,
SET_ORIGINAL_IMAGE,
SET_SHOWN_TABS_MENU,
SHOW_LOADER,
UPDATE_STATE,
} from 'actions';
import FeedbackPopup from 'components/FeedbackPopup';
import loadImage from 'utils/loadImage';
import {
usePhoneScreen,
useResizeObserver,
useStore,
useTransformedImgData,
} from 'hooks';
import Spinner from 'components/common/Spinner';
import { getBackendTranslations } from 'utils/translator';
import cloudimageQueryToDesignState from 'utils/cloudimageQueryToDesignState';
import finetunesStrsToClasses from 'utils/finetunesStrsToClasses';
import filterStrToClass from 'utils/filterStrToClass';
import isSameImage from 'utils/isSameImage';
import useUpdateEffect from 'hooks/useUpdateEffect';
import TabsDrawer from 'components/TabsDrawer';
import {
StyledAppWrapper,
StyledMainContent,
StyledTabs,
StyledCanvasAndTools,
} from './App.styled';
const App = () => {
const {
config,
isLoadingGlobally,
haveNotSavedChanges,
dispatch,
originalImage,
shownImageDimensions,
t,
theme,
feedback = {},
} = useStore();
const {
loadableDesignState,
useCloudimage,
cloudimage,
source,
avoidChangesNotSavedAlertOnLeave,
useBackendTranslations,
translations,
language,
defaultSavedImageName,
observePluginContainerSize,
showCanvasOnly,
getCurrentImgDataFnRef,
updateStateFnRef,
noCrossOrigin,
resetOnImageSourceChange,
} = config;
const showTabsDrawer = window.matchMedia('(max-width: 760px)').matches;
const [observeResize, unobserveElement] = useResizeObserver();
const [rootSize, setRootSize] = useState({
width: undefined,
height: undefined,
});
const isPhoneScreen = usePhoneScreen();
const pluginRootRef = useRef(null);
const cloudimageQueryLoaded = useRef(false);
const imageBeingLoadedSrc = useRef(null);
// Hacky solution, For being used in beforeunload event
// as it won't be possible to have the latest value of the state variable in js event handler.
const haveNotSavedChangesRef = useRef(haveNotSavedChanges);
const transformImgFn = useTransformedImgData();
const setNewOriginalImage = useCallback((newOriginalImage) => {
dispatch({
type: SET_ORIGINAL_IMAGE,
payload: {
originalImage: newOriginalImage,
},
});
}, []);
const setError = useCallback((newError) => {
dispatch({
type: SET_FEEDBACK,
payload: {
feedback: {
message: newError.message || newError,
duration: 0,
},
},
});
}, []);
// We are promisifying the image loading for mixing it with other promises
const loadAndSetOriginalImage = (imgToLoad) =>
new Promise((resolve) => {
const imgSrc = imgToLoad?.src || imgToLoad;
if (
imageBeingLoadedSrc.current === imgSrc ||
(!imgSrc && originalImage) ||
isSameImage(imgSrc, originalImage)
) {
if (!imageBeingLoadedSrc.current) {
resolve();
}
return;
}
const triggerResolve = () => {
imageBeingLoadedSrc.current = null;
resolve();
};
imageBeingLoadedSrc.current = imgSrc;
// This timeout is a workaround when re-initializing
// the react app from vanilla JS. Due to a bug in react
// the dispatch method that is called in setNewOriginalImage
// still points to the old dispatch method after re-init,
// so we need to wait for one tick to make sure it's updated.
//
// This applies to both URLs and HTMLImageElement, since URLs
// may resolve immediately in some cases, e.g. memory cache.
setTimeout(() => {
if (typeof imgToLoad === 'string') {
loadImage(imgToLoad, defaultSavedImageName, noCrossOrigin)
.then(setNewOriginalImage)
.catch(setError)
.finally(triggerResolve);
} else if (imgToLoad instanceof HTMLImageElement) {
if (!imgToLoad.name && defaultSavedImageName) {
// eslint-disable-next-line no-param-reassign
imgToLoad.name = defaultSavedImageName;
}
if (!imgToLoad.complete) {
imgToLoad.addEventListener('load', () => {
setNewOriginalImage(imgToLoad);
triggerResolve();
});
return;
}
setNewOriginalImage(imgToLoad);
triggerResolve();
} else {
setError(t('invalidImageError'));
triggerResolve();
}
}, 0);
});
const promptDialogIfHasChangeNotSaved = (e) => {
if (haveNotSavedChangesRef.current) {
e.preventDefault();
e.returnValue = '';
}
};
// loadingPromisesFn is a function for enabling the ability to show loader first then trigger requests not vice versa.
const handleLoading = (loadingPromisesFn = () => []) => {
dispatch({ type: SHOW_LOADER });
return Promise.all(loadingPromisesFn()).finally(() => {
dispatch({ type: HIDE_LOADER });
});
};
const updateDesignStateWithLoadableOne = () => {
if (loadableDesignState && Object.keys(loadableDesignState).length > 0) {
dispatch({
type: UPDATE_STATE,
payload: {
...loadableDesignState,
finetunes: finetunesStrsToClasses(loadableDesignState?.finetunes),
filter: filterStrToClass(loadableDesignState?.filter),
},
});
}
};
useUpdateEffect(() => {
if (source && !isSameImage(source, originalImage)) {
cloudimageQueryLoaded.current = false;
handleLoading(() => [loadAndSetOriginalImage(source)]);
}
if (resetOnImageSourceChange) {
dispatch({
type: RESET,
payload: { config },
});
}
}, [source]);
useUpdateEffect(() => {
const newImgSrc = loadableDesignState?.imgSrc;
if (newImgSrc && !isSameImage(newImgSrc, originalImage)) {
handleLoading(() => [
loadAndSetOriginalImage(newImgSrc).then(
updateDesignStateWithLoadableOne,
),
]);
} else {
updateDesignStateWithLoadableOne();
}
}, [loadableDesignState]);
useEffect(() => {
if (
Object.keys(shownImageDimensions || {}).length > 0 &&
!Object.keys(shownImageDimensions).some(
(k) => !shownImageDimensions[k],
) &&
originalImage &&
useCloudimage &&
cloudimage?.loadableQuery &&
!cloudimageQueryLoaded.current
) {
dispatch({
type: UPDATE_STATE,
payload: cloudimageQueryToDesignState(
cloudimage.loadableQuery,
shownImageDimensions,
originalImage,
),
});
cloudimageQueryLoaded.current = true;
}
}, [shownImageDimensions, originalImage, useCloudimage, cloudimage]);
useEffect(() => {
let isUnmounted = false;
if (observePluginContainerSize && pluginRootRef.current) {
observeResize(pluginRootRef.current.parentNode, ({ width, height }) =>
setRootSize({ width, height }),
);
} else if (rootSize.width && rootSize.height && !isUnmounted) {
setRootSize({ width: undefined, height: undefined });
}
return () => {
if (observePluginContainerSize && pluginRootRef.current) {
unobserveElement(pluginRootRef.current);
}
isUnmounted = true;
};
}, [observePluginContainerSize]);
useEffect(() => {
const initialRequestsPromisesFn = () => [
loadAndSetOriginalImage(loadableDesignState?.imgSrc || source),
...(useBackendTranslations
? [getBackendTranslations(language, translations)]
: []),
];
handleLoading(initialRequestsPromisesFn);
if (window && !avoidChangesNotSavedAlertOnLeave) {
window.addEventListener('beforeunload', promptDialogIfHasChangeNotSaved);
}
return () => {
if (window && !avoidChangesNotSavedAlertOnLeave) {
window.removeEventListener(
'beforeunload',
promptDialogIfHasChangeNotSaved,
);
}
};
}, []);
useEffect(() => {
if (updateStateFnRef && typeof updateStateFnRef === 'object') {
updateStateFnRef.current = (newStatePartObjOrFn) => {
dispatch({
type: UPDATE_STATE,
payload: newStatePartObjOrFn,
});
};
}
}, [updateStateFnRef, dispatch]);
useEffect(() => {
if (getCurrentImgDataFnRef && typeof getCurrentImgDataFnRef === 'object') {
getCurrentImgDataFnRef.current = transformImgFn;
}
}, [transformImgFn]);
useEffect(() => {
haveNotSavedChangesRef.current = haveNotSavedChanges;
}, [haveNotSavedChanges]);
const toggleMainMenu = (open) => {
dispatch({
type: SET_SHOWN_TABS_MENU,
payload: {
opened: open,
},
});
};
const renderContent = () => (
<>
{!showCanvasOnly && (
<>
{showTabsDrawer && <TabsDrawer toggleMainMenu={toggleMainMenu} />}
<Topbar toggleMainMenu={toggleMainMenu} />
</>
)}
{originalImage && feedback.duration !== 0 && (
<StyledMainContent className="FIE_main-container">
{!showCanvasOnly && !showTabsDrawer && (
<StyledTabs className="FIE_tabs">
<Tabs toggleMainMenu={toggleMainMenu} />
</StyledTabs>
)}
<StyledCanvasAndTools
className="FIE_editor-content"
showTabsDrawer={showTabsDrawer}
>
<MainCanvas />
{!showCanvasOnly && <ToolsBar isPhoneScreen={isPhoneScreen} />}
</StyledCanvasAndTools>
</StyledMainContent>
)}
</>
);
return (
<StyledAppWrapper
className={ROOT_CONTAINER_CLASS_NAME}
data-phone={isPhoneScreen}
showTabsDrawer={showTabsDrawer}
ref={pluginRootRef}
$size={rootSize}
>
{isLoadingGlobally && <Spinner theme={theme} />}
{renderContent()}
<FeedbackPopup />
</StyledAppWrapper>
);
};
export default memo(App);