g3w-admin-qplotly 0.0.1__py3-none-any.whl

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.
Files changed (139) hide show
  1. g3w_admin_qplotly-0.0.1.dist-info/METADATA +52 -0
  2. g3w_admin_qplotly-0.0.1.dist-info/RECORD +139 -0
  3. g3w_admin_qplotly-0.0.1.dist-info/WHEEL +5 -0
  4. g3w_admin_qplotly-0.0.1.dist-info/licenses/LICENSE +373 -0
  5. g3w_admin_qplotly-0.0.1.dist-info/top_level.txt +1 -0
  6. qplotly/__init__.py +1 -0
  7. qplotly/admin.py +34 -0
  8. qplotly/api/__init__.py +0 -0
  9. qplotly/api/plots/__init__.py +0 -0
  10. qplotly/api/plots/views.py +211 -0
  11. qplotly/api/widgets/__init__.py +0 -0
  12. qplotly/api/widgets/permissions.py +79 -0
  13. qplotly/api/widgets/serializers.py +109 -0
  14. qplotly/api/widgets/views.py +287 -0
  15. qplotly/apiurls.py +132 -0
  16. qplotly/apps.py +11 -0
  17. qplotly/locale/bg/LC_MESSAGES/django.mo +0 -0
  18. qplotly/locale/bg/LC_MESSAGES/django.po +162 -0
  19. qplotly/locale/de/LC_MESSAGES/django.mo +0 -0
  20. qplotly/locale/de/LC_MESSAGES/django.po +126 -0
  21. qplotly/locale/de/LC_MESSAGES/djangojs.mo +0 -0
  22. qplotly/locale/de/LC_MESSAGES/djangojs.po +221 -0
  23. qplotly/locale/es/LC_MESSAGES/django.mo +0 -0
  24. qplotly/locale/es/LC_MESSAGES/django.po +151 -0
  25. qplotly/locale/es/LC_MESSAGES/djangojs.mo +0 -0
  26. qplotly/locale/es/LC_MESSAGES/djangojs.po +232 -0
  27. qplotly/locale/fi/LC_MESSAGES/django.mo +0 -0
  28. qplotly/locale/fi/LC_MESSAGES/django.po +126 -0
  29. qplotly/locale/fi/LC_MESSAGES/djangojs.mo +0 -0
  30. qplotly/locale/fi/LC_MESSAGES/djangojs.po +222 -0
  31. qplotly/locale/fr/LC_MESSAGES/django.mo +0 -0
  32. qplotly/locale/fr/LC_MESSAGES/django.po +160 -0
  33. qplotly/locale/fr/LC_MESSAGES/djangojs.mo +0 -0
  34. qplotly/locale/fr/LC_MESSAGES/djangojs.po +222 -0
  35. qplotly/locale/it/LC_MESSAGES/django.mo +0 -0
  36. qplotly/locale/it/LC_MESSAGES/django.po +163 -0
  37. qplotly/locale/it/LC_MESSAGES/djangojs.mo +0 -0
  38. qplotly/locale/it/LC_MESSAGES/djangojs.po +220 -0
  39. qplotly/locale/pl/LC_MESSAGES/django.mo +0 -0
  40. qplotly/locale/pl/LC_MESSAGES/django.po +129 -0
  41. qplotly/locale/pl/LC_MESSAGES/djangojs.mo +0 -0
  42. qplotly/locale/pl/LC_MESSAGES/djangojs.po +217 -0
  43. qplotly/locale/pt/LC_MESSAGES/django.mo +0 -0
  44. qplotly/locale/pt/LC_MESSAGES/django.po +160 -0
  45. qplotly/locale/ro/LC_MESSAGES/django.mo +0 -0
  46. qplotly/locale/ro/LC_MESSAGES/django.po +128 -0
  47. qplotly/locale/ro/LC_MESSAGES/djangojs.mo +0 -0
  48. qplotly/locale/ro/LC_MESSAGES/djangojs.po +222 -0
  49. qplotly/locale/se/LC_MESSAGES/django.mo +0 -0
  50. qplotly/locale/se/LC_MESSAGES/django.po +126 -0
  51. qplotly/locale/se/LC_MESSAGES/djangojs.mo +0 -0
  52. qplotly/locale/se/LC_MESSAGES/djangojs.po +222 -0
  53. qplotly/migrations/0001_initial.py +26 -0
  54. qplotly/migrations/0002_qplotlywidget_type.py +18 -0
  55. qplotly/migrations/0003_auto_20200925_0838.py +18 -0
  56. qplotly/migrations/0004_auto_20200925_1535.py +25 -0
  57. qplotly/migrations/0005_qplotlywidget_show_on_start_client.py +18 -0
  58. qplotly/migrations/0006_alter_qplotlywidget_options_qplotlywidget_order.py +23 -0
  59. qplotly/migrations/0007_alter_qplotlywidget_options_and_more.py +22 -0
  60. qplotly/migrations/0008_alter_qplotlywidget_order.py +18 -0
  61. qplotly/migrations/0009_qplotlywidget_show_in_sidebar.py +18 -0
  62. qplotly/migrations/0010_remove_qplotlywidget_show_in_sidebar_and_more.py +22 -0
  63. qplotly/migrations/0011_rename_show_poistion_qplotlywidget_show_position.py +18 -0
  64. qplotly/migrations/0012_qplotlywidgetrelation_qplotlywidget_related_widgets.py +34 -0
  65. qplotly/migrations/0013_alter_qplotlywidgetrelation_source_and_more.py +24 -0
  66. qplotly/migrations/0014_alter_qplotlywidgetrelation_source_and_more.py +24 -0
  67. qplotly/migrations/0015_qplotlywidgetrelation_project.py +34 -0
  68. qplotly/migrations/0016_remove_qplotlywidget_project.py +17 -0
  69. qplotly/migrations/__init__.py +0 -0
  70. qplotly/models.py +142 -0
  71. qplotly/receivers.py +356 -0
  72. qplotly/requirements.txt +1 -0
  73. qplotly/server_filters/__init__.py +1 -0
  74. qplotly/server_filters/relations.py +32 -0
  75. qplotly/static/qplotly/icons/2dhistogram.svg +2048 -0
  76. qplotly/static/qplotly/icons/barplot.svg +2048 -0
  77. qplotly/static/qplotly/icons/boxplot.svg +2048 -0
  78. qplotly/static/qplotly/icons/contour.svg +2056 -0
  79. qplotly/static/qplotly/icons/histogram.svg +2048 -0
  80. qplotly/static/qplotly/icons/pie.svg +2048 -0
  81. qplotly/static/qplotly/icons/polar.svg +2055 -0
  82. qplotly/static/qplotly/icons/scatterplot.svg +2048 -0
  83. qplotly/static/qplotly/icons/scatterternary.svg +2055 -0
  84. qplotly/static/qplotly/icons/violin.svg +2878 -0
  85. qplotly/static/qplotly/js/data-widget-qplotlyWidgetList.js +373 -0
  86. qplotly/static/qplotly/js/i18n/bg.js +19 -0
  87. qplotly/static/qplotly/js/i18n/de.js +19 -0
  88. qplotly/static/qplotly/js/i18n/en.js +19 -0
  89. qplotly/static/qplotly/js/i18n/fi.js +19 -0
  90. qplotly/static/qplotly/js/i18n/fr.js +19 -0
  91. qplotly/static/qplotly/js/i18n/index.js +19 -0
  92. qplotly/static/qplotly/js/i18n/it.js +19 -0
  93. qplotly/static/qplotly/js/i18n/ro.js +19 -0
  94. qplotly/static/qplotly/js/i18n/se.js +19 -0
  95. qplotly/static/qplotly/js/i18n/uk.js +19 -0
  96. qplotly/static/qplotly/js/plugin.js +927 -0
  97. qplotly/static/qplotly/js/sidebar.js +373 -0
  98. qplotly/static/qplotly/js/widget.js +9 -0
  99. qplotly/static/qplotly/plotly-1.52.2.min.js +7 -0
  100. qplotly/static/qplotly/polyfill.min.js +3 -0
  101. qplotly/templates/qplotly/include/plot_type_icon.html +52 -0
  102. qplotly/templates/qplotly/layer_action.html +13 -0
  103. qplotly/templates/qplotly/plots_list_order.html +68 -0
  104. qplotly/templates/qplotly/plots_list_order_action.html +14 -0
  105. qplotly/templatetags/__init__.py +0 -0
  106. qplotly/templatetags/qplotly_tags.py +28 -0
  107. qplotly/urls.py +52 -0
  108. qplotly/utils/__init__.py +13 -0
  109. qplotly/utils/models.py +86 -0
  110. qplotly/utils/qplotly_factory.py +699 -0
  111. qplotly/utils/qplotly_settings.py +37 -0
  112. qplotly/vendor/DataPlotly/__init__.py +0 -0
  113. qplotly/vendor/DataPlotly/core/__init__.py +0 -0
  114. qplotly/vendor/DataPlotly/core/plot_factory.py +843 -0
  115. qplotly/vendor/DataPlotly/core/plot_settings.py +322 -0
  116. qplotly/vendor/DataPlotly/core/plot_types/__init__.py +20 -0
  117. qplotly/vendor/DataPlotly/core/plot_types/bar_plot.py +83 -0
  118. qplotly/vendor/DataPlotly/core/plot_types/box.py +56 -0
  119. qplotly/vendor/DataPlotly/core/plot_types/contour.py +43 -0
  120. qplotly/vendor/DataPlotly/core/plot_types/histogram.py +66 -0
  121. qplotly/vendor/DataPlotly/core/plot_types/histogram2d.py +39 -0
  122. qplotly/vendor/DataPlotly/core/plot_types/icons/2dhistogram.svg +2048 -0
  123. qplotly/vendor/DataPlotly/core/plot_types/icons/barplot.svg +2048 -0
  124. qplotly/vendor/DataPlotly/core/plot_types/icons/boxplot.svg +2048 -0
  125. qplotly/vendor/DataPlotly/core/plot_types/icons/contour.svg +2056 -0
  126. qplotly/vendor/DataPlotly/core/plot_types/icons/histogram.svg +2048 -0
  127. qplotly/vendor/DataPlotly/core/plot_types/icons/pie.svg +2048 -0
  128. qplotly/vendor/DataPlotly/core/plot_types/icons/polar.svg +2055 -0
  129. qplotly/vendor/DataPlotly/core/plot_types/icons/scatterplot.svg +2048 -0
  130. qplotly/vendor/DataPlotly/core/plot_types/icons/scatterternary.svg +2055 -0
  131. qplotly/vendor/DataPlotly/core/plot_types/icons/violin.svg +2878 -0
  132. qplotly/vendor/DataPlotly/core/plot_types/pie.py +60 -0
  133. qplotly/vendor/DataPlotly/core/plot_types/plot_type.py +170 -0
  134. qplotly/vendor/DataPlotly/core/plot_types/polar.py +63 -0
  135. qplotly/vendor/DataPlotly/core/plot_types/scatter.py +74 -0
  136. qplotly/vendor/DataPlotly/core/plot_types/ternary.py +129 -0
  137. qplotly/vendor/DataPlotly/core/plot_types/violin.py +62 -0
  138. qplotly/vendor/__init__.py +0 -0
  139. qplotly/views.py +148 -0
