forked from laurent22/joplin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImageEditor.tsx
190 lines (166 loc) · 4.99 KB
/
ImageEditor.tsx
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
const React = require('react');
import { _ } from '@joplin/lib/locale';
import Setting from '@joplin/lib/models/Setting';
import shim from '@joplin/lib/shim';
import { themeStyle } from '@joplin/lib/theme';
import { Theme } from '@joplin/lib/themes/type';
import { useCallback, useEffect, useMemo, useRef } from 'react';
import { Alert, BackHandler } from 'react-native';
import { WebViewMessageEvent } from 'react-native-webview';
import ExtendedWebView from '../../ExtendedWebView';
type OnSaveCallback = (svgData: string)=> void;
type OnCancelCallback = ()=> void;
interface Props {
themeId: number;
initialSVGData: string;
onSave: OnSaveCallback;
onCancel: OnCancelCallback;
}
const useCss = (editorTheme: Theme) => {
return useMemo(() => {
return `
:root .imageEditorContainer {
--primary-background-color: ${editorTheme.backgroundColor};
--primary-background-color-transparent: ${editorTheme.backgroundColorTransparent};
--secondary-background-color: ${editorTheme.selectedColor2};
--primary-foreground-color: ${editorTheme.color};
--secondary-foreground-color: ${editorTheme.color2};
--primary-shadow-color: ${editorTheme.colorFaded};
width: 100vw;
height: 100vh;
box-sizing: border-box;
}
body, html {
padding: 0;
margin: 0;
}
`;
}, [editorTheme]);
};
const ImageEditor = (props: Props) => {
const editorTheme: Theme = themeStyle(props.themeId);
const webviewRef = useRef(null);
const onBackPress = useCallback(() => {
Alert.alert(
_('Save changes?'), _('This drawing may have unsaved changes.'), [
{
text: _('Discard changes'),
onPress: () => props.onCancel(),
style: 'destructive',
},
{
text: _('Save changes'),
onPress: () => {
// saveDrawing calls props.onSave(...) which may close the
// editor.
webviewRef.current.injectJS('saveDrawing();');
},
},
]
);
return true;
}, [webviewRef, props.onCancel]);
useEffect(() => {
BackHandler.addEventListener('hardwareBackPress', onBackPress);
return () => {
BackHandler.removeEventListener('hardwareBackPress', onBackPress);
};
}, [onBackPress]);
const css = useCss(editorTheme);
const html = useMemo(() => `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"/>
<style>
${css}
</style>
</head>
<body></body>
</html>
`, [css]);
const injectedJavaScript = useMemo(() => `
window.onerror = (message, source, lineno) => {
window.ReactNativeWebView.postMessage(
"error: " + message + " in file://" + source + ", line " + lineno
);
};
const saveDrawing = (isAutosave) => {
const img = window.editor.toSVG();
window.ReactNativeWebView.postMessage(
JSON.stringify({
action: isAutosave ? 'autosave' : 'save',
data: img.outerHTML,
}),
);
};
window.saveDrawing = saveDrawing;
try {
if (window.editor === undefined) {
${shim.injectedJs('svgEditorBundle')}
window.editor = svgEditorBundle.createJsDrawEditor();
window.initialSVGData = ${JSON.stringify(props.initialSVGData)};
if (initialSVGData && initialSVGData.length > 0) {
editor.loadFromSVG(initialSVGData);
}
const toolbar = editor.addToolbar();
toolbar.addActionButton({
label: ${JSON.stringify(_('Done'))},
icon: editor.icons.makeSaveIcon(),
}, () => {
saveDrawing(false);
});
svgEditorBundle.restoreToolbarState(
toolbar,
${JSON.stringify(Setting.value('imageeditor.jsdrawToolbar'))}
);
svgEditorBundle.listenToolbarState(editor, toolbar);
// Auto-save every four minutes.
const autoSaveInterval = 4 * 60 * 1000;
setInterval(() => {
saveDrawing(true);
}, autoSaveInterval);
}
} catch(e) {
window.ReactNativeWebView.postMessage(
'error: ' + e.message + ': ' + JSON.stringify(e)
);
}
true;
`, [props.initialSVGData]);
const onMessage = useCallback(async (event: WebViewMessageEvent) => {
const data = event.nativeEvent.data;
if (data.startsWith('error:')) {
console.error('ImageEditor:', data);
return;
}
const json = JSON.parse(data);
if (json.action === 'save') {
props.onSave(json.data);
} else if (json.action === 'autosave') {
const filePath = `${Setting.value('resourceDir')}/autosaved-drawing.joplin.svg`;
await shim.fsDriver().writeFile(filePath, json.data, 'utf8');
console.info('Auto-saved to %s', filePath);
} else if (json.action === 'save-toolbar') {
Setting.setValue('imageeditor.jsdrawToolbar', json.data);
} else {
console.error('Unknown action,', json.action);
}
}, [props.onSave]);
const onError = useCallback((event: any) => {
console.error('ImageEditor: WebView error: ', event);
}, []);
return (
<ExtendedWebView
themeId={props.themeId}
html={html}
injectedJavaScript={injectedJavaScript}
onMessage={onMessage}
onError={onError}
ref={webviewRef}
webviewInstanceId={'image-editor-js-draw'}
/>
);
};
export default ImageEditor;