File size: 14,002 Bytes
9bd422a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * GraphLayoutSwitcher - Chuyển Đổi Layout Đồ Thα»‹
 * Cung cαΊ₯p dropdown cho phΓ©p chọn layout Δ‘α»“ thα»‹: Top-Down, Left-Right, Circle, Force-Directed.
 * LΖ°u/khΓ΄i phα»₯c layout preference tα»« localStorage.
 * Requirements: 31.1, 31.2, 31.3, 31.4, 31.5
 */

const GraphLayoutSwitcher = (function () {
    'use strict';

    // ─── Layout Configurations ────────────────────────────────────────────────

    var LAYOUTS = {
        'top-down': {
            name: 'breadthfirst',
            label: 'Top-Down',
            icon: 'fa-arrow-down',
            options: {
                directed: true,
                spacingFactor: 1.2,
                padding: 20,
                avoidOverlap: true,
                nodeDimensionsIncludeLabels: true,
                animate: true,
                animationDuration: 500
            }
        },
        'left-right': {
            name: 'breadthfirst',
            label: 'Left-Right',
            icon: 'fa-arrow-right',
            options: {
                directed: true,
                spacingFactor: 1.5,
                padding: 20,
                avoidOverlap: true,
                nodeDimensionsIncludeLabels: true,
                animate: true,
                animationDuration: 500,
                transform: function (node, position) {
                    return { x: position.y, y: position.x };
                }
            }
        },
        'circle': {
            name: 'circle',
            label: 'Circle',
            icon: 'fa-circle-notch',
            options: {
                padding: 20,
                avoidOverlap: true,
                nodeDimensionsIncludeLabels: true,
                animate: true,
                animationDuration: 500
            }
        },
        'force-directed': {
            name: 'cose',
            label: 'Force-Directed',
            icon: 'fa-project-diagram',
            options: {
                animate: true,
                animationDuration: 500,
                nodeDimensionsIncludeLabels: true,
                nodeRepulsion: function () { return 4500; },
                idealEdgeLength: function () { return 50; },
                edgeElasticity: function () { return 100; }
            }
        }
    };

    var DEFAULT_LAYOUT = 'top-down';

    // ─── Class ────────────────────────────────────────────────────────────────

    class GraphLayoutSwitcher {
        /**
         * @param {string} [graphContainerSelector='#graphContainer'] - CSS selector cho container Δ‘α»“ thα»‹
         * @param {string} [storageKey='onnx_explorer_graph_layout'] - Key localStorage
         */
        constructor(graphContainerSelector, storageKey) {
            /** @type {string} */
            this._containerSelector = graphContainerSelector || '#graphContainer';

            /** @type {string} */
            this._storageKey = storageKey || 'onnx_explorer_graph_layout';

            /** @type {string} */
            this._currentLayout = DEFAULT_LAYOUT;

            /** @type {HTMLElement|null} */
            this._dropdownWrapper = null;

            /** @type {HTMLElement|null} */
            this._dropdownMenu = null;

            /** @type {HTMLButtonElement|null} */
            this._toggleBtn = null;

            /** @type {Function|null} */
            this._unsubscribeGraphRendered = null;

            /** @type {Function|null} */
            this._documentClickHandler = null;

            /** @type {boolean} */
            this._initialized = false;
        }

        // ─── Public API ─────────────────────────────────────────────────────

        /**
         * Khởi tαΊ‘o: tαΊ‘o dropdown, khΓ΄i phα»₯c layout Δ‘Γ£ lΖ°u, lαΊ―ng nghe graph:rendered.
         */
        init() {
            if (this._initialized) return;

            // Restore saved layout preference
            this._currentLayout = this._loadPreference() || DEFAULT_LAYOUT;

            // Create the dropdown UI
            this._createDropdown();

            // Listen for graph:rendered to apply saved layout
            if (window.EventBus) {
                this._unsubscribeGraphRendered = window.EventBus.on(
                    CONFIG.EVENTS.GRAPH_RENDERED,
                    this._onGraphRendered.bind(this)
                );
            }

            this._initialized = true;
            console.log('[GraphLayoutSwitcher] Initialized with layout:', this._currentLayout);
        }

        /**
         * Áp dα»₯ng layout mα»›i cho Δ‘α»“ thα»‹.
         * @param {string} layoutName - 'top-down', 'left-right', 'circle', 'force-directed'
         */
        applyLayout(layoutName) {
            var layoutConfig = LAYOUTS[layoutName];
            if (!layoutConfig) {
                console.warn('[GraphLayoutSwitcher] Unknown layout:', layoutName);
                return;
            }

            var cy = this._getCytoscapeInstance();
            if (!cy) {
                console.warn('[GraphLayoutSwitcher] Cytoscape instance not available');
                return;
            }

            // Build layout options with the cytoscape layout name
            var options = Object.assign({}, layoutConfig.options, { name: layoutConfig.name });

            // Run the layout
            cy.layout(options).run();

            // Update current layout
            this._currentLayout = layoutName;

            // Save preference
            this._savePreference(layoutName);

            // Update dropdown UI
            this._updateDropdownLabel();

            console.log('[GraphLayoutSwitcher] Applied layout:', layoutName);
        }

        /**
         * LαΊ₯y layout hiện tαΊ‘i.
         * @returns {string}
         */
        getCurrentLayout() {
            return this._currentLayout;
        }

        /**
         * Hủy và dọn dẹp.
         */
        destroy() {
            if (this._unsubscribeGraphRendered) {
                this._unsubscribeGraphRendered();
                this._unsubscribeGraphRendered = null;
            }

            if (this._documentClickHandler) {
                document.removeEventListener('click', this._documentClickHandler);
                this._documentClickHandler = null;
            }

            if (this._dropdownWrapper && this._dropdownWrapper.parentNode) {
                this._dropdownWrapper.parentNode.removeChild(this._dropdownWrapper);
            }

            this._dropdownWrapper = null;
            this._dropdownMenu = null;
            this._toggleBtn = null;
            this._initialized = false;
        }

        // ─── Private ────────────────────────────────────────────────────────

        /**
         * Create the dropdown UI and insert into the graph card header.
         */
        _createDropdown() {
            var exportContainer = document.getElementById('graphExportContainer');
            if (!exportContainer) {
                console.warn('[GraphLayoutSwitcher] #graphExportContainer not found');
                return;
            }

            // Wrapper
            var wrapper = document.createElement('div');
            wrapper.className = 'graph-layout-switcher d-inline-block';
            wrapper.style.position = 'relative';

            // Toggle button
            var btn = document.createElement('button');
            btn.className = 'btn btn-outline-secondary btn-sm me-2';
            btn.id = 'graphLayoutBtn';
            btn.title = 'Change Graph Layout';
            btn.type = 'button';
            this._updateBtnContent(btn, this._currentLayout);
            wrapper.appendChild(btn);

            // Dropdown menu
            var menu = document.createElement('div');
            menu.className = 'graph-layout-dropdown';
            menu.id = 'graphLayoutDropdown';
            menu.style.display = 'none';

            var layoutKeys = Object.keys(LAYOUTS);
            for (var i = 0; i < layoutKeys.length; i++) {
                var key = layoutKeys[i];
                var config = LAYOUTS[key];

                var option = document.createElement('button');
                option.className = 'graph-layout-option';
                option.type = 'button';
                option.dataset.layout = key;
                option.innerHTML = '<i class="fas ' + config.icon + ' me-2"></i>' + config.label;

                if (key === this._currentLayout) {
                    option.classList.add('active');
                }

                menu.appendChild(option);
            }

            wrapper.appendChild(menu);

            // Insert before the export container's first child (so it appears to the left)
            exportContainer.insertBefore(wrapper, exportContainer.firstChild);

            this._dropdownWrapper = wrapper;
            this._dropdownMenu = menu;
            this._toggleBtn = btn;

            // Bind events
            this._bindEvents();
        }

        /**
         * Bind click events for the dropdown.
         */
        _bindEvents() {
            var self = this;

            // Toggle dropdown on button click
            if (this._toggleBtn) {
                this._toggleBtn.addEventListener('click', function (e) {
                    e.stopPropagation();
                    var isVisible = self._dropdownMenu.style.display !== 'none';
                    self._dropdownMenu.style.display = isVisible ? 'none' : 'block';
                });
            }

            // Handle layout option click
            if (this._dropdownMenu) {
                this._dropdownMenu.addEventListener('click', function (e) {
                    var option = e.target.closest('.graph-layout-option');
                    if (!option) return;

                    var layoutName = option.dataset.layout;
                    self._dropdownMenu.style.display = 'none';
                    self.applyLayout(layoutName);
                });
            }

            // Close dropdown when clicking outside
            this._documentClickHandler = function () {
                if (self._dropdownMenu) {
                    self._dropdownMenu.style.display = 'none';
                }
            };
            document.addEventListener('click', this._documentClickHandler);
        }

        /**
         * Handle graph:rendered event - apply saved layout.
         * @param {Object} payload - { cy: cytoscape instance }
         */
        _onGraphRendered(payload) {
            // Only apply non-default layout (default is already breadthfirst top-down)
            if (this._currentLayout && this._currentLayout !== DEFAULT_LAYOUT) {
                // Small delay to let the initial layout settle
                var self = this;
                setTimeout(function () {
                    self.applyLayout(self._currentLayout);
                }, 100);
            }
        }

        /**
         * Update the toggle button content to show current layout.
         * @param {HTMLButtonElement} btn
         * @param {string} layoutName
         */
        _updateBtnContent(btn, layoutName) {
            var config = LAYOUTS[layoutName] || LAYOUTS[DEFAULT_LAYOUT];
            btn.innerHTML = '<i class="fas ' + config.icon + ' me-1"></i>Layout';
        }

        /**
         * Update dropdown label and active state after layout change.
         */
        _updateDropdownLabel() {
            if (this._toggleBtn) {
                this._updateBtnContent(this._toggleBtn, this._currentLayout);
            }

            // Update active state on options
            if (this._dropdownMenu) {
                var options = this._dropdownMenu.querySelectorAll('.graph-layout-option');
                for (var i = 0; i < options.length; i++) {
                    if (options[i].dataset.layout === this._currentLayout) {
                        options[i].classList.add('active');
                    } else {
                        options[i].classList.remove('active');
                    }
                }
            }
        }

        /**
         * Get the Cytoscape instance from the app's GraphVisualizer.
         * @returns {object|null}
         */
        _getCytoscapeInstance() {
            try {
                if (window._onnxApp && typeof window._onnxApp.getGraphVisualizer === 'function') {
                    var visualizer = window._onnxApp.getGraphVisualizer();
                    if (visualizer && visualizer._cy) {
                        return visualizer._cy;
                    }
                }
            } catch (err) {
                console.warn('[GraphLayoutSwitcher] Could not access Cytoscape instance:', err);
            }
            return null;
        }

        /**
         * Save layout preference to localStorage.
         * @param {string} layoutName
         */
        _savePreference(layoutName) {
            try {
                localStorage.setItem(this._storageKey, layoutName);
            } catch (_) { /* ignore quota/security errors */ }
        }

        /**
         * Load layout preference from localStorage.
         * @returns {string|null}
         */
        _loadPreference() {
            try {
                var value = localStorage.getItem(this._storageKey);
                if (value && LAYOUTS[value]) {
                    return value;
                }
            } catch (_) { /* ignore */ }
            return null;
        }
    }

    return GraphLayoutSwitcher;
})();

// Export as global for browser usage
window.GraphLayoutSwitcher = GraphLayoutSwitcher;