@abi-software/flatmap-viewer 2.3.0-a.1 → 2.3.0-a.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.rst CHANGED
@@ -38,7 +38,7 @@ The map server endpoint is specified as ``MAP_ENDPOINT`` in ``src/main.js``. It
38
38
  Package Installation
39
39
  ====================
40
40
 
41
- * ``npm install @abi-software/flatmap-viewer@2.2.8``
41
+ * ``npm install @abi-software/flatmap-viewer@2.3.0-a.3``
42
42
 
43
43
  Documentation
44
44
  -------------
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@abi-software/flatmap-viewer",
3
- "version": "2.3.0-a.1",
3
+ "version": "2.3.0-a.3",
4
4
  "description": "Flatmap viewer using Maplibre GL",
5
5
  "repository": "https://github.com/AnatomicMaps/flatmap-viewer.git",
6
6
  "main": "src/main.js",
@@ -18,12 +18,15 @@
18
18
  "license": "MIT",
19
19
  "dependencies": {
20
20
  "@babel/runtime": "^7.10.4",
21
+ "@fortawesome/fontawesome-free": "^6.4.0",
21
22
  "@turf/area": "^6.0.1",
22
23
  "@turf/bbox": "^6.0.1",
23
24
  "@turf/helpers": "^6.1.4",
24
25
  "@turf/projection": "^6.5.0",
25
26
  "bezier-js": "^6.1.0",
26
- "maplibre-gl": ">=1.15.3",
27
+ "html-es6cape": "^2.0.2",
28
+ "jspanel4": "^4.16.1",
29
+ "maplibre-gl": ">=2.4.0",
27
30
  "minisearch": "^2.2.1",
28
31
  "polylabel": "^1.1.0"
29
32
  },
@@ -38,7 +41,7 @@
38
41
  "css-loader": "^6.5.1",
39
42
  "eslint": "^8.7.0",
40
43
  "express": "^4.17.1",
41
- "html-webpack-plugin": "^4.5.1",
44
+ "html-webpack-plugin": "^4.5.2",
42
45
  "strip-ansi": "^7.0.1",
43
46
  "style-loader": "^1.0.0",
44
47
  "url-loader": "^4.1.0",
@@ -0,0 +1,487 @@
1
+ /******************************************************************************
2
+
3
+ Flatmap viewer and annotation tool
4
+
5
+ Copyright (c) 2019 - 2023 David Brooks
6
+
7
+ Licensed under the Apache License, Version 2.0 (the "License");
8
+ you may not use this file except in compliance with the License.
9
+ You may obtain a copy of the License at
10
+
11
+ http://www.apache.org/licenses/LICENSE-2.0
12
+
13
+ Unless required by applicable law or agreed to in writing, software
14
+ distributed under the License is distributed on an "AS IS" BASIS,
15
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ See the License for the specific language governing permissions and
17
+ limitations under the License.
18
+
19
+ ******************************************************************************/
20
+
21
+ 'use strict';
22
+
23
+ //==============================================================================
24
+
25
+ // We use Font Awesome icons
26
+ import '@fortawesome/fontawesome-free/css/all.css';
27
+ import escape from 'html-es6cape';
28
+ import { jsPanel } from 'jspanel4';
29
+ import 'jspanel4/dist/jspanel.css';
30
+
31
+ //==============================================================================
32
+
33
+ const FETCH_TIMEOUT = 3000; // 3 seconds
34
+ const UPDATE_TIMEOUT = 5000; // 5 seconds
35
+ const LOGIN_TIMEOUT = 30000; // 30 seconds
36
+ const LOGOUT_TIMEOUT = 5000; // 5 seconds
37
+
38
+ const STATUS_MESSAGE_TIMEOUT = 3000;
39
+
40
+ //==============================================================================
41
+
42
+ const FEATURE_DISPLAY_PROPERTIES = {
43
+ 'id': 'Feature',
44
+ 'label': 'Tooltip',
45
+ 'models': 'Models',
46
+ 'name': 'Name',
47
+ 'sckan': 'SCKAN valid',
48
+ 'fc-class': 'FC class',
49
+ 'fc-kind': 'FC kind',
50
+ 'layer': 'Map layer',
51
+ }
52
+
53
+ const ANNOTATION_FIELDS = [
54
+ {
55
+ prompt: 'Feature derived from',
56
+ key: 'prov:wasDerivedFrom',
57
+ update: true,
58
+ kind: 'list',
59
+ size: 6
60
+ },
61
+ {
62
+ prompt: 'Comment',
63
+ key: 'rdfs:comment',
64
+ update: false,
65
+ kind: 'textbox'
66
+ },
67
+ ];
68
+
69
+ //==============================================================================
70
+
71
+ export class Annotator
72
+ {
73
+ constructor(flatmap)
74
+ {
75
+ this.__flatmap = flatmap;
76
+ this.__haveAnnotation = false;
77
+ this.__user = undefined;
78
+ this.__savedStatusMessage = '';
79
+ this.__authorised = false;
80
+ }
81
+
82
+ get user()
83
+ {
84
+ return this.__user;
85
+ }
86
+
87
+ __creatorName(creator)
88
+ {
89
+ return creator.name || creator.email || creator.login || creator.company || creator;
90
+ }
91
+
92
+ __setUser(creator)
93
+ {
94
+ this.__user = creator;
95
+ this.__setStatusMessage(`Annotating as ${this.__creatorName(creator)}`, 0)
96
+ }
97
+
98
+ __clearUser()
99
+ {
100
+ this.__user = undefined;
101
+ this.__setStatusMessage('', 0);
102
+ }
103
+
104
+ __authorise(panel, callback)
105
+ //==========================
106
+ {
107
+ const abortController = new AbortController();
108
+ const url = `${this.__flatmap._baseUrl}login`;
109
+ panel.headerlogo.innerHTML = '<span class="fa fa-spinner fa-spin ml-2"></span>';
110
+ fetch(url, {
111
+ headers: { "Content-Type": "application/json; charset=utf-8" },
112
+ signal: abortController.signal
113
+ }).then((response) => {
114
+ panel.headerlogo.innerHTML = '';
115
+ if (response.ok) {
116
+ const creator = response.json();
117
+ if ('error' in creator) {
118
+ callback({error: creator.error});
119
+ } else {
120
+ this.__setUser(creator);
121
+ this.__authorised = true;
122
+ callback(creator);
123
+ }
124
+ } else {
125
+ callback({error: `${response.status} ${response.statusText}`});
126
+ }
127
+ });
128
+ setTimeout((panel) => {
129
+ if (this.user === 'undefined') {
130
+ console.log("Aborting login...");
131
+ abortController.abort();
132
+ panel.headerlogo.innerHTML = '';
133
+ this.__setStatusMessage('Unable to login...');
134
+ }
135
+ },
136
+ LOGIN_TIMEOUT, panel);
137
+ }
138
+
139
+ __unauthorise()
140
+ //=============
141
+ {
142
+ this.__clearUser();
143
+ const abortController = new AbortController();
144
+ const url = `${this.__flatmap._baseUrl}logout`;
145
+ fetch(url, {
146
+ headers: { "Content-Type": "application/json; charset=utf-8" },
147
+ signal: abortController.signal
148
+ }).then((response) => {
149
+ if (response.ok) {
150
+ this.__authorised = false;
151
+ console.log('Annotator logout:', response.json());
152
+ } else {
153
+ console.log('Annotator logout:', `${response.status} ${response.statusText}`);
154
+ }
155
+ });
156
+ setTimeout(() => {
157
+ if (this.__authorised) {
158
+ console.log("Aborting logout...");
159
+ abortController.abort();
160
+ this.__setStatusMessage('Unable to logout...');
161
+ }
162
+ },
163
+ LOGOUT_TIMEOUT);
164
+ }
165
+
166
+ __setStatusMessage(message, timeout=STATUS_MESSAGE_TIMEOUT)
167
+ //=========================================================
168
+ {
169
+ if (timeout == 0) {
170
+ this.__savedStatusMessage = message;
171
+ }
172
+ this.__statusMessage.innerHTML = message;
173
+ if (+timeout > 0) {
174
+ setTimeout(() => {
175
+ this.__statusMessage.innerHTML = this.__savedStatusMessage;
176
+ }, +timeout);
177
+ }
178
+ }
179
+
180
+ __featureHtml(featureProperties)
181
+ //==============================
182
+ {
183
+ // Feature properties
184
+ const html = [];
185
+ for (const [key, prompt] of Object.entries(FEATURE_DISPLAY_PROPERTIES)) {
186
+ const value = featureProperties[key];
187
+ if (value !== undefined && value !== '') {
188
+ const escapedValue = escape(value).replaceAll('\n', '<br/>');
189
+ html.push(`<div><span class="flatmap-annotation-prompt">${prompt}:</span><span class="flatmap-annotation-value">${escapedValue}</span></div>`)
190
+ }
191
+ }
192
+ return html;
193
+ }
194
+
195
+ __annotationHtml(annotations)
196
+ //===========================
197
+ {
198
+ const html = [];
199
+ let firstBlock = true;
200
+ for (const annotation of annotations) {
201
+ if (firstBlock) {
202
+ firstBlock = false;
203
+ } else {
204
+ html.push('<hr/>')
205
+ }
206
+ if (annotation['rdf:type'] === 'prov:Entity') {
207
+ const annotator = this.__creatorName(annotation['dct:creator']);
208
+ html.push(`<div><span class="flatmap-annotation-prompt">${annotation['dct:created']}</span><span class="flatmap-annotation-value">${annotator}</span></div>`);
209
+ for (const field of ANNOTATION_FIELDS) {
210
+ const value = annotation[field.key];
211
+ if (value !== undefined && value !== '') {
212
+ const escapedValue = (field.kind === 'list')
213
+ ? value.filter(v => v.trim()).map(v => escape(v.trim())).join(', ')
214
+ : escape(value).replaceAll('\n', '<br/>');
215
+ html.push(`<div><span class="flatmap-annotation-prompt">${field.prompt}:</span><span class="flatmap-annotation-value">${escapedValue}</span></div>`);
216
+ }
217
+ }
218
+ }
219
+ }
220
+ return html.join('\n');
221
+ }
222
+
223
+ __editFormHtml(annotation)
224
+ //========================
225
+ {
226
+ const html = [];
227
+ html.push('<div id="flatmap-annotation-formdata">');
228
+ for (const field of ANNOTATION_FIELDS) {
229
+ html.push('<div class="flatmap-annotation-entry">');
230
+ html.push(` <label for="${field.key}">${field.prompt}:</label>`);
231
+ const value = field.update ? annotation[field.key] || '' : '';
232
+ if (field.kind === 'textbox') {
233
+ html.push(` <textarea rows="5" cols="40" id="${field.key}" name="${field.key}">${value.trim()}</textarea>`)
234
+ } else if (!('kind' in field) || field.kind !== 'list') {
235
+ html.push(` <input type="text" size="40" id="${field.key}" name="${field.key}" value="${value.trim()}"/>`)
236
+ } else { // field.kind === 'list'
237
+ html.push(' <div class="multiple">')
238
+ for (let n = 1; n <= field.size; n++) {
239
+ const fieldValue = (n <= value.length) ? value[n-1].trim() : '';
240
+ html.push(` <input type="text" size="40" id="${field.key}_${n}" name="${field.key}" value="${fieldValue}"/>`)
241
+ }
242
+ html.push(' </div>')
243
+ }
244
+ html.push('</div>');
245
+ }
246
+ html.push(' <div><input id="annotation-save-button" type="button" value="Save"/></div>');
247
+ html.push('</div>');
248
+ return html.join('\n');
249
+ }
250
+
251
+ __changedAnnotation(lastAnnotation)
252
+ //=================================
253
+ {
254
+ const newProperties = {};
255
+ let propertiesChanged = false;
256
+ for (const field of ANNOTATION_FIELDS) {
257
+ const lastValue = field.update ? lastAnnotation[field.key] || '' : '';
258
+ if (!('kind' in field) || field.kind !== 'list') {
259
+ const inputField = document.getElementById(field.key);
260
+ newProperties[field.key] = inputField.value.trim();
261
+ if (!propertiesChanged && newProperties[field.key] !== lastValue.trim()) {
262
+ propertiesChanged = true;
263
+ }
264
+ } else { // field.kind === 'list'
265
+ newProperties[field.key] = [];
266
+ const changedList = false;
267
+ for (let n = 1; n <= field.size; n++) {
268
+ const lastListValue = (n <= lastValue.length) ? lastValue[n-1].trim() : '';
269
+ const inputField = document.getElementById(`${field.key}_${n}`);
270
+ const newListValue = inputField.value.trim();
271
+ newProperties[field.key].push(newListValue);
272
+ if (!propertiesChanged && newListValue !== lastListValue) {
273
+ propertiesChanged = true;
274
+ }
275
+ }
276
+ }
277
+ }
278
+ return {
279
+ changed: propertiesChanged,
280
+ properties: newProperties
281
+ }
282
+ }
283
+
284
+ __updateRemoteAnnotation(annotation, callback)
285
+ //============================================
286
+ {
287
+ const abortController = new AbortController();
288
+ const url = this.__flatmap.addBaseUrl_(`/annotations/${this.__currentFeatureId}`);
289
+ fetch(url, {
290
+ headers: { "Content-Type": "application/json; charset=utf-8" },
291
+ method: 'POST',
292
+ body: JSON.stringify(annotation),
293
+ signal: abortController.signal
294
+ }).then((response) => {
295
+ if (response.ok) {
296
+ callback(response.json());
297
+ } else {
298
+ callback({error: `${response.status} ${response.statusText}`});
299
+ }
300
+ });
301
+ return abortController;
302
+ }
303
+
304
+ __saveAnnotation(panel, lastAnnotation)
305
+ //=====================================
306
+ {
307
+ const changedProperties = this.__changedAnnotation(lastAnnotation);
308
+ if (this.__currentFeatureId !== undefined && changedProperties.changed) {
309
+ const annotation = {
310
+ ...changedProperties.properties,
311
+ 'rdf:type': 'prov:Entity',
312
+ 'dct:subject': `flatmaps:${this.__flatmap.uuid}/${this.__currentFeatureId}`,
313
+ 'dct:creator': this.user
314
+ }
315
+ panel.headerlogo.innerHTML = '<span class="fa fa-spinner fa-spin ml-2"></span>';
316
+ const remoteUpdate = this.__updateRemoteAnnotation(annotation,
317
+ (response) => {
318
+ if ('error' in response) {
319
+ panel.headerlogo.innerHTML = response.error;
320
+ } else {
321
+ panel.headerlogo.innerHTML = '';
322
+ panel.close();
323
+ }
324
+ });
325
+ setTimeout((panel) => {
326
+ if (panel.status !== 'closed') {
327
+ console.log("Aborting remote update...");
328
+ remoteUpdate.abort();
329
+ panel.headerlogo.innerHTML = '';
330
+ this.__setStatusMessage('Cannot update annotation...');
331
+ }
332
+ }, UPDATE_TIMEOUT, panel);
333
+ } else {
334
+ this.__
335
+ this.__setStatusMessage('No changes to save...');
336
+ }
337
+ }
338
+
339
+ __finishPanelContent(panel, response)
340
+ //====================================
341
+ {
342
+ this.__haveAnnotation = true;
343
+ this.__existingAnnotation.innerHTML = this.__annotationHtml(response);
344
+ const lastAnnotation = response.length ? response[0] : {};
345
+ this.__annotationForm.innerHTML = this.__editFormHtml(lastAnnotation);
346
+
347
+ // Lock focus to focusable elements within the panel
348
+ const inputElements = panel.content.querySelectorAll('input, textarea, button');
349
+ this.__firstInputField = inputElements[0];
350
+ const lastInput = inputElements[inputElements.length - 1];
351
+ const saveButton = document.getElementById('annotation-save-button');
352
+
353
+ panel.addEventListener('keydown', function (e) {
354
+ if (e.key === 'Tab') {
355
+ if ( e.shiftKey ) /* shift + tab */ {
356
+ if (document.activeElement === this.__firstInputField) {
357
+ lastInput.focus();
358
+ e.preventDefault();
359
+ }
360
+ } else /* tab */ {
361
+ if (document.activeElement === lastInput) {
362
+ this.__firstInputField.focus();
363
+ e.preventDefault();
364
+ }
365
+ }
366
+ } else if (e.key === 'Enter') {
367
+ if (e.target === saveButton) {
368
+ this.__saveAnnotation(panel, lastAnnotation);
369
+ }
370
+ }
371
+ }.bind(this));
372
+
373
+ saveButton.addEventListener('mousedown', function (e) {
374
+ this.__saveAnnotation(panel, lastAnnotation);
375
+ }.bind(this));
376
+ }
377
+
378
+ annotate(feature, closedCallback)
379
+ //===============================
380
+ {
381
+ this.__currentFeatureId = feature.properties['id']
382
+
383
+ if (this.__currentFeatureId === undefined) {
384
+ closedCallback();
385
+ return;
386
+ }
387
+
388
+ const panelContent = [];
389
+ panelContent.push('<div id="flatmap-annotation-panel">');
390
+ panelContent.push(' <div id="flatmap-annotation-feature">');
391
+ panelContent.push(...this.__featureHtml(feature.properties));
392
+ panelContent.push(' </div>');
393
+ panelContent.push(' <form id="flatmap-annotation-form"></form>');
394
+ panelContent.push(' <div id="flatmap-annotation-existing"></div>');
395
+ panelContent.push('</div>');
396
+
397
+ const annotator = this; // To use in panel code
398
+ const flatmap = this.__flatmap; // To use in panel code
399
+ const contentFetchAbort = new AbortController();
400
+ this.__panel = jsPanel.create({
401
+ theme: 'light',
402
+ border: '2px solid #080',
403
+ borderRadius: '.5rem',
404
+ panelSize: '725px auto',
405
+ position: 'left-top',
406
+ data: {
407
+ flatmap: this.__flatmap
408
+ },
409
+ content: panelContent.join('\n'),
410
+ closeOnEscape: true,
411
+ closeOnBackdrop: false,
412
+ headerTitle: 'Feature annotations',
413
+ headerControls: 'closeonly xs',
414
+ footerToolbar: [
415
+ '<span id="flatmap-annotation-status" class="flex-auto"></span>',
416
+ '<span id="flatmap-annotation-lock" class="jsPanel-ftr-btn fa fa-lock"></span>',
417
+ ],
418
+ contentFetch: {
419
+ resource: flatmap.addBaseUrl_(`/annotations/${this.__currentFeatureId}`),
420
+ fetchInit: {
421
+ method: 'GET',
422
+ mode: 'cors',
423
+ headers: {
424
+ "Accept": "application/json; charset=utf-8",
425
+ "Cache-Control": "no-store"
426
+ },
427
+ signal: contentFetchAbort.signal
428
+ },
429
+ bodyMethod: 'json',
430
+ beforeSend: (fetchConfig, panel) => {
431
+ panel.headerlogo.innerHTML = '<span class="fa fa-spinner fa-spin ml-2"></span>';
432
+ setTimeout((panel) => {
433
+ if (!annotator.__haveAnnotation) {
434
+ console.log("Aborting content fetch...");
435
+ contentFetchAbort.abort();
436
+ panel.headerlogo.innerHTML = '';
437
+ annotator.__setStatusMessage('Cannot fetch annotation...');
438
+ annotator.__authoriseLock.className = '';
439
+ }
440
+ }, FETCH_TIMEOUT, panel);
441
+ },
442
+ done: (response, panel) => {
443
+ annotator.__finishPanelContent(panel, response);
444
+ panel.headerlogo.innerHTML = '';
445
+ }
446
+ },
447
+ callback: (panel) => {
448
+ annotator.__annotationForm = document.getElementById('flatmap-annotation-form');
449
+ // Data entry only once authorised
450
+ annotator.__annotationForm.hidden = true;
451
+
452
+ // Populate once we have content from server
453
+ annotator.__existingAnnotation = document.getElementById('flatmap-annotation-existing');
454
+ annotator.__statusMessage = document.getElementById('flatmap-annotation-status');
455
+
456
+ annotator.__authoriseLock = document.getElementById('flatmap-annotation-lock');
457
+ annotator.__authoriseLock.addEventListener('click', (e) => {
458
+ const lockClasses = annotator.__authoriseLock.classList;
459
+ if (lockClasses.contains('fa-lock')) {
460
+ annotator.__authorise(panel, (response) => {
461
+ if ('error' in response) {
462
+ annotator.__setStatusMessage(response.error);
463
+ } else {
464
+ annotator.__annotationForm.hidden = false;
465
+ annotator.__firstInputField.focus();
466
+ lockClasses.remove('fa-lock');
467
+ lockClasses.add('fa-unlock');
468
+ }
469
+ });
470
+ } else {
471
+ annotator.__unauthorise();
472
+ annotator.__annotationForm.hidden = true;
473
+ lockClasses.remove('fa-unlock');
474
+ lockClasses.add('fa-lock');
475
+ }
476
+ });
477
+
478
+ // should we warn if unsaved changes when closing??
479
+ document.addEventListener('jspanelclosed', closedCallback, false);
480
+ }
481
+ });
482
+
483
+ }
484
+
485
+ }
486
+
487
+ //==============================================================================