-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathviewer-state.ts
431 lines (361 loc) · 11.3 KB
/
viewer-state.ts
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
import { reactive } from 'vue'
import { transform } from 'ol/proj.js'
import type { Extent } from 'ol/extent'
import { purify_lenient } from './dompurify'
import useClient from '~/lib/viewer-client'
import type {
Category,
Family,
Tag,
DisplayableCachedEntity,
DisplayableCluster,
FetchedEntity,
InitConfig,
EnumFilter,
ViewerPaginatedCachedEntities,
BootstrapPermissions,
} from '~/lib'
type ViewData = {
entities: DisplayableCachedEntity[]
clusters: DisplayableCluster[]
}
type AllowedCategory = Category & { allowed: boolean }
type AllowedTag = Tag & { allowed: boolean }
export class AppState {
public initialized = false
private _client: ReturnType<typeof useClient> | null = null
get client() {
return this._client!
}
public initConfig: InitConfig | null = null
public permissions: BootstrapPermissions | null = null
private familiesData: Family[] | null = null
private categoriesData: AllowedCategory[] | null = null
private tagsData: AllowedTag[] | null = null
private familiesLookupTable: Record<string, Family> = {}
private categoriesLookupTable: Record<string, Category> = {}
private tagsLookupTable: Record<string, Tag> = {}
private viewData: ViewData = {
entities: [],
clusters: [],
}
private activeFamilyId: string | null = null
private _activeEntity: FetchedEntity | null = null
public filteringTags: (Tag & { active: boolean | null })[] = []
public filteringCategories: (Category & { active: boolean })[] = []
public filteringEnums: EnumFilter[] = []
get mapSource() {
return {
light: {
url: this.initConfig?.cartography_source.light_map_url,
attribution: this.initConfig?.cartography_source.light_map_attributions,
},
dark: {
url: this.initConfig?.cartography_source.dark_map_url,
attribution: this.initConfig?.cartography_source.dark_map_attributions,
},
}
}
get activeFilteringCategories() {
return this.filteringCategories.filter(c => c.active).map(c => c.id)
}
get activeRequiredTags() {
return this.filteringTags.filter(t => t.active).map(t => t.id)
}
get activeFilteringEnums(): Record<string, string[]> {
return Object
.fromEntries(
this.filteringEnums
.filter(f => f.active.length > 0)
.map(f => [f.key, f.active]),
)
}
get activeHiddenTags() {
return this.filteringTags.filter(t => t.active === false).map(t => t.id)
}
get activeEntity() {
if (this._activeEntity === null) {
return null
}
return {
...this._activeEntity!,
family: this.familiesLookupTable[this._activeEntity!.entity.family_id],
category: this.categoriesLookupTable[this._activeEntity!.entity.category_id],
tags: this._activeEntity!.entity.tags.map(tagId => this.tagsLookupTable[tagId]),
}
}
get entities() {
return this.viewData.entities
}
get clusters() {
return this.viewData.clusters
}
get activeFamily() {
return this.familiesLookupTable[this.activeFamilyId!]
}
set activeFamily(family: Family) {
this.activeFamilyId = family.id
this.filteringCategories = this.categories
.filter(c => c.family_id === family.id && c.allowed)
.map((c) => {
return {
...c,
active: c.default_status,
}
})
if (this.permissions?.can_list_with_enum_constraints)
this.filteringEnums = family.entity_form.fields
.filter(
f => f.indexed
&& !f.privately_indexed
&& (f.field_type === 'EnumMultiOption' || f.field_type === 'EnumSingleOption'))
.map((f) => {
return {
key: f.key,
title: f.display_name,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
values: (f.field_type_metadata as any).options.map((v: any) => {
return {
label: v.label,
value: v.value,
}
}),
active: [],
}
})
}
get online() {
return this.initConfig?.status === 'ok'
}
get hasSafeModeEnabled() {
return !!this.initConfig?.safe_mode.enabled
}
get safeMode() {
return this.initConfig!.safe_mode
}
get hCaptchaSiteKey() {
return this.initConfig?.safe_mode.hcaptcha_sitekey
}
get title() {
return this.initConfig!.general.title!
}
get subtitle() {
return this.initConfig!.general.subtitle ?? null
}
get logo() {
return this.initConfig!.general.logo_url ?? null
}
get loaded() {
return this.initConfig !== null
}
get hasInformation() {
return !!this.initConfig?.general.information
}
get getSanitizedPopup() {
if (!this.initConfig?.init_popup.popup) {
return null
}
return {
siteTitle: this.initConfig!.general.title!,
sanitizedContent: purify_lenient(this.initConfig!.init_popup.popup!),
sanitizedCheckbox: this.initConfig!.init_popup.popup_check_text
? purify_lenient(this.initConfig!.init_popup.popup_check_text!)
: null,
}
}
get redirectUrl() {
return this.initConfig!.general.redirect_url
}
async getSanitizedInformation() {
if (!this.initConfig?.general.information) {
return null
}
return purify_lenient(this.initConfig!.general.information!)
}
async init() {
this._client = useClient()
this.initConfig = await this.client.checkStatus()
this.client.onAuthenticationFailed(async () => {
// It is impossible to recover from this error, since the token is deemed invalid
// and the user needs to use a valid URL from now on. If the redirect url is set,
// we will redirect the user to the configured URL. Otherwise, we will show an error.
if (this.redirectUrl) {
window.location.href = this.redirectUrl
}
else {
throw createError({
statusCode: 404,
statusMessage: 'Page Not Found',
fatal: true,
})
}
})
}
async bootstrapWithToken(token: string) {
if (this.initialized) return
const data = await this.client.bootstrap(token)
this.permissions = data.permissions
this.familiesData = data.families
.sort((a, b) => a.sort_order - b.sort_order)
this.categoriesData = data.categories
.map((category) => {
return {
...category,
allowed: data.allowed_categories.includes(category.id),
}
})
.sort((a, b) => a.title.localeCompare(b.title))
this.tagsData = data.tags.map((tag) => {
return {
...tag,
allowed: data.allowed_tags.includes(tag.id),
}
})
if (this.permissions.can_list_with_filters)
this.filteringTags = this.tagsData
.filter(tag => tag.allowed)
.filter(tag => tag.is_filter)
.map((tag) => {
return {
...tag,
active: tag.default_filter_status ? null : false,
}
})
this.familiesData?.forEach((family) => {
this.familiesLookupTable[family.id] = family
})
this.categoriesData.forEach((category) => {
this.categoriesLookupTable[category.id] = category
})
this.tagsData.forEach((tag) => {
this.tagsLookupTable[tag.id] = tag
})
if (this.familiesData?.length === 0) {
throw new Error('No families available')
}
this.activeFamily = this.familiesData![0]
this.initialized = true
}
get families(): Family[] {
return this.familiesData!
}
get categories(): AllowedCategory[] {
return this.categoriesData!
}
get tags(): Tag[] {
return this.tagsData!
}
get hasActiveEntity() {
return this.activeEntity !== null
}
set hasActiveEntity(value: boolean) {
if (!value) {
this._activeEntity = null
}
}
startCenter() {
// The configuration files is in WGS84 (EPSG:4326)
// The map is in Web Mercator (EPSG:3857)
// We need to transform the coordinates
return transform(
[
state.initConfig!.cartography_init.center_lng!,
state.initConfig!.cartography_init.center_lat!,
],
'EPSG:4326', // WGS84
'EPSG:3857', // Web Mercator
)
}
startZoom() {
return state.initConfig!.cartography_init.zoom
}
async selectedCachedEntity(cacheEntity: DisplayableCachedEntity) {
this._activeEntity = await this.client.fetchEntity(
cacheEntity.entity_id,
this.activeFilteringCategories,
this.activeRequiredTags,
this.activeHiddenTags,
)
}
async selectEntity(id: string) {
this._activeEntity = await this.client.fetchEntity(
id,
this.activeFilteringCategories,
this.activeRequiredTags,
this.activeHiddenTags,
)
}
async searchEntities(query: string, page: number, pageSize: number, require_locations?: boolean): Promise<ViewerPaginatedCachedEntities> {
if (this.permissions?.can_list_without_query || query.length >= 4)
return await this.client.searchEntities(
query,
this.activeFamilyId!,
this.activeFilteringCategories,
this.activeRequiredTags,
this.activeHiddenTags,
page,
pageSize,
this.activeFilteringEnums,
require_locations ?? false,
)
else
return { entities: [], response_current_page: 0, total_pages: 0, total_results: 0 }
}
getCategory(category_id: string) {
return this.categories.find(c => c.id === category_id)!
}
async refreshView(extent: Extent, zoomLevel: number) {
const zoom = Math.round(zoomLevel)
const newViewData = await this.client.getEntitiesWithinBounds(
{
xmin: extent[0],
ymin: extent[1],
xmax: extent[2],
ymax: extent[3],
},
zoom,
this.activeFamilyId!,
this.activeFilteringCategories,
this.activeRequiredTags,
this.activeHiddenTags,
this.activeFilteringEnums,
)
// Step 1: Identify and filter out entities that are no longer present
const existingEntityIds = new Set(newViewData.entities.map(ne => ne.id))
this.viewData.entities = this.viewData.entities.filter(e =>
existingEntityIds.has(e.id),
)
// Step 2: Add new entities that are not already in viewData
const currentEntityIds = new Set(this.viewData.entities.map(e => e.id))
const newEntities = newViewData.entities.filter(
ne => !currentEntityIds.has(ne.id),
)
this.viewData.entities.push(
...newEntities.map(entity => ({
...entity,
coordinates: [entity.web_mercator_x!, entity.web_mercator_y!],
family: this.familiesLookupTable[entity.family_id],
category: this.categoriesLookupTable[entity.category_id],
highlighted: false,
})),
)
// Step 3: Identify and filter out clusters that are no longer present
const existingClusterIds = new Set(newViewData.clusters.map(nc => nc.id))
this.viewData.clusters = this.viewData.clusters.filter(c =>
existingClusterIds.has(c.id),
)
// Step 4: Add new clusters that are not already in viewData
const currentClusterIds = new Set(this.viewData.clusters.map(c => c.id))
const newClusters = newViewData.clusters.filter(
nc => !currentClusterIds.has(nc.id),
)
this.viewData.clusters.push(
...newClusters.map(cluster => ({
...cluster,
coordinates: [cluster.center_x, cluster.center_y],
})),
)
}
}
const state = reactive(new AppState())
export default state