-
Notifications
You must be signed in to change notification settings - Fork 416
/
Copy pathGeoStoryUtils.js
675 lines (639 loc) · 21.3 KB
/
GeoStoryUtils.js
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
/*
* Copyright 2019, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* Utils for geostory
*/
import get from "lodash/get";
import findIndex from "lodash/findIndex";
import toPath from "lodash/toPath";
import isArray from "lodash/isArray";
import values from "lodash/values";
import filter from "lodash/filter";
import merge from "lodash/merge";
import isString from "lodash/isString";
import isObject from "lodash/isObject";
import includes from "lodash/includes";
import replace from 'lodash/replace';
import uuid from 'uuid';
export const EMPTY_CONTENT = "EMPTY_CONTENT";
// Allowed StoryTypes
export const StoryTypes = {
CASCADE: 'cascade'
};
// Allowed types
export const SectionTypes = {
TITLE: 'title',
PARAGRAPH: 'paragraph',
IMMERSIVE: 'immersive',
BANNER: 'banner',
CAROUSEL: 'carousel'
};
/**
* Allowed contents
*/
export const ContentTypes = {
TEXT: 'text',
MEDIA: 'media',
WEBPAGE: 'webPage',
COLUMN: 'column' // can have contents of type 'text' or 'media'
};
// Templates for contents that can be created using getDefaultSectionTemplate
export const SectionTemplates = {
MEDIA: 'template-media',
WEBPAGE: 'template-web-page'
};
export const MediaTypes = {
IMAGE: 'image',
MAP: 'map',
VIDEO: 'video'
};
export const Modes = {
EDIT: 'edit',
VIEW: 'view'
};
export const Controls = {
SHOW_SAVE: 'save.show',
SHOW_DELETE: 'delete.show',
LOADING: 'loading'
};
export const lists = {
StoryTypes: values(StoryTypes),
SectionTypes: values(SectionTypes),
MediaTypes: values(MediaTypes),
Modes: values(Modes)
};
/**
* Return a class name from props of a content
* @prop {object} theme theme object
* @prop {string} theme.value one of 'bright', 'dark', 'dark-transparent' or 'bright-transparent'
* @prop {string} align one of 'center', 'left' or 'right'
* @prop {string} size one of 'full', 'large', 'medium', 'small' or 'h-{size},v-{size}'
*/
export const getClassNameFromProps = ({ theme = {}, align = 'center', size = 'full' }) => {
const themeValue = theme?.value || isString(theme) && theme;
const themeClassName = themeValue && themeValue !== 'custom' && isString(themeValue) && ` ms-${themeValue}` || '';
const alignClassName = ` ms-align-${align}`;
const sizeClassName = size.split(',').map(sClass=> ` ms-size-${sClass}`).join(''); // when size has both horizontal and vertical classes
return `${themeClassName}${alignClassName}${sizeClassName}`;
};
/**
* Return a theme style props of a content and background
* @prop {object} theme one of 'bright', 'dark', 'dark-transparent' or 'bright-transparent'
* @prop {string} theme.value style key
* @prop {string} theme[theme.value] a style object referred to the style key
*/
export const getThemeStyleFromProps = ({ theme = {}, storyTheme }) => {
if (
theme === ''
|| theme?.value === ''
) {
return isObject(storyTheme) ? storyTheme : {};
}
const styleKey = theme?.value;
const style = theme?.[styleKey];
return isObject(style) && style || {};
};
/**
* tells if an element is a paragraph and it contains a media
* @param {object} element
* @return {boolean}
*/
export const isMediaSection = (element) => element.type === SectionTypes.PARAGRAPH &&
element &&
isArray(element.contents) &&
element.contents.length &&
isArray(element.contents[0].contents) &&
element.contents[0].contents.length &&
element.contents[0].contents[0].type === ContentTypes.MEDIA;
/**
* cleans the id in case it has any get parameters attached at the end
* @param {string} id id of the dom element
* @return {string}
*/
export const onCleanId = (id) => {
const splitId = id.split('?');
return splitId.length === 2 ? splitId[0] : id;
};
/**
* utility function that scrolls the view to the element
* @param {string} id id of the dom element
* @param {object|boolean} scrollOptions options used to the scroll action
* @see https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
*/
export const scrollToContent = (id, scrollOptions) => {
const cleanId = onCleanId(id);
const element = document.getElementById(cleanId);
if (element) {
element.scrollIntoView(scrollOptions);
}
};
export const DEFAULT_MAP_OPTIONS = {
zoomControl: true,
mapInfoControl: false,
mapOptions: {
// leaflet
scrollWheelZoom: false,
interactions: {
// openlayers
mouseWheelZoom: false,
dragPan: true
}
}
};
/**
* generate map defaults
* @param {object} options to merge with defaults
* @return {object} options merged with defaults
*/
export const applyDefaults = (options = {}) => merge({}, DEFAULT_MAP_OPTIONS, options);
/**
* create map object
* @param {object} baseMap initial map object
* @param {object} overrides object to override with
* @return {object} options merged with defaults
*/
export const createMapObject = (baseMap = {}, overrides = {}) => {
return merge({}, baseMap, overrides);
};
/**
* check if a string matches a regex
* @param {string} title string to test
* @param {string} filterText used to generate regex
* @param {RegExp} [regex] used to test input string, default it uses the filterText
* @return {boolean} true if it matches, false otherwise
*/
export const testRegex = (title, filterText, regex = RegExp(filterText, "i")) => {
return filterText ? regex.test(title) : true;
};
/**
* filter resources based on their title (name in case of missing title), description and a filter string
* @param {object[]} resources resources to filter
* @param {string} filterText string used to generate regex
* @param {RegExp} [regex] regex used to test input string, default it uses the filterText
* @return {object[]} filtered resources
*/
export const filterResources = (resources = [], filterText, regex = RegExp(filterText, "i") ) => {
return filter(resources, r => testRegex(r.data && (r.data.title || r.data.name), filterText, regex) || testRegex(r.data && r.data.description, filterText, regex));
};
/**
* Creates a default template for the given type
* @param {string} type can be section type, a content type or a template (custom. i.e. paragraph with initial image for add media)
* @param {function/string} localize localization function or localized string
* @return {object} the template object of the content/section
*/
export const getDefaultSectionTemplate = (type, localize = v => v) => {
switch (type) {
case SectionTypes.TITLE:
return {
id: uuid(),
type: SectionTypes.TITLE,
title: localize("geostory.builder.defaults.titleTitle"),
cover: false,
contents: [
{
id: uuid(),
type: ContentTypes.TEXT,
html: '',
size: 'large',
align: 'center',
theme: '',
background: {
fit: 'cover',
size: 'full',
align: 'center'
}
}
]
};
case SectionTypes.BANNER:
return {
id: uuid(),
type: SectionTypes.BANNER,
title: localize("geostory.builder.defaults.titleBanner"),
cover: false,
contents: [{
id: uuid(),
background: {
fit: 'cover',
size: 'full',
align: 'center'
}
}]
};
case SectionTypes.PARAGRAPH:
return {
id: uuid(),
type: SectionTypes.PARAGRAPH,
title: localize("geostory.builder.defaults.titleParagraph"),
contents: [
{
id: uuid(),
type: ContentTypes.COLUMN,
size: 'full',
align: 'center',
contents: [{
id: uuid(),
type: ContentTypes.TEXT,
html: ''
}]
}
]
};
case SectionTypes.IMMERSIVE:
return {
id: uuid(),
type: SectionTypes.IMMERSIVE,
title: localize("geostory.builder.defaults.titleImmersive"),
contents: [getDefaultSectionTemplate(ContentTypes.COLUMN, localize("geostory.builder.defaults.titleImmersiveContent"))]
};
case SectionTypes.CAROUSEL:
return {
id: uuid(),
type,
title: localize("geostory.builder.defaults.titleGeocarousel"),
template: type,
background: {
fit: 'cover',
size: 'full',
align: 'center'
},
contents: [getDefaultSectionTemplate(ContentTypes.COLUMN, localize("geostory.builder.defaults.titleGeocarouselContent"))]
};
case SectionTemplates.MEDIA: {
return {
id: uuid(),
type: SectionTypes.PARAGRAPH,
title: localize("geostory.builder.defaults.titleMedia"),
contents: [
{
id: uuid(),
type: ContentTypes.COLUMN,
contents: [{
id: uuid(),
type: ContentTypes.MEDIA,
size: 'large',
align: 'center'
}]
}
]
};
}
case SectionTemplates.WEBPAGE: {
return {
id: uuid(),
type: SectionTypes.PARAGRAPH,
title: localize("geostory.builder.defaults.titleWebPageSection"),
contents: [
{
id: uuid(),
type: ContentTypes.COLUMN,
contents: [{
id: uuid(),
type: ContentTypes.WEBPAGE,
size: 'h-medium,v-medium', // Webpage has both horizontal and vertical size button
align: 'center'
}]
}
]
};
}
case ContentTypes.COLUMN: {
return {
id: uuid(),
type: ContentTypes.COLUMN,
align: 'left',
size: 'small',
theme: '',
title: localize,
contents: [{
id: uuid(),
type: ContentTypes.TEXT,
html: ''
}],
background: {
fit: 'cover',
size: 'full',
align: 'center'
}
};
}
case ContentTypes.TEXT: {
return {
id: uuid(),
type: ContentTypes.TEXT,
title: localize("geostory.builder.defaults.titleText"),
html: ''
};
}
case ContentTypes.IMAGE: {
return {
id: uuid(),
type,
title: localize("geostory.builder.defaults.titleMedia"),
size: 'full',
align: 'center'
};
}
case ContentTypes.WEBPAGE: {
return {
id: uuid(),
type,
title: localize("geostory.builder.defaults.titleWebPage"),
size: 'h-full,v-medium',
align: 'center'
};
}
case ContentTypes.MEDIA: {
return {
id: uuid(),
type,
title: localize("geostory.builder.defaults.titleUnknown"),
size: 'large',
align: 'center'
};
}
default:
return {
id: uuid(),
type,
title: localize("geostory.builder.defaults.titleUnknown"),
size: 'full',
align: 'center'
};
}
};
/**
* transforms the path with into a path with predicates into a path with array indexes
* @private
* @param {string|string[]} rawPath path to transform in real path
* @param {object} state the state to check to inspect the tree and get the real path
*/
export const getEffectivePath = (rawPath, state) => {
const rawPathArray = toPath(rawPath); // converts `a.b['section'].c[{"a":"b"}]` into `["a","b","section","c","{\"a\":\"b\"}"]`
// use curly brackets elements as predicates of findIndex to get the correct index.
return rawPathArray.reduce( (path, current) => {
if (current && current.indexOf('{') === 0) {
const predicate = JSON.parse(current);
const currentArray = get(state, path);
const index = findIndex(
currentArray,
predicate
);
if (index >= 0) {
return [...path, index];
}
// if the predicate is not found, it will ignore the unknown part
return path;
}
return [...path, current];
}, []);
};
/**
* transforms the path with predicates into a path with id
* @private
* @param {string|string[]} rawPath path to transform in real path
* @param {object} state the state to check to inspect the tree and get the real path
*/
export const getFlatPath = (rawPath, state) => {
const rawPathArray = toPath(rawPath); // converts `a.b['section'].c[{"a":"b"}]` into `["a","b","section","c","{\"a\":\"b\"}"]`
// use curly brackets elements as predicates of findIndex to get the correct index.
return rawPathArray.reduce( ({path, flatPath}, current) => {
if (current && current.indexOf('{') === 0) {
const predicate = JSON.parse(current);
const currentArray = get(state, path);
const index = findIndex(
currentArray,
predicate
);
if (index >= 0) {
const {id, type} = currentArray[index];
return {path: [...path, index], flatPath: [...flatPath, {id, type: path[path.length - 1], contentType: type}]};
}
// if the predicate is not found, it will ignore the unknown part
return {path, flatPath};
}
return {path: [...path, current], flatPath};
}, {path: [], flatPath: []});
};
/** finding section id from a give column id (immersive content)
* @param {object[]} immSections sections to loop on
* @param {*} columnId to use to find its section parent
*/
export const findSectionIdFromColumnId = (immSections, columnId) => {
return immSections.reduce((p, c) => {
if (includes(c.contents.map(cont => cont.id), columnId)) {
return c.id;
}
return p;
}, null);
};
/**
* tells if an element is a paragraph and it contains a WebPage component
* @param {object} element
* @return {boolean}
*/
export const isWebPageSection = (element) =>
element.type === SectionTypes.PARAGRAPH &&
element.editURL !== false &&
element &&
isArray(element.contents) &&
element.contents.length &&
isArray(element.contents[0].contents) &&
element.contents[0].contents.length &&
element.contents[0].contents[0].type === ContentTypes.WEBPAGE &&
element.contents[0].contents[0].editURL !== false;
/**
* computes container height based on object size
* @param {string} size - size of element
* @param {number} viewHeight - height of viewport
*/
export const getWebPageComponentHeight = (size, viewHeight) => {
if (viewHeight) {
switch (size) {
case 'small':
return viewHeight * 0.4;
case 'medium':
return viewHeight * 0.6;
case 'large':
return viewHeight * 0.8;
default:
return viewHeight;
}
}
return 0;
};
export const parseHashUrlScrollUpdate = (url, hash = '', storyId, sectionId, columnId) => {
const EMPTY = 'EMPTY';
if (!hash.includes(storyId)) {
return null;
}
const storyIds = hash.substring(hash.indexOf(storyId)).split('/');
if (sectionId && storyId) {
if (storyIds.length > 1 && storyIds[2] && Number(storyIds[0]) === storyId) {
if (storyIds.length === 5) {
return replace(url, `${storyIds[2]}/column/${storyIds[4]}`, `${sectionId}`);
}
return replace(url, `${storyIds[2]}`, `${sectionId}`);
}
if (hash.includes('shared')) {
return storyIds[1] !== '' ? `${url}/section/${sectionId}` : `${url}section/${sectionId}`;
}
return storyIds[1] !== '' ? `${url}/section/${sectionId}` : `${url}section/${sectionId}`;
} else if (!sectionId && columnId && isString(columnId) && columnId !== EMPTY) {
if (storyIds.length > 1) {
if (hash.includes('shared') && !storyIds[2]) {
return url;
}
if (storyIds.length === 5) {
return replace(url, `${storyIds[4]}`, `${columnId}`);
}
return `${url}/column/${columnId}`;
}
}
return null;
};
/**
* Creates a configuration from localConfig object to be used by the webfontloader library
* @param {array} fontFamilies - font families configured from localConfig
* @param {function} activeCallback - call back function to run when fonts are successfully loaded
* @param {function} inactiveCallback - call back function to run when font loading fails
*/
export const createWebFontLoaderConfig = (fontFamilies, activeCallback, inactiveCallback) => {
const config = {
active: activeCallback,
inactive: inactiveCallback,
custom: {
families: [],
urls: []
}
};
// first filter out those without a src property
fontFamilies.filter((family) => !!family.src)
.forEach((family, i) => {
config.custom.families[i] = family.family;
config.custom.urls[i] = family.src;
});
return config;
};
/**
* Creates an array with just font family names from an object
* @param {array} fontFamilies - an array of font families i.e [{"name": "fontName", "src": "fontSrc"}]
* @return {array} - array of font family names
*/
export const extractFontNames = (fontFamilies) => {
return fontFamilies.map(family => family.family);
};
export const DEFAULT_FONT_FAMILIES = [
'inherit',
'Arial',
'Georgia',
'Impact',
'Tahoma',
'Times New Roman',
'Verdana'
];
/**
* Get current mode of the geostory launched based on the url
* @return {string} - mode of the geostory
*/
export const getGeostoryMode = () => {
return window.location.href.match('geostory-embedded')
? 'geostoryEmbedded'
: 'geostory';
};
/**
* Get content and section Id from the path
* @param {string} path
* @return {object} {sectionId, contentId, innerContentId}
*/
export const getIdFromPath = (path) => {
const getId = (_path) => {
try {
return JSON.parse(_path)?.id;
} catch {
return null;
}
};
const pathArray = toPath(path) || [];
// Returns null when not an id
return {
sectionId: getId(pathArray?.[1]),
contentId: getId(pathArray?.[3]),
innerContentId: getId(pathArray?.[5])
};
};
/**
* Update carousel section content
* @param {array} resources
* @param {array} sections
* @param {object} action
* @param {string} mode
* @return {array} updated sections
*/
export const updateGeoCarouselSections = (sections = [], action) => {
return sections.map(_section=> {
if (action.sectionId === _section.id) {
return {..._section,
contents: (_section.contents || []).map(content=> ({
...content,
hideContent: content.id !== action.showContentId
}))
};
}
return _section;
});
};
/**
* Create a vector layer based on content's features
* @param {string} id id of section
* @param {array} contents array of content objects
* @param {function} featureStyle a function to generate a feature style ({ content, feature }, idx) => ({ })
* @param {object} layerOptions additional layer option for a vector layer
*/
export function getVectorLayerFromContents({
id,
contents,
featureStyle,
layerOptions
}) {
return {
visibility: true,
handleClickOnLayer: true,
...layerOptions,
id: `geostory-vector-${id}`,
name: `geostory-vector-${id}`,
type: 'vector',
features: contents.reduce((acc, content, idx) => [
...acc, ...(
(content?.features || [])
.map((feature) => ({
...feature,
properties: {
...feature.properties,
title: content.title,
sectionId: id,
contentId: content.id
},
contentRefId: content.id,
...(featureStyle && {
style: featureStyle({ content, feature }, idx)
})
}))
|| [])
], []).reverse()
};
}
/**
* Applies to the contents style passed the iconText (1, 2, 3), merges the default marker style with the specific feature style and adds the `highlighted` flag.
*/
export const getContentsFeatureStyle = (markerStyle, contents, content, contentId, feature) => ({
...markerStyle,
iconText: `${findIndex(contents, ({id: _id}) => content.id === _id) + 1}`,
...feature.style,
highlight: contentId === content.id
});