-
-
Notifications
You must be signed in to change notification settings - Fork 301
Expand file tree
/
Copy pathrapidEditor.js
More file actions
296 lines (271 loc) · 9.9 KB
/
rapidEditor.js
File metadata and controls
296 lines (271 loc) · 9.9 KB
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
import { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import PropTypes from 'prop-types';
import { OSM_CLIENT_ID, OSM_REDIRECT_URI, OSM_SERVER_API_URL, OSM_SERVER_URL } from '../config';
import { types } from '../store/actions/editor';
// We import from a CDN using a SEMVER minor version range
import rapidPackage from '@rapideditor/rapid/package.json';
const baseCdnUrl = `https://cdn.jsdelivr.net/npm/${rapidPackage.name}@~${rapidPackage.version}/dist/`;
// We currently copy rapid files to the public/static/rapid directory. This should probably remain,
// since it can be useful for debugging rapid issues in the TM.
// const baseCdnUrl = '/static/rapid/';
/**
* Check if two URL search parameters are semantically equal
* @param {URLSearchParams} first
* @param {URLSearchParams} second
* @return {boolean} true if they are semantically equal
*/
function equalsUrlParameters(first, second) {
if (first.size === second.size) {
for (const [key, value] of first) {
if (!second.has(key) || second.get(key) !== value) {
return false;
}
}
return true;
}
return false;
}
/**
* Update the URL (this also fires a hashchange event)
* @param {URLSearchParams} hashParams the URL hash parameters
*/
function updateUrl(hashParams) {
const oldUrl = window.location.href;
const newUrl = window.location.pathname + window.location.search + '#' + hashParams.toString();
window.history.pushState(null, '', newUrl);
window.dispatchEvent(
new HashChangeEvent('hashchange', {
newUrl: newUrl,
oldUrl: oldUrl,
}),
);
}
/**
* Generate the starting hash for the project
* @param {string | undefined} comment The comment to use
* @param {Array.<String> | undefined} presets The presets
* @param {string | undefined} gpxUrl The task boundaries
* @param {boolean | undefined} powerUser if the user should be shown advanced options
* @param {string | undefined} imagery The imagery to use for the task
* @return {module:url.URLSearchParams | boolean} the new URL search params or {@code false} if no parameters changed
*/
function generateStartingHash({ comment, presets, gpxUrl, powerUser, imagery }) {
const hashParams = new URLSearchParams(window.location.hash.substring(1));
if (comment) {
hashParams.set('comment', comment);
}
if (gpxUrl) {
hashParams.set('data', gpxUrl);
}
if (powerUser !== undefined) {
hashParams.set('poweruser', powerUser.toString());
}
if (presets) {
hashParams.set('presets', presets.join(','));
}
if (imagery) {
if (imagery.startsWith('http')) {
hashParams.set('background', 'custom:' + imagery);
} else {
hashParams.set('background', imagery);
}
}
if (equalsUrlParameters(hashParams, new URLSearchParams(window.location.hash.substring(1)))) {
return false;
}
return hashParams;
}
/**
* Resize rapid
* @param {Context} rapidContext The rapid context to resize
* @type {import('@rapideditor/rapid').Context} Context
*/
function resizeRapid(rapidContext) {
// Get rid of black bars when toggling the TM sidebar
const uiSystem = rapidContext?.systems?.ui;
if (uiSystem?.started) {
uiSystem.resize();
}
}
/**
* Check if there are changes
* @param changes The changes to check
* @returns {boolean} {@code true} if there are changes
*/
function thereAreChanges(changes) {
return changes.modified.length || changes.created.length || changes.deleted.length;
}
/**
* Update the disable state for the sidebar map actions
* @param {function(boolean)} setDisable
* @param {EditSystem} editSystem The edit system
* @type {import('@rapideditor/rapid/modules').EditSystem} EditSystem
*/
function updateDisableState(setDisable, editSystem) {
if (thereAreChanges(editSystem.changes())) {
setDisable(true);
} else {
setDisable(false);
}
}
/**
* Create a new RapidEditor component
* @param {function(boolean)} setDisable
* @param {string} comment The default changeset comment
* @param {[string]|null|undefined} presets The presets to allow the user to use
* @param {string|null|undefined} imagery The imagery to default to for the user
* @param {string} gpxUrl The task boundary url
* @param {boolean} powerUser true if the user should be shown advanced options
* @param {boolean} showSidebar Changes are used to resize the Rapid mapview
* @returns {JSX.Element} The element to add to the DOM
* @constructor
*/
function RapidEditor({
setDisable,
comment,
presets,
imagery,
gpxUrl,
powerUser = false,
showSidebar = true,
}) {
const dispatch = useDispatch();
const session = useSelector((state) => state.auth.session);
const [rapidLoaded, setRapidLoaded] = useState(window.Rapid !== undefined);
const { context, dom } = useSelector((state) => state.editor.rapidContext);
const locale = useSelector((state) => state.preferences.locale);
const windowInit = typeof window !== 'undefined';
// This significantly reduces build time _and_ means different TM instances can share the same download of Rapid.
// Unfortunately, Rapid doesn't use a public CDN itself, so we cannot reuse that.
useEffect(() => {
if (!rapidLoaded && !context) {
// Add the style element
const style = document.createElement('link');
style.setAttribute('type', 'text/css');
style.setAttribute('rel', 'stylesheet');
style.setAttribute('href', baseCdnUrl + 'rapid.css');
document.head.appendChild(style);
// Now add the editor
const script = document.createElement('script');
script.src = baseCdnUrl + 'rapid.js';
script.async = true;
script.onload = () => setRapidLoaded(true);
document.body.appendChild(script);
} else if (context && !rapidLoaded) {
setRapidLoaded(true);
}
}, [rapidLoaded, setRapidLoaded, context]);
useEffect(() => {
return () => {
dispatch({ type: 'SET_VISIBILITY', isVisible: true });
};
});
useEffect(() => {
if (windowInit && context === null && rapidLoaded) {
/* This is used to avoid needing to re-initialize Rapid on every page load -- this can lead to jerky movements in the UI */
const dom = document.createElement('div');
dom.className = 'w-100 vh-minus-69-ns';
// we need to keep Rapid context on redux store because Rapid works better if
// the context is not restarted while running in the same browser session
// Unfortunately, we need to recreate the context every time we recreate the rapid-container dom node.
const context = new window.Rapid.Context();
context.embed(true);
context.containerNode = dom;
context.assetPath = baseCdnUrl;
context.apiConnections = [
{
url: OSM_SERVER_URL,
apiUrl: OSM_SERVER_API_URL,
client_id: OSM_CLIENT_ID,
redirect_uri: OSM_REDIRECT_URI,
},
];
dispatch({ type: types.SET_RAPIDEDITOR, context: { context, dom } });
}
}, [windowInit, rapidLoaded, context, dispatch]);
useEffect(() => {
if (context) {
// setup the context
context.locale = locale;
}
}, [context, locale]);
// This ensures that Rapid has the correct map size
useEffect(() => {
// This might be a _slight_ efficiency improvement by making certain that Rapid isn't painting unneeded items
resizeRapid(context);
// This is the only bit that is *really* needed -- it prevents black bars when hiding the sidebar.
return () => resizeRapid(context);
}, [showSidebar, context]);
useEffect(() => {
const newParams = generateStartingHash({ comment, presets, gpxUrl, powerUser, imagery });
if (newParams) {
updateUrl(newParams);
}
}, [comment, presets, gpxUrl, powerUser, imagery]);
useEffect(() => {
const containerRoot = document.getElementById('rapid-container-root');
const editListener = () => updateDisableState(setDisable, context.systems.editor);
if (context && dom) {
containerRoot.appendChild(dom);
// init the ui or restart if it was loaded previously
let promise;
if (context?.systems?.ui !== undefined) {
// Currently commented out in Rapid source code (2023-07-20)
// RapidContext.systems.ui.restart();
resizeRapid(context);
promise = Promise.resolve();
} else {
promise = context.initAsync();
}
/* Perform tasks after Rapid has started up */
promise.then(() => {
if (context?.systems?.editor) {
/* Keep track of edits */
const editSystem = context.systems.editor;
editSystem.on('stablechange', editListener);
editSystem.on('reset', editListener);
}
});
}
return () => {
if (containerRoot?.childNodes && dom in containerRoot.childNodes) {
document.getElementById('rapid-container-root')?.removeChild(dom);
}
if (context?.systems?.editor) {
const editSystem = context.systems.editor;
editSystem.off('stablechange', editListener);
editSystem.off('reset', editListener);
}
};
}, [dom, context, setDisable]);
useEffect(() => {
if (context?.systems?.editor) {
return () => context.systems.editor.saveBackup();
}
}, [context]);
useEffect(() => {
if (context && session) {
context.preauth = {
url: OSM_SERVER_URL,
apiUrl: OSM_SERVER_API_URL,
client_id: OSM_CLIENT_ID,
redirect_uri: OSM_REDIRECT_URI,
access_token: session.osm_oauth_token,
};
context.apiConnections = [context.preauth];
}
}, [context, session, session?.osm_oauth_token]);
return <div className="w-100 vh-minus-69-ns" id="rapid-container-root"></div>;
}
RapidEditor.propTypes = {
setDisable: PropTypes.func,
comment: PropTypes.string,
presets: PropTypes.array,
imagery: PropTypes.string,
gpxUrl: PropTypes.string.isRequired,
powerUser: PropTypes.bool.isRequired,
showSidebar: PropTypes.bool.isRequired,
};
export { RapidEditor, generateStartingHash, equalsUrlParameters, updateUrl };
export default RapidEditor;