@@ -0,0 +1,927 @@
1
+ (async function() { try {
2
+
3
+ const BASE_URL = `${initConfig.group.plugins.qplotly.baseUrl}qplotly/js`;
4
+
5
+ const { G3W_FID } = g3wsdk.constant;
6
+ const { debounce, throttle, XHR } = g3wsdk.core.utils;
7
+ const { GUI } = g3wsdk.gui;
8
+ const { ApplicationState } = g3wsdk.core;
9
+ const { Plugin } = g3wsdk.core.plugin;
10
+ const { CatalogLayersStoresRegistry } = g3wsdk.core.catalog;
11
+ const MAP = GUI.getService('map');
12
+
13
+ new class extends Plugin {
14
+
15
+ #SIDEBAR; //sidebar component
16
+ #LAYERS = new Set(); //store unique layers that has plot
17
+ #QUERY_RELATIONS_LAYERS = new Set(); //store unique layers that has query position plot
18
+ #CHARTS = [];
19
+
20
+
21
+ /**
22
+ * @fires service~ready
23
+ */
24
+ constructor() {
25
+
26
+ super({
27
+ name: 'qplotly',
28
+ i18n: `${initConfig.staticurl}qplotly/js/i18n/`,
29
+ });
30
+
31
+ // state of plugin
32
+ this.state = Vue.observable({
33
+ loading: false, // loading purpose
34
+ showCharts: false, // show/hide charts
35
+ geolayer: false, // is geolayer
36
+ bbox_filter: false, // Boolean - if set bbox filter on charts
37
+ bbox_ids: [], // plot ids associated to bbox (moveend event)
38
+ bbox_key: null, // Openlayers key event for map `moveend`
39
+ bbox: undefined, // store content of in_bbox param to ge data inside the map bbox
40
+ rel: null, // relation data
41
+ });
42
+
43
+ // loop over plots
44
+ this.config.plots.forEach(plot => {
45
+
46
+ //get catalog layer
47
+ const layer = CatalogLayersStoresRegistry.getLayerById(plot.qgs_layer_id);
48
+
49
+ this.#LAYERS.add(layer);
50
+
51
+ //Add only in a plot that we must show on query
52
+ if (plot.show_position.includes('query')) {
53
+ this.#QUERY_RELATIONS_LAYERS.add(layer);
54
+ }
55
+
56
+ plot.loaded = false // set if plot already laoded
57
+
58
+ //check if plot is visible when open sidebar item
59
+ plot.show = plot.show_on_start; //boolean
60
+
61
+ //set tools for each plots
62
+ plot.tools = {
63
+ filter: layer.getFilter(), // reactive layer filter attribute: { filter: { active: <Boolean> } }
64
+ selection: layer.getSelection(), // reactive layer selection attribute: { selection: { active: <Boolean> } }
65
+ geolayer: Vue.observable({ show: layer.isGeoLayer(), active: false }) // if is geolayer show map tool
66
+ };
67
+
68
+ //check if layer is father on a relation
69
+ plot._rel = layer.isFather() ? {
70
+ data: null,
71
+ relations: layer.getRelations().getArray()
72
+ .filter(r => plot.qgs_layer_id === r.getFather())
73
+ .map(r => ({ id: r.getId(), relationLayer: r.getChild() }))
74
+ } : null;
75
+
76
+ // reload charts after changing filter
77
+ layer.on('filtertokenchange', debounce(({ layerId }) => this.toggleCharts({ layerId })));
78
+ });
79
+
80
+ // check if some some plot has visible geolayer
81
+ this.state.geolayer = this.config.plots.some(p => p.show && p.tools.geolayer.show);
82
+
83
+ // Add query action (show relations (plot))
84
+ GUI.onafter('addActionsForLayers', (actions, layers) => {
85
+ layers.forEach(layer => {
86
+ const relations = ApplicationState.project.getRelations().filter(r => layer.id === r.referencedLayer);
87
+ const charts = relations.filter(r => 'MANY' === r.type).map(r => Array.from(this.#QUERY_RELATIONS_LAYERS).map(l => l.getId()).find(id => id === r.referencingLayer)).filter(Boolean);
88
+ const show_relations = actions[layer.id].findIndex(action => 'show-query-relations' === action.id);
89
+ if (charts.length) {
90
+ const containers = new Map();
91
+ const state = Vue.observable({ toggled: layer.features.reduce((a, _, i) => { a[i] = null; return a; }, {}) });
92
+ const clear = async () => {
93
+ const entries = Array.from(containers);
94
+ containers.clear();
95
+ const results = await Promise.allSettled(entries.map(async ([index, { container, pending }]) => {
96
+ try {
97
+ await pending;
98
+ } finally {
99
+ await this.toggleCharts({ show: false, container });
100
+ Vue.set(state.toggled, index, false);
101
+ }
102
+ }));
103
+ const failure = results.find(result => 'rejected' === result.status);
104
+ if (failure) {
105
+ throw failure.reason;
106
+ }
107
+ };
108
+ actions[layer.id].splice(-1 !== show_relations ? (show_relations + 1) : actions[layer.id].length, 0, {
109
+ id: 'show-plots-relations',
110
+ opened: true,
111
+ class: 'fas fa-chart-bar',
112
+ state,
113
+ hint: 'Show relations chart',
114
+ cbk: throttle(async (layer, feature, action, index, container) => {
115
+ Vue.set(action.state.toggled, index, !action.state.toggled[index]);
116
+ if (action.state.toggled[index]) {
117
+ GUI.disableContent(true);
118
+ try {
119
+ const pending = this.toggleCharts({
120
+ show: true,
121
+ ids: charts,
122
+ container,
123
+ rel: {
124
+ relations,
125
+ fid: feature.attributes[G3W_FID],
126
+ height: 400
127
+ }
128
+ });
129
+ containers.set(index, { container, pending });
130
+ await pending;
131
+ } catch (e) {
132
+ containers.delete(index);
133
+ Vue.set(action.state.toggled, index, false);
134
+ GUI.showUserMessage({ type: 'alert', message: e.message || e });
135
+ } finally {
136
+ GUI.disableContent(false);
137
+ }
138
+ } else {
139
+ const entry = containers.get(index);
140
+ containers.delete(index);
141
+ await this.toggleCharts({ show: false, container: entry?.container || container });
142
+ }
143
+ }),
144
+ clear,
145
+ change: () => clear().catch(e => console.warn(e)),
146
+ });
147
+ }
148
+ });
149
+ });
150
+
151
+ // Listen for the 'addActionsForRelation' event to add chart actions for relations.
152
+ GUI.onafter('addActionsForRelation', (actions, { relation, fid }) => {
153
+ if (!Array.from(this.#QUERY_RELATIONS_LAYERS).some(layer => layer.getId() === relation.referencingLayer)) {
154
+ return;
155
+ }
156
+
157
+ let chart, panel, pending;
158
+
159
+ let disposed = false; // Becomes true when clear starts; this action cannot be reused.
160
+ const state = Vue.observable({ toggled: false, disabled: false });
161
+
162
+ actions.push({
163
+ id: 'qplotly-relation-chart',
164
+ class: 'fas fa-chart-bar',
165
+ hint: 'Show Chart',
166
+ state,
167
+ cbk: async () => {
168
+ // Ignore clicks while loading and callbacks after this action has been cleared.
169
+ if (state.disabled || disposed) {
170
+ return;
171
+ }
172
+ state.disabled = true;
173
+ try {
174
+ if (state.toggled) {
175
+ try {
176
+ if (chart) {
177
+ await this.toggleCharts({ show: false, container: chart });
178
+ }
179
+ } finally {
180
+ panel?.remove();
181
+ panel = null;
182
+ chart = null;
183
+ state.toggled = false;
184
+ }
185
+ return;
186
+ }
187
+
188
+ const container = GUI.getCurrentContent()?.content?.getInternalComponent?.()?.$el?.querySelector('.relation-table');
189
+ if (!container) {
190
+ throw new Error('Relation chart container not found');
191
+ }
192
+ let width = 30;
193
+ panel = document.createElement('div');
194
+ panel.innerHTML = /* html */`
195
+ <div
196
+ role = "separator"
197
+ tabindex = "0"
198
+ aria-label = "Chart width"
199
+ aria-orientation = "vertical"
200
+ aria-valuemin = "10"
201
+ aria-valuemax = "90"
202
+ aria-valuenow = "${width}"
203
+ style = "border-inline: 1px solid var(--skin-color); flex: 0 0 5px; background: #ddd; cursor: col-resize; margin: 0 8px; user-select: none; touch-action: none;"
204
+ ></div>
205
+ <div style="flex: 1; min-width: 0; min-height: 0;"></div>
206
+ `;
207
+ panel.style.cssText = `display: flex; flex: 0 0 ${width}%; min-width: 0;`;
208
+ const divider = panel.firstElementChild;
209
+ chart = panel.lastElementChild;
210
+
211
+ divider.addEventListener('pointerdown', event => {
212
+ event.stopPropagation();
213
+ if (event.button === 0) {
214
+ divider.setPointerCapture(event.pointerId);
215
+ }
216
+ });
217
+ divider.addEventListener('pointermove', event => {
218
+ if (divider.hasPointerCapture(event.pointerId)) {
219
+ const right = panel.getBoundingClientRect().right;
220
+ width = Math.min(90, Math.max(10, (right - event.clientX) * 100 / container.clientWidth));
221
+ panel.style.flexBasis = `${width}%`;
222
+ divider.setAttribute('aria-valuenow', String(width));
223
+ }
224
+ });
225
+ divider.addEventListener('lostpointercapture', () => Vue.nextTick(() => GUI.emit('resize')));
226
+ divider.addEventListener('keydown', event => {
227
+ const nextWidth = {
228
+ ArrowLeft: width + 5,
229
+ ArrowRight: width - 5,
230
+ Home: 10,
231
+ End: 90,
232
+ }[event.key];
233
+ if (undefined === nextWidth) {
234
+ return;
235
+ }
236
+ event.preventDefault();
237
+ width = Math.min(90, Math.max(10, nextWidth));
238
+ panel.style.flexBasis = `${width}%`;
239
+ divider.setAttribute('aria-valuenow', String(width));
240
+ Vue.nextTick(() => GUI.emit('resize'));
241
+ });
242
+ container.append(panel);
243
+ state.toggled = true;
244
+
245
+ // Track chart mounting so cleanup waits for in-flight work.
246
+ pending = this.toggleCharts({
247
+ show: true,
248
+ ids: [relation.referencingLayer],
249
+ container: chart,
250
+ rel: { relations: [relation], fid },
251
+ });
252
+ await pending;
253
+ } catch(e) {
254
+ try {
255
+ if (chart) {
256
+ await this.toggleCharts({ show: false, container: chart });
257
+ }
258
+ } finally {
259
+ panel?.remove();
260
+ panel = null;
261
+ chart = null;
262
+ state.toggled = false;
263
+ }
264
+ GUI.showUserMessage({ type: 'alert', message: e.message || e });
265
+ } finally {
266
+ pending = null;
267
+ state.disabled = false;
268
+ }
269
+ },
270
+ //called when relation component is cleared or the action is disposed
271
+ // Ensures that any in-flight chart operations are completed and the chart is properly closed.
272
+ clear: async () => {
273
+ // Block future callbacks before waiting for an in-flight chart mount to finish.
274
+ disposed = true;
275
+ try {
276
+ await pending;
277
+ if (chart) {
278
+ await this.toggleCharts({ show: false, container: chart });
279
+ }
280
+ } finally {
281
+ panel?.remove();
282
+ panel = null;
283
+ chart = null;
284
+ state.toggled = false;
285
+ }
286
+ },
287
+ });
288
+ });
289
+
290
+ // setup gui
291
+ GUI.isReady().then(async () => {
292
+ if (!this.registerPlugin(this.config.gid)) {
293
+ return;
294
+ }
295
+ // multi plot selector
296
+ const sidebar = this.#SIDEBAR = this.createSideBarComponent({
297
+ data: () => ({ service: this, }),
298
+ template: /* html */ `
299
+ <ul class = "treeview-menu" style = "padding: 10px; color:#FFF;">
300
+ <li v-for = "plot in service.config.plots" :key = "plot.id" :hidden = "!plot.show_position.includes('sidebar')">
301
+ <input
302
+ type = "checkbox"
303
+ :id = "plot.id"
304
+ @change = "service.toggleCharts({ id: plot.id })"
305
+ v-model = "plot.show"
306
+ class = "magic-checkbox" />
307
+ <label :for = "plot.id" style = "display:flex; justify-content: space-between;">
308
+ <span style = "white-space: pre-wrap"> {{ plot.label }} </span>{{ plot.type }}
309
+ </label>
310
+ </li>
311
+ </ul>`
312
+ }, this.config.sidebar);
313
+
314
+ sidebar.onbefore('setOpen', async b => {
315
+ //need to close content before. In this way eventually charts on query result service are cleared
316
+ await GUI.closeContent();
317
+ try {
318
+ await this.toggleCharts({ show: b });
319
+ } catch (e) {
320
+ GUI.showUserMessage({ type: 'alert', message: e.message || e });
321
+ sidebar.setOpen(false);
322
+ return;
323
+ }
324
+ GUI.once('closecontent', () => setTimeout(() => sidebar.getOpen() && sidebar.click()));
325
+ if (!b) {
326
+ GUI.closeContent();
327
+ }
328
+ });
329
+
330
+ this.setReady(true);
331
+
332
+ });
333
+
334
+ }
335
+
336
+ /**
337
+ * Resets plot data and recursively clears related child or parent data.
338
+ * @param {Object} plot - The plot object to clear.
339
+ * @returns {Array} List of plot IDs that were affected/cleared.
340
+ */
341
+ clearData(plot) {
342
+ const plotIds = [];
343
+ plot.loaded = false;
344
+ plot.data = null;
345
+
346
+ // --- 1. Recursive cleanup for child plots (Parent -> Children) ---
347
+ if (plot._rel?.data) {
348
+ // Iterate through all relation layers and their associated data entries
349
+ Object
350
+ .values(plot._rel.data)
351
+ .forEach(data => {
352
+ data.forEach(({ id }) => {
353
+ this.clearData(this.config.plots.find(p => p.id === id)); // Recursively clear child
354
+ plotIds.push(id);
355
+ });
356
+ });
357
+ // Reset the relation data object after clearing children
358
+ plot._rel.data = null;
359
+ }
360
+
361
+ // --- 2. Cleanup orphan references in other plots (Child -> Parent) ---
362
+ // If the plot has no specific relation metadata, check if it exists as a child elsewhere
363
+ if (null === plot._rel) {
364
+ this.config.plots
365
+ .filter(p => p.show && p.id !== plot.id && p._rel?.data)
366
+ .forEach(p => {
367
+ Object.entries(p._rel.data)
368
+ .forEach(([layerId, data]) => {
369
+ // Remove the current plot ID from the parent's relation data
370
+ p._rel.data[layerId] = data.filter(d => plot.id !== d.id);
371
+
372
+ // Cleanup: if a layer's data array is empty, remove the layer key
373
+ if (0 === p._rel.data[layerId].length) {
374
+ delete p._rel.data[layerId];
375
+ }
376
+
377
+ // Final cleanup: if no layers remain, set the whole data object to null
378
+ if (0 === Object.keys(p._rel.data)) {
379
+ p._rel.data = null;
380
+ }
381
+ });
382
+ });
383
+ }
384
+
385
+ return plotIds;
386
+ }
387
+
388
+ /**
389
+ * Get charts data from server
390
+ *
391
+ * @param { Object } opts
392
+ * @param opts.layerIds provide by query by result service otherwise is undefined - Array of relations layer ids
393
+ * @param opts.rel provide by query by result service otherwise is undefined - Object: { relations: Array of relations object, fid: father feature fid, height: heigh of content }
394
+ * @param { Array } opts.plotIds plots id to show provide by plugin sideb item checkbox
395
+ *
396
+ * @returns { Promise<{ order, charts }> }
397
+ */
398
+ async getCharts({
399
+ layerIds,
400
+ plotIds,
401
+ rel,
402
+ } = {}) {
403
+
404
+ //start loading
405
+ this.setLoading(true);
406
+
407
+ // check if it has relation data
408
+ this.state.rel = rel;
409
+
410
+ /** @type { Array } plots that need to be get data to show charts */
411
+ let plots = [];
412
+
413
+ // plots request from Query Result Service
414
+ if (layerIds) {
415
+ //need to filter only query position and plot that has layerIds
416
+ plots = this.config.plots.filter(p => p.show_position.includes('query') && layerIds.find(id => p.qgs_layer_id === id));
417
+ }
418
+
419
+ // plots that have id belong to plotIds array set by check uncheck plot on sidebar interface
420
+ if (!layerIds && plotIds) {
421
+ //loop throught plot ids
422
+ plotIds.forEach(plotId => {
423
+ const currentPlot = this.config.plots.find(p => p.id === plotId);
424
+ if (!currentPlot) return;
425
+
426
+ // Check if there is an already shown parent with a relation to the current plot's layer
427
+ const parentPlot = this.config.plots.find(p => {
428
+ if (!p.show || p.id === plotId || !p._rel) return false;
429
+
430
+ return p._rel.relations.some(r => {
431
+ const isSameLayer = r.relationLayer === currentPlot.qgs_layer_id;
432
+ const data = p._rel.data;
433
+
434
+ // The plot is "new" if relation data is null, the specific layer is missing, or the ID is not yet loaded
435
+ const isNotInData = !data || !data[r.relationLayer] || !data[r.relationLayer].some(d => d.id === plotId);
436
+
437
+ return isSameLayer && isNotInData;
438
+ });
439
+ });
440
+
441
+ const added = parentPlot || currentPlot;
442
+
443
+ // Avoid duplicates and reset loading state
444
+ if (!plots.includes(added)) {
445
+ added.loaded = false;
446
+ plots.push(added);
447
+ }
448
+ });
449
+ }
450
+
451
+ // plots that have attribute show to true and not in relation with other plot show
452
+ // if not belong to show plot father relation
453
+ // is not the same plot id
454
+ // find a plot that relations with relationLayer the same layer id belog to plot qgis_layer_id
455
+ if (layerIds && plotIds) {
456
+ plots = this.config.plots.filter(plot => plot.show && !this.config.plots.some(p => p.show && plot.id !== p.id && p._rel?.relations.some(r => r.relationLayer === plot.qgs_layer_id)));
457
+ }
458
+
459
+ if (!layerIds && !plotIds) {
460
+ // get only plots that have attribute show to true
461
+ // and not in relation with other plot show
462
+ const activePlots = this.config.plots.filter(p => p.show);
463
+
464
+ plots = activePlots.filter(plot => {
465
+ // Find active parent plot relating to current layer
466
+ const hasParentRelation = activePlots.some(parent =>
467
+ parent.id !== plot.id &&
468
+ parent._rel !== null &&
469
+ parent._rel.relations.some(rel => plot.qgs_layer_id === rel.relationLayer)
470
+ );
471
+
472
+ // Filter out children: keep only plots that do not belong to a parent relation
473
+ return !hasParentRelation;
474
+ });
475
+ }
476
+
477
+ const order = (layerIds ? plots : this.config.plots.filter(({ show, show_position }) => show && show_position.includes('sidebar'))).map(p => p.id); // order of plot ids
478
+ const charts = {}; // Object containing charts data
479
+ const c_cache = []; // cache charts plots TODO: register already loaded relation to avoid to replace the same plot multiple times
480
+ const r_cache = new Set(); // cache already loaded relationIds
481
+ const father_relations = Array.from(this.#LAYERS).flatMap(l => l.isFather() ? l.getRelations().getArray() : []); // add "withrerlations" attribute in case of father relation
482
+
483
+ // loop through array plots waiting all promises
484
+ (await Promise
485
+ .allSettled(
486
+ plots.flatMap(plot => {
487
+ const promises = []; // promises array
488
+ let promise;
489
+ // A plot is valid if loaded and has no relations, or if all its visible children are already in data
490
+ const isLoadedWithoutRel = plot.loaded && !plot._rel;
491
+
492
+ const areAllChildrenLoaded = plot.loaded && plot._rel?.data &&
493
+ this.config.plots
494
+ .filter(p => p.show && plot._rel.relations.some(r => p.qgs_layer_id === r.relationLayer))
495
+ .every(childPlot =>
496
+ // Check if this specific child ID exists within any of the plot's relation data arrays
497
+ Object.values(plot._rel.data).some(data => data.some(d => childPlot.id === d.id))
498
+ );
499
+
500
+ if (isLoadedWithoutRel || areAllChildrenLoaded) {
501
+ // no further requests needed, use cached data
502
+ c_cache.push(plot);
503
+ return Promise.resolve({
504
+ result: true,
505
+ data: plot.data,
506
+ relations: plot?._rel?.data,
507
+ });
508
+ }
509
+
510
+ // charts relations
511
+ const activePlots = this.config.plots.filter(p => p.show);
512
+
513
+ // 1. Data passed directly, or single plot visible, or found as a child of another active plot
514
+ const isStandaloneOrPassed = undefined !== rel || activePlots.length <= 1;
515
+
516
+ const foundInParentRelation = !isStandaloneOrPassed && activePlots.some(parent => {
517
+ if (parent.id === plot.id || !parent._rel?.data) return false;
518
+
519
+ // Check if plot.id exists within any of the parent's relation data arrays
520
+ return Object.values(parent._rel.data).some(dataArray => {
521
+ const match = dataArray.find(d => d.id === plot.id);
522
+ if (match) {
523
+ // If found, resolve with the nested data and stop searching
524
+ promises.push(Promise.resolve({ result: true, data: [match.data] }));
525
+ return true;
526
+ }
527
+ return false;
528
+ });
529
+ });
530
+
531
+ if (isStandaloneOrPassed || !foundInParentRelation) {
532
+ // Determine the base relations: use undefined if no layerIds, otherwise filter by referencing layer
533
+ const relations = layerIds
534
+ ? (this.state?.rel?.relations || [])
535
+ .filter(r => plot.qgs_layer_id === r.referencingLayer)
536
+ .map(r => `${r.id}|${this.state.rel.fid}`)
537
+ : [undefined];
538
+
539
+ relations.forEach(relParam => {
540
+ c_cache.push(plot);
541
+
542
+ // If already loaded, resolve immediately; otherwise, fetch data
543
+ const currentPromise = plot.loaded
544
+ ? Promise.resolve({ result: true, data: plot.data })
545
+ : Promise.allSettled((plot.plots ?? [plot]).map(p => {
546
+
547
+ // Identify child relations that need to be loaded (sidebar visibility and not in cache)
548
+ const pendingRelations = p._rel?.relations?.filter(r => {
549
+ const isTargetPlot = this.config.plots.some(cp =>
550
+ cp.show &&
551
+ cp.show_position.includes('sidebar') &&
552
+ cp.qgs_layer_id === r.relationLayer &&
553
+ !cp.loaded
554
+ );
555
+
556
+ if (isTargetPlot && !r_cache.has(r.id)) {
557
+ r_cache.add(r.id);
558
+ p.loaded = false;
559
+ return true;
560
+ }
561
+ return false;
562
+ }) || [];
563
+
564
+ return XHR.get({
565
+ url: `/qplotly/api/trace/${this.config?.gid.split(':')[1]}/${p.qgs_layer_id}/${p.id}/`,
566
+ params: {
567
+ relationonetomany: relParam,
568
+ filtertoken: ApplicationState.tokens.filtertoken || undefined,
569
+ withrelations: pendingRelations.map(r => r.id).join(',') || undefined,
570
+ // Only apply bbox if no specific IDs are set or if the current plot is active
571
+ in_bbox: (this.state.bbox_ids.length === 0 || this.state.bbox_ids.some(b => b.active && b.id === p.id)) && this.state.bbox,
572
+ }
573
+ });
574
+ })).then(results => {
575
+ // Aggregate results from multiple XHR calls
576
+ const success = results.every(r => r.status === 'fulfilled' && r.value?.result);
577
+ const data = results.flatMap(r => r.value?.data || []);
578
+
579
+ // Merge relations from all results into a single object
580
+ const mergedRelations = results
581
+ .filter(r => r.value?.relations)
582
+ .reduce((acc, r) => {
583
+ Object.entries(r.value.relations).forEach(([key, val]) => {
584
+ acc[key] = (acc[key] || []).concat(val);
585
+ });
586
+ return acc;
587
+ }, {});
588
+
589
+ return {
590
+ result: success,
591
+ data,
592
+ relations: Object.keys(mergedRelations).length ? mergedRelations : null
593
+ };
594
+ });
595
+
596
+ promises.push(currentPromise);
597
+ });
598
+ }
599
+ return promises;
600
+ })
601
+ )).forEach((response, index) => {
602
+ const is_error = 'fulfilled' !== response.status || !response.value.result; // some error occurs during get data from server
603
+ const plot = c_cache[index];
604
+
605
+ // request has valid response with multiple chart plot of same plot
606
+ if (!is_error) {
607
+ plot.data = response.value.data;
608
+ plot.loaded = true;
609
+ }
610
+
611
+ this.#setActiveFilters(plot);
612
+
613
+ /** In not yet get data from a plot id, set empty array */
614
+ if (!charts[plot.id]) {
615
+ charts[plot.id] = [];
616
+ }
617
+ charts[plot.id].push({
618
+ filters: plot.filters,
619
+ tools: plot.tools,
620
+ layerId: plot.qgs_layer_id,
621
+ title: plot.label,
622
+ data: (is_error ?? false) ? null : plot.data,
623
+ });
624
+
625
+ // skip on relation or invalid response
626
+ if (is_error || response.value.relation) {
627
+ return;
628
+ }
629
+
630
+ // request has valid response
631
+ const { relations } = response.value; //get relations attribute
632
+ // add data to relations if not set yet
633
+ if (relations && !plot._rel.data) {
634
+ plot._rel.data = relations; //add data of relations
635
+ }
636
+
637
+ //Update relation data for each relation
638
+ if (relations && plot._rel.data) {
639
+ Object.keys(relations).forEach(id => plot._rel.data[id] = relations[id]);
640
+ }
641
+
642
+ // data has a relations attributes data
643
+ // loop through relations by id and get relation data filtered by only show plot
644
+
645
+ // Pre-calculate common values and filter active plots once
646
+ const activePlots = this.config.plots.filter(p => p.show);
647
+ const baseFilter = plot.filters[0];
648
+
649
+ Object.entries(relations ?? {}).forEach(([relId, relationData]) => {
650
+ // Find the father relation name once per relation ID
651
+ const fatherRelName = father_relations.find(rel => relId === rel.getId())?.getName() || "";
652
+
653
+ relationData.forEach(r => {
654
+ // Find the specific plot associated with this relation ID
655
+ activePlots
656
+ .filter(p => p.id === r.id)
657
+ .forEach(p => {
658
+ p.loaded = true;
659
+ p.data = r.data;
660
+ p.title = `${fatherRelName} ${p.label}`.trim();
661
+
662
+ // Manage child plot filters based on the parent's first filter
663
+ const hasValidParentFilter = baseFilter && !(`relation.${baseFilter}` in plot.filters);
664
+ p.filters = hasValidParentFilter ? [`relation.${baseFilter}`] : [];
665
+
666
+ this.#setActiveFilters(plot);
667
+
668
+ // Ensure the chart entry exists and push the new plot data
669
+ charts[p.id] = charts[p.id] || [];
670
+ charts[p.id].push({
671
+ filters: p.filters,
672
+ tools: p.tools,
673
+ layerId: p.qgs_layer_id,
674
+ title: p.title,
675
+ data: (is_error ?? false) ? null : p.data,
676
+ });
677
+ });
678
+ });
679
+ });
680
+
681
+ });
682
+
683
+ // Keep only active plots in bbox_ids if bbox filtering is disabled
684
+ if (!this.state.bbox_filter) {
685
+ this.state.bbox_ids = this.state.bbox_ids.filter(p => p.active);
686
+
687
+ // If no active plots remain, unbind the map move event and clear state
688
+ if (!this.state.bbox_ids.length && this.state.bbox_key) {
689
+ ol.Observable.unByKey(this.state.bbox_key);
690
+ this.state.bbox_key = null;
691
+ }
692
+ }
693
+
694
+ //stop loading
695
+ this.setLoading(false);
696
+
697
+ return Promise.resolve({ order, charts });
698
+ }
699
+
700
+ /**
701
+ * Called by chart actions or when opening/closing the sidebar item.
702
+ *
703
+ * @param { Object } opts
704
+ * @param { boolean } opts.show whether to show charts
705
+ * @param { number } opts.id id of plot to be toggled
706
+ * @param { Array } opts.ids passed by query result services
707
+ * @param opts.container DOM element - passed by query result service
708
+ * @param opts.rel relation data - Passed by query result service
709
+ * @param {boolean} opts.bbox whether to toggle bbox filter
710
+ * @param opts.layerId passed by filter token (add or remove to a specific layer)
711
+ *
712
+ * @returns { Promise<unknown> }
713
+ *
714
+ * @fires change-charts
715
+ */
716
+ async toggleCharts({
717
+ show,
718
+ id,
719
+ ids,
720
+ container,
721
+ rel,
722
+ bbox,
723
+ layerId,
724
+ }) {
725
+ try {
726
+ let CHARTS, PLOT_IDS;
727
+ const { plots } = this.config;
728
+
729
+ // --- 1. Handle Sidebar visibility (Open/Close) ---
730
+ if (true === show) {
731
+ // Clear data for all previously loaded plots to ensure a fresh state
732
+ plots.forEach(p => p.loaded && this.clearData(p));
733
+
734
+ // Dynamically import and mount the Sidebar Vue component
735
+ const component = new (Vue.extend((await import(`${BASE_URL}/sidebar.js`)).default))({
736
+ propsData: { ids, rel, service: this, container }
737
+ }).$mount();
738
+
739
+ this.#CHARTS.push(component);
740
+
741
+ // Wait until the sidebar has finished drawing its charts and setting up observers.
742
+ try {
743
+ await component.mountPromise;
744
+ } catch (e) {
745
+ const index = this.#CHARTS.indexOf(component);
746
+ if (index !== -1) {
747
+ component.$destroy();
748
+ this.#CHARTS.splice(index, 1);
749
+ }
750
+ throw e;
751
+ }
752
+ }
753
+
754
+ if (false === show) {
755
+ // Find the chart instance associated with the provided container selector
756
+ const index = this.#CHARTS.findIndex(component => (container?.[0] ?? container) === (component.container?.[0] ?? component.container));
757
+ if (index !== -1) {
758
+ const component = this.#CHARTS[index];
759
+ try {
760
+ await component.mountPromise;
761
+ } finally {
762
+ // Properly destroy the Vue instance and remove it from the tracking array
763
+ const currentIndex = this.#CHARTS.indexOf(component);
764
+ if (currentIndex !== -1) {
765
+ component.$destroy();
766
+ this.#CHARTS.splice(currentIndex, 1);
767
+ }
768
+
769
+ // Cleanup plot data after closing the sidebar
770
+ plots.forEach(p => p.loaded && this.clearData(p));
771
+ }
772
+ }
773
+ }
774
+
775
+ // --- 2. Handle BBOX / Map Filter changes ---
776
+ if (undefined !== bbox) {
777
+ // Synchronize bbox filter state and fetch current map bounds
778
+ this.state.bbox_filter = bbox;
779
+ this.state.bbox = bbox ? MAP.getMapBBOX().toString() : undefined;
780
+
781
+ // Identify plots with geographic tools and toggle their active state
782
+ const geoPlots = plots.filter(p => p.show && p.tools.geolayer.show);
783
+ geoPlots.forEach(p => p.tools.geolayer.active = bbox);
784
+
785
+ // Register or unregister map 'moveend' listener to trigger reloads on pan/zoom
786
+ if (bbox && !this.state.bbox_key) {
787
+ this.state.bbox_key = MAP.getMap().on('moveend', debounce(() => this.toggleCharts({ layerId: false })));
788
+ }
789
+
790
+ if (!bbox && this.state.bbox_key) {
791
+ ol.Observable.unByKey(this.state.bbox_key);
792
+ this.state.bbox_key = null;
793
+ }
794
+
795
+ // Update the list of plot IDs that should react to bbox changes
796
+ this.state.bbox_ids = bbox ? geoPlots.map(p => ({ id: p.id, active: true })) : [];
797
+ PLOT_IDS = geoPlots.map(p => { this.clearData(p); return p.id; });
798
+ }
799
+
800
+ // --- 3. Handle Layer Filter / Token changes ---
801
+ if (undefined !== layerId && this.state.showCharts) {
802
+ const hasValidRel = undefined !== this.state.rel;
803
+ const isPlotVisible = plots.some(p => this.state.bbox || (layerId === p.qgs_layer_id && p.show));
804
+
805
+ // Proceed only if there isn't a relation preventing the update of hidden plots
806
+ if (!(hasValidRel && !isPlotVisible)) {
807
+ // Refresh bbox string if any bbox-related filter is active
808
+ this.state.bbox = (this.state.bbox_ids.length || this.state.bbox_filter) ? MAP.getMapBBOX().toString() : undefined;
809
+
810
+ // Collect plots affected by bbox or layer-specific token changes
811
+ const reloadQueue = [
812
+ ...(this.state.bbox_ids || []).map(b => Object.assign(plots.find(p => b.id === p.id), { filters: [] })),
813
+ ...(layerId ? plots.filter(p => p.show && p.qgs_layer_id === layerId) : [])
814
+ ];
815
+
816
+ if (reloadQueue.length) {
817
+ PLOT_IDS = reloadQueue.map(p => { this.clearData(p); return p.id; });
818
+ }
819
+ }
820
+ }
821
+
822
+ // --- 4. Handle individual Plot Toggle (Checkbox) ---
823
+ if (undefined !== id) {
824
+ const plot = plots.find(p => p.id === id);
825
+ const hasGeo = plot.tools.geolayer.show;
826
+
827
+ // Sync the plot's geolayer tool with the global bbox filter
828
+ plot.tools.geolayer.active = hasGeo ? (plot.show && this.state.bbox_filter) : plot.tools.geolayer.active;
829
+
830
+ // Check if at least one visible plot requires the geolayer tool
831
+ this.state.geolayer = plots.some(p => p.show && p.tools.geolayer.show);
832
+
833
+ // Add or remove the plot from the bbox tracking list based on its visibility
834
+ if (hasGeo && this.state.bbox_key) {
835
+ if (plot.show) {
836
+ this.state.bbox_ids.push({ id: plot.id, active: this.state.bbox_filter });
837
+ } else {
838
+ this.state.bbox_ids = this.state.bbox_ids.filter(p => p.id !== plot.id);
839
+ }
840
+ }
841
+
842
+ // Disable bbox filtering entirely if no geographic plots are left
843
+ if (!plot.show && hasGeo && !this.state.bbox_ids.length) {
844
+ this.state.bbox = undefined;
845
+ this.state.bbox_filter = false;
846
+ }
847
+
848
+ // If a parent plot is shown, reload its related child plots to maintain data integrity
849
+ if (plot.show && plot._rel && !plots.some(p => p.show && p.id !== plot.id && p.qgs_layer_id === plot.qgs_layer_id)) {
850
+ plots.filter(p => p.show && p.id !== plot.id && plot._rel.relations.some(r => p.qgs_layer_id === r.relationLayer))
851
+ .forEach(p => {
852
+ const pIds = this.clearData(p);
853
+ if (pIds.length) {
854
+ this.getCharts({ plotIds: pIds }).then(d => this.emit('change-charts', d));
855
+ }
856
+ });
857
+ }
858
+
859
+ // Determine which IDs to fetch: either the newly shown plot or the leftovers of a hidden one
860
+ const plotIds = plot.show ? [plot.id] : this.clearData(plot);
861
+ if (plot.show || plotIds.length) PLOT_IDS = plotIds;
862
+
863
+ if (!plot.show) {
864
+ // Reset filters and update the chart display order when a plot is unchecked
865
+ this.#setActiveFilters(plot);
866
+ CHARTS = {
867
+ plotId: plot.id,
868
+ order: plots.filter(p => p.show && p.show_position.includes('sidebar')).map(p => p.id)
869
+ };
870
+ }
871
+ }
872
+
873
+ // --- 5. Finalize and Redraw ---
874
+ if (CHARTS || PLOT_IDS) {
875
+ // Emit the update event with either cached chart metadata or newly fetched data
876
+ const result = CHARTS || await this.getCharts({ plotIds: PLOT_IDS });
877
+ this.emit('change-charts', result);
878
+ }
879
+
880
+ } catch (e) {
881
+ console.warn("toggleCharts error:", e);
882
+ if (true === show) {
883
+ this.setLoading(false);
884
+ throw e;
885
+ }
886
+ }
887
+ }
888
+
889
+
890
+
891
+ /**
892
+ * Show loading charts data (loading === true) is on going
893
+ *
894
+ * @param { boolean } b loading
895
+ * @returns { undefined }
896
+ */
897
+ setLoading(b) {
898
+ document.querySelector('#qplotly')?.classList.toggle('g3w-disabled', b);
899
+ this.state.loading = b;
900
+ }
901
+
902
+ /**
903
+ * Set array of active filter on a plot (eg. map bbox or filtertoken)
904
+ *
905
+ * @param plot
906
+ */
907
+ #setActiveFilters(plot) {
908
+ plot.filters = [];
909
+
910
+ // filtertoken is active
911
+ if (plot.tools.filter.active) {
912
+ plot.filters.push('filtertoken');
913
+ }
914
+
915
+ // map bbox tools is active
916
+ if (plot.tools.geolayer.active && plot.tools.filter.active) {
917
+ plot.filters.splice(0, 1, 'in_bbox_filtertoken');
918
+ }
919
+
920
+ if (plot.tools.geolayer.active && !plot.tools.filter.active) {
921
+ plot.filters.push('in_bbox');
922
+ }
923
+ }
924
+
925
+ }
926
+
927
+ } catch(e) { console.error(e); } })();