Repository navigation
Expand file tree
/
Copy pathcontent.js
More file actions
1818 lines (1660 loc) · 76.3 KB
/
Copy pathcontent.js
File metadata and controls
1818 lines (1660 loc) · 76.3 KB
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
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Configuration
const INJECTED_ATTR = "data-sn-injected-item";
const INVESTIGATION_COLUMN_SELECTOR = 'table[role="presentation"] th[rowspan="1"] div[class*="LinesEllipsis"]';
const INVESTIGATION_TABLE_SELECTOR = 'table[role="presentation"]';
const SELECTION_CHECKBOX_SELECTOR = "input[type='checkbox']";
const SELECTION_MENU_ATTR = 'data-nqa-export-menu';
const SELECTION_BUTTON_ATTR = 'data-nqa-export-action';
const SELECTION_FALLBACK_ID = 'nqa-export-floating-bar';
const SELECTION_ACTION_STYLE_ID = 'nqa-export-action-style';
const SELECTION_ACTION_BAR_SELECTOR = 'div[data-insights="undefined_action-bar"]';
let currentSubmenuTrigger = null; // track open submenu trigger for toggle
let cleanupFn = null; // cleanup for global listeners
const copyTooltipTargets = new Set(); // track copy buttons needing tooltip updates
const modifierIndicatorMap = new Map(); // map copy buttons to modifier state indicators
const modifierState = { alt: false, shift: false }; // track pressed modifier keys
const CLIPBOARD_MODIFIER_SEQUENCE = ['html', 'markdown', 'ascii']; // preferred modifier sequence
// Build tooltip text reflecting the configured clipboard format.
function buildClipboardTooltipText() {
const api = window.NqaExport;
if (!api) return '';
let label = '';
if (typeof api.getClipboardFormatLabel === 'function') {
label = api.getClipboardFormatLabel();
} else if (typeof api.getClipboardFormat === 'function') {
label = api.getClipboardFormat();
}
if (!label) return '';
return `Clipboard format: ${label}`;
}
// Apply tooltip to a specific button.
function applyClipboardTooltip(target) {
if (!(target instanceof Element)) return;
const text = buildClipboardTooltipText();
if (text) target.setAttribute('title', text);
else target.removeAttribute('title');
}
// Register a button so tooltip stays in sync with preferences.
function registerClipboardTooltipTarget(target) {
if (!(target instanceof Element)) return;
copyTooltipTargets.add(target);
applyClipboardTooltip(target);
}
// Remove button from tracking when it is no longer in use.
function unregisterClipboardTooltipTarget(target) {
if (!target) return;
copyTooltipTargets.delete(target);
}
// Refresh tooltip text on all tracked buttons (call on config changes).
function refreshClipboardTooltips() {
const stale = [];
copyTooltipTargets.forEach((el) => {
if (!(el instanceof Element) || !document.contains(el)) {
stale.push(el);
return;
}
applyClipboardTooltip(el);
});
stale.forEach((el) => copyTooltipTargets.delete(el));
}
// Return a human-friendly caption for a clipboard format identifier.
function describeClipboardFormatForUi(format) {
if (!format) return '';
const api = window.NqaExport;
if (api && typeof api.describeClipboardFormat === 'function') {
try { return api.describeClipboardFormat(format); }
catch (_) { /* ignore */ }
}
return String(format);
}
// Build the ordered list of clipboard formats considered for modifiers.
function buildModifierFormatSequence(defaultFormat) {
const api = window.NqaExport;
let base = null;
if (api && typeof api.getClipboardFormatSequence === 'function') {
try {
const seq = api.getClipboardFormatSequence();
if (Array.isArray(seq) && seq.length) base = seq.map((item) => String(item || '').trim().toLowerCase());
} catch (_) { base = null; }
}
const sequence = [];
const seen = new Set();
const push = (value) => {
const normalized = String(value || '').trim().toLowerCase();
if (!normalized || seen.has(normalized)) return;
seen.add(normalized);
sequence.push(normalized);
};
if (defaultFormat) push(defaultFormat);
(base || CLIPBOARD_MODIFIER_SEQUENCE).forEach(push);
if (!sequence.length) push('html');
return sequence;
}
// Resolve the base clipboard format that should be used when no modifier is pressed.
function resolveDefaultClipboardFormat(api) {
let chosen = '';
if (api && typeof api.getClipboardFormat === 'function') {
try { chosen = api.getClipboardFormat(); }
catch (_) { chosen = ''; }
}
if (typeof chosen !== 'string' || !chosen.trim()) {
const fallback = api?.DEFAULT_PREFS?.textFormat || 'markdown';
chosen = fallback;
}
return String(chosen || '').trim().toLowerCase() || 'markdown';
}
// Normalize and deduplicate a sequence of formats while keeping the default first.
function buildOrderedFormatList(sequence, defaultFormat) {
const ordered = [];
const seen = new Set();
const push = (value) => {
const key = String(value || '').trim().toLowerCase();
if (!key || seen.has(key)) return;
seen.add(key);
ordered.push(key);
};
push(defaultFormat);
sequence.forEach(push);
return ordered;
}
// Pick alternate formats for Alt and Shift keys from the ordered list.
function pickModifierFormats(orderedFormats, defaultFormat) {
const alt = orderedFormats.find((fmt) => fmt !== defaultFormat) || null;
const shift = orderedFormats.find((fmt) => fmt !== defaultFormat && fmt !== alt) || alt || null;
return { alt, shift };
}
// Resolve default, Alt and Shift formats together with display labels.
function computeModifierFormats() {
const api = window.NqaExport;
if (!api) return null;
const defaultFormat = resolveDefaultClipboardFormat(api);
const sequence = buildModifierFormatSequence(defaultFormat);
const ordered = buildOrderedFormatList(sequence, defaultFormat);
const { alt: altFormat, shift: shiftFormat } = pickModifierFormats(ordered, defaultFormat);
const altLabel = altFormat ? describeClipboardFormatForUi(altFormat) : '';
const shiftLabel = shiftFormat ? describeClipboardFormatForUi(shiftFormat) : '';
return { defaultFormat, altFormat, shiftFormat, altLabel, shiftLabel };
}
// Determine which modifier (if any) is currently overriding the format.
function getActiveModifierState() {
const mapping = computeModifierFormats();
if (!mapping) return null;
if (modifierState.alt && mapping.altFormat && mapping.altFormat !== mapping.defaultFormat) {
return {
key: 'Alt',
format: mapping.altFormat,
label: mapping.altLabel || mapping.altFormat,
};
}
if (modifierState.shift && mapping.shiftFormat && mapping.shiftFormat !== mapping.defaultFormat) {
return {
key: 'Shift',
format: mapping.shiftFormat,
label: mapping.shiftLabel || mapping.shiftFormat,
};
}
return null;
}
// Update modifier chips on all tracked buttons so they match current keys.
function refreshModifierIndicators() {
ensureModifierIndicatorTargets();
const mapping = computeModifierFormats();
const state = mapping ? getActiveModifierState() : null;
const stale = [];
modifierIndicatorMap.forEach((entry, target) => {
if (!(target instanceof Element)) {
stale.push(target);
return;
}
if (!target.isConnected) {
if (!entry?.chip || !entry.chip.isConnected) stale.push(target);
return;
}
if (!entry || !entry.chip) return;
if (state) {
const label = state.label || state.format;
entry.chip.textContent = `\u00A0(${label})`;
entry.chip.hidden = false;
target.setAttribute('data-nqa-modifier-active', '1');
target.classList.add('nqa-modifier-active');
} else {
entry.chip.textContent = '';
entry.chip.hidden = true;
target.removeAttribute('data-nqa-modifier-active');
target.classList.remove('nqa-modifier-active');
}
});
stale.forEach((target) => unregisterModifierIndicatorTarget(target));
}
// Register any copy buttons in DOM that are missing modifier indicators.
function ensureModifierIndicatorTargets() {
const candidates = document.querySelectorAll(`[${SELECTION_BUTTON_ATTR}][data-nqa-export-copy="1"]`);
candidates.forEach((el) => {
if (!(el instanceof Element)) return;
if (!modifierIndicatorMap.has(el)) {
registerModifierIndicatorTarget(el);
}
});
}
// Attach modifier indicator elements to the provided copy button.
function registerModifierIndicatorTarget(target) {
if (!(target instanceof Element)) return;
if (modifierIndicatorMap.has(target)) {
refreshModifierIndicators();
return;
}
const chip = document.createElement('span');
chip.className = 'nqa-export-modifier-chip';
chip.setAttribute('aria-hidden', 'true');
chip.hidden = true;
try {
target.appendChild(chip);
} catch (_) {
try { target.insertAdjacentElement('beforeend', chip); }
catch (__) { return; }
}
modifierIndicatorMap.set(target, {
chip,
});
target.classList.add('nqa-export-modifier-anchor');
if (typeof requestAnimationFrame === 'function') {
requestAnimationFrame(() => refreshModifierIndicators());
} else {
setTimeout(() => refreshModifierIndicators(), 0);
}
}
// Remove the modifier indicator bindings associated with a copy button.
function unregisterModifierIndicatorTarget(target) {
if (!(target instanceof Element)) return;
const entry = modifierIndicatorMap.get(target);
if (!entry) return;
modifierIndicatorMap.delete(target);
try { entry.chip.remove(); } catch (_) {}
target.classList.remove('nqa-export-modifier-anchor');
target.classList.remove('nqa-modifier-active');
target.removeAttribute('data-nqa-modifier-active');
}
// Update a stored modifier flag and report whether the value changed.
function setModifierFlag(flag, value) {
if (!Object.prototype.hasOwnProperty.call(modifierState, flag)) return false;
const normalized = !!value;
if (modifierState[flag] === normalized) return false;
modifierState[flag] = normalized;
return true;
}
// Reset all modifier keys back to their default (inactive) state.
function clearModifierState() {
let changed = false;
if (modifierState.alt) {
modifierState.alt = false;
changed = true;
}
if (modifierState.shift) {
modifierState.shift = false;
changed = true;
}
if (changed) refreshModifierIndicators();
}
// Handle keydown events to detect Alt/Shift activation.
function handleModifierKeyDown(event) {
if (!event) return;
let changed = false;
if (event.key === 'Alt' || event.key === 'AltGraph') {
changed = setModifierFlag('alt', true) || changed;
}
if (event.key === 'Shift') {
changed = setModifierFlag('shift', true) || changed;
}
if (event.altKey && !modifierState.alt) {
changed = setModifierFlag('alt', true) || changed;
}
if (event.shiftKey && !modifierState.shift) {
changed = setModifierFlag('shift', true) || changed;
}
if (changed) refreshModifierIndicators();
}
// Handle keyup events to clear modifier flags when keys are released.
function handleModifierKeyUp(event) {
if (!event) return;
let changed = false;
if (event.key === 'Alt' || event.key === 'AltGraph') {
changed = setModifierFlag('alt', false) || changed;
}
if (event.key === 'Shift') {
changed = setModifierFlag('shift', false) || changed;
}
if (!event.altKey && modifierState.alt) {
changed = setModifierFlag('alt', false) || changed;
}
if (!event.shiftKey && modifierState.shift) {
changed = setModifierFlag('shift', false) || changed;
}
if (changed) refreshModifierIndicators();
}
// Sync modifier flags from pointer events (covers trackpads, stylus buttons, etc.).
function handleModifierPointer(event) {
if (!event) return;
let changed = false;
changed = setModifierFlag('alt', !!event.altKey) || changed;
changed = setModifierFlag('shift', !!event.shiftKey) || changed;
if (changed) refreshModifierIndicators();
}
// Clear modifiers if focus leaves the window while a key is held.
function handleModifierBlur() {
clearModifierState();
}
// Reset modifier state when the document becomes hidden.
function handleVisibilityChange() {
if (typeof document === 'undefined') return;
if (document.visibilityState !== 'visible') clearModifierState();
}
if (typeof document !== 'undefined') {
document.addEventListener('keydown', handleModifierKeyDown, true);
document.addEventListener('keyup', handleModifierKeyUp, true);
document.addEventListener('pointerdown', handleModifierPointer, true);
document.addEventListener('pointermove', handleModifierPointer, true);
document.addEventListener('pointerup', handleModifierPointer, true);
document.addEventListener('visibilitychange', handleVisibilityChange, true);
}
if (typeof window !== 'undefined') {
window.addEventListener('blur', handleModifierBlur, true);
}
// Build a native-like menu entry (container -> contents -> anchor) using classes from an existing item
function buildAnchoredMenuItem(container, label, href, onClick) {
// Find a reference native menuitem (<a role="menuitem"> or <span role="menuitem">)
const ref = container.querySelector('a[role="menuitem"], span[role="menuitem"]');
if (!ref) return null;
// Reference wrappers
const refContents = ref.parentElement; // usually the StyledContents div
const refContainer = ref.closest('[class*="StyledActionMenuItemContainer"]');
// Create outer container
const outer = document.createElement("div");
if (refContainer) {
refContainer.classList.forEach((cls) => {
try {
if (cls) outer.classList.add(cls);
} catch (_) { }
});
}
outer.setAttribute(INJECTED_ATTR, "1");
// Create contents wrapper
const contents = document.createElement("div");
if (refContents) {
refContents.classList.forEach((cls) => {
try {
if (cls) contents.classList.add(cls);
} catch (_) { }
});
}
// Create anchor that looks like the native one
const a = document.createElement("a");
a.setAttribute("role", "menuitem");
a.setAttribute("tabindex", "-1");
a.setAttribute("data-tabindex", "0");
a.setAttribute("rel", "noreferrer noopener");
a.setAttribute("target", "_blank");
a.href = href;
// Copy classes from the reference item (text-only or icon+text)
ref.classList.forEach((cls) => {
try {
if (cls) a.classList.add(cls);
} catch (_) { }
});
// Text node structure similar to native (<span>Text</span>)
const span = document.createElement("span");
span.textContent = label;
a.appendChild(span);
if (onClick) {
a.addEventListener("click", (e) => {
// Let navigation occur; still avoid bubbling to keep menu behavior consistent
e.stopPropagation();
});
}
contents.appendChild(a);
outer.appendChild(contents);
return outer;
}
// Build a separator similar to native menus.
function buildMenuSeparator(container) {
try {
// Prefer a native group-separator (not the right-side "StyledExtra" separator used inside items)
let native = null;
// 1) Direct child of the menu container with role=separator
for (const el of Array.from(container.children)) {
if (el && el.getAttribute && el.getAttribute('role') === 'separator') {
const cls = String(el.className || '');
if (!/StyledExtra|Extra_/i.test(cls)) { native = el; break; }
}
}
// 2) Scoped lookup for known separator classes
if (!native) {
native = container.querySelector('div[role="separator"][class*="ActionMenuSeparator"], div[role="separator"][class*="SeparatorLi"]');
}
// 3) Global fallback
if (!native) {
native = document.querySelector('div[role="separator"][class*="ActionMenuSeparator"], div[role="separator"][class*="SeparatorLi"]');
}
const sep = document.createElement('div');
sep.setAttribute('role', 'separator');
sep.setAttribute(INJECTED_ATTR, '1');
// Minimal default styling to ensure visibility even if class copy fails
const ensureLine = (bgColor) => {
const line = document.createElement('div');
line.style.height = '1px';
line.style.margin = '6px 0';
line.style.backgroundColor = bgColor || 'rgba(0,0,0,0.15)';
sep.appendChild(line);
};
if (native) {
// Copy outer classes if available
try { native.classList.forEach((cls) => { if (cls) sep.classList.add(cls); }); } catch (_) {}
// Try to clone the inner line look
let nativeLine = native.querySelector('div[class*="SeparatorLine"], div');
if (nativeLine) {
const line = document.createElement('div');
try { nativeLine.classList.forEach((cls) => { if (cls) line.classList.add(cls); }); } catch (_) {}
// Mirror computed style to be safe
try {
const cs = window.getComputedStyle(nativeLine);
if (cs) {
line.style.height = cs.height || '';
line.style.margin = cs.margin || '';
line.style.backgroundColor = cs.backgroundColor || '';
line.style.opacity = cs.opacity || '';
}
} catch (_) {}
sep.appendChild(line);
} else {
ensureLine();
}
} else {
ensureLine();
}
return sep;
} catch (_) {
return null;
}
}
// Return only menu entries whose URL contains the placeholder for the current column
// Current column key is read from window.nqaPlaceHolder.columnName (already normalized);
// Device View falls back to a fixed set of device/user placeholders.
// Example: keeps items where url includes `{devices_full_name}` if columnName is `devices_full_name`.
function getMenuFilteredByCurrentColumn(callback) {
try {
const holder = window.nqaPlaceHolder || {};
const table_name = String(holder?.table_name || '').toLowerCase();
const columnName = holder?.columnName || '';
const tokens = [];
if (table_name === 'device_view') {
tokens.push('devices_name', 'login_name', 'full_name', 'ad_name');
} else if (columnName) {
tokens.push(String(columnName));
}
const normalizedTokens = tokens
.map((t) => String(t || '').trim().toLowerCase())
.filter(Boolean);
const uniqueTokens = Array.from(new Set(normalizedTokens));
if (!uniqueTokens.length) { callback([]); return; }
const store = new window.NqaConfigStore();
store.getMenu()
.then((menu) => {
const filtered = (menu || []).filter((it) => {
const url = it?.url ?? '';
const matches = url.match(/\{([^}]+)\}/g) || [];
if (!matches.length) return false;
return matches.some((rawPlaceholder) => {
const inner = rawPlaceholder.slice(1, -1);
const pattern = inner.replace(/\*/g, '.*');
const re = new RegExp('^' + pattern + '$', 'i');
return uniqueTokens.some((token) => re.test(token));
});
});
callback(filtered);
})
.catch(() => callback([]));
} catch (_) { callback([]); }
}
// Build submenu items for a given device name using stored configs.
// Supports any placeholders of the form {name} and replaces them with values
// from window.nqaPlaceHolder.rawValues if available.
// Remove any line breaks from the URL as the edition is a textarea.
function buildActionItemsForDevice(callback) {
// Get suitable menu entries for the current column
const store = new window.NqaConfigStore();
getMenuFilteredByCurrentColumn(async (cfgs) => {
if (!Array.isArray(cfgs) || !cfgs.length) { callback([]); return; }
const items = [];
const raw = { ...(window?.nqaPlaceHolder?.rawValues ?? {}) };
try {
const inst = await store.getInstance();
const prefix = inst && (inst.prefix || inst.name);
if (prefix) raw.instance_name = String(prefix);
} catch (_) { /* ignore */ }
for (const it of cfgs) {
const label = (it?.name || it?.label) ?? '';
let url = it?.url ?? '';
if (!label || !url) continue;
try {
url = url.replace(/[\r\n]+/g, '');
url = url.replace(/\{([^}]+)\}/g, (match, placeholderPattern) => {
const regex = new RegExp('^' + placeholderPattern.replace(/\*/g, '.*') + '$', 'i');
const matchingKey = Object.keys(raw).find(rawKey => regex.test(rawKey));
if (matchingKey) return raw[matchingKey];
return match;
});
} catch (_) { continue; }
items.push({ label, href: url });
}
callback(items);
});
}
// Find classes from an existing submenu trigger (one that shows an angle-right icon)
function findSubmenuReference(container) {
const items = Array.from(container.querySelectorAll('[role="menuitem"]'));
let fallback = null;
for (const mi of items) {
// Prepare a generic fallback based on the first native item
if (!fallback) {
fallback = {
item: mi,
container: mi.closest('[class*="StyledActionMenuItemContainer"]'),
contents: mi.parentElement,
extra: null
};
}
// Look for a stable FontAwesome angle-right chevron near this item
const scope = mi.parentElement?.parentElement || mi.parentElement || container;
const icon = scope?.querySelector('[data-icon="angle-right"], .fa-angle-right, svg[data-icon="angle-right"]');
if (icon) {
const extra = icon.closest('[aria-hidden="true"][role="separator"]') || icon.parentElement;
return {
item: mi,
container: mi.closest('[class*="StyledActionMenuItemContainer"]'),
contents: mi.parentElement,
extra: extra || null
};
}
}
// No explicit chevron found: return the generic reference (classes may still be copied from item/container)
return fallback;
}
// Build a native-like submenu trigger with left icon and right chevron
function buildSubmenuTrigger(container, label, iconSpec) {
// Try to adopt classes from an existing submenu item
const ref = findSubmenuReference(container);
const outer = document.createElement('div');
outer.setAttribute(INJECTED_ATTR, '1');
if (ref?.container) ref.container.classList.forEach(c => { try { if (c) outer.classList.add(c); } catch (_) { } });
const contents = document.createElement('div');
if (ref?.contents) ref.contents.classList.forEach(c => { try { if (c) contents.classList.add(c); } catch (_) { } });
const trigger = document.createElement('span');
trigger.setAttribute('role', 'menuitem');
trigger.setAttribute('tabindex', '-1');
trigger.setAttribute('data-tabindex', '0');
trigger.setAttribute('aria-label', label);
if (ref?.item) ref.item.classList.forEach(c => { try { if (c) trigger.classList.add(c); } catch (_) { } });
// Inner span holding left icon + label
const inner = document.createElement('span');
// Left icon (SVG Element) at 16px
if (iconSpec && typeof iconSpec === 'object') {
// Accept an Element (expected SVGElement) and normalize
const holder = document.createElement('span');
holder.style.display = 'inline-flex';
holder.style.width = '16px';
holder.style.height = '16px';
holder.style.marginRight = '4px';
holder.style.verticalAlign = 'middle';
let svgEl = null;
try {
let el = null;
if (iconSpec instanceof Element) {
if (iconSpec.tagName && iconSpec.tagName.toLowerCase() === 'svg') {
el = iconSpec.cloneNode(true);
} else if (iconSpec.querySelector) {
const found = iconSpec.querySelector('svg');
el = (found ? found.cloneNode(true) : iconSpec.cloneNode(true));
}
}
if (el) {
holder.appendChild(el);
svgEl = (el.tagName && el.tagName.toLowerCase() === 'svg') ? el : holder.querySelector('svg');
}
} catch (_) { svgEl = null; }
if (svgEl) {
svgEl.setAttribute('width', '16');
svgEl.setAttribute('height', '16');
svgEl.style.width = '16px';
svgEl.style.height = '16px';
svgEl.style.display = 'block';
try {
let refIcon = null;
if (ref?.item) refIcon = ref.item.querySelector('svg');
if (!refIcon) refIcon = container.querySelector('[role="menuitem"] svg');
if (refIcon) {
refIcon.classList.forEach(c => { if (c) svgEl.classList.add(c); });
['aria-hidden', 'focusable', 'role'].forEach(attr => {
const val = refIcon.getAttribute(attr);
if (val !== null) svgEl.setAttribute(attr, val);
});
}
} catch (_) { /* keep minimal styling if no reference icon */ }
}
inner.appendChild(holder);
}
const text = document.createTextNode(label);
inner.appendChild(text);
trigger.appendChild(inner);
// Right side chevron container
const extra = document.createElement('div');
extra.setAttribute('aria-hidden', 'true');
extra.setAttribute('role', 'separator');
if (ref?.extra) ref.extra.classList.forEach(c => { try { if (c) extra.classList.add(c); } catch (_) { } });
// Chevron SVG (self-contained, no obfuscated classes)
try {
const chevron = buildChevronRightIconSvg();
extra.appendChild(chevron);
} catch (_) { /* keep minimal container if SVG fails */ }
contents.appendChild(trigger);
contents.appendChild(extra);
outer.appendChild(contents);
return { outer, trigger };
}
// Show a custom submenu to the right of a trigger element
function showCustomSubmenu(triggerEl, items) {
// Close any existing custom submenu
hideCustomSubmenu();
// Anchors for positioning
const itemContainer = triggerEl.closest('[class*="StyledActionMenuItemContainer"]') || triggerEl;
const rootMenu = triggerEl.closest('[role="menu"]');
if (!rootMenu) return;
const itemRect = itemContainer.getBoundingClientRect();
const rootMenuRect = rootMenu.getBoundingClientRect();
// Try to clone native submenu wrappers/classes for perfect alignment & radius
const nativeSubWrap = document.querySelector('[class*="StyledActionSubMenu_"]');
const nativeInnerMenu = nativeSubWrap?.querySelector('[role="menu"]');
// Outer wrapper (StyledActionSubMenu_*)
const outerWrap = document.createElement('div');
outerWrap.id = 'nca-custom-submenu-wrap';
if (nativeSubWrap?.classList) {
nativeSubWrap.classList.forEach(c => { try { if (c) outerWrap.classList.add(c); } catch (_) { } });
}
// Position like native: flush to the right edge of the root menu, aligned to the triggering row
Object.assign(outerWrap.style, {
position: 'fixed',
top: `${Math.round(itemRect.top)}px`,
left: `${Math.round(rootMenuRect.right)}px`,
transform: `translate(-12px, -2px)`,
zIndex: 2147483647,
});
// Native submenu usually has an extra anonymous div wrapper
const midWrap = document.createElement('div');
outerWrap.appendChild(midWrap);
// Real menu node (StyledActionMenu_*)
const menu = document.createElement('div');
menu.id = 'nca-custom-submenu';
menu.setAttribute('role', 'menu');
if (nativeInnerMenu?.classList) {
nativeInnerMenu.classList.forEach(c => { try { if (c) menu.classList.add(c); } catch (_) { } });
} else if (rootMenu?.classList) {
rootMenu.classList.forEach(c => { try { if (c) menu.classList.add(c); } catch (_) { } });
}
// Try to match rounded corners / shadow from the native submenu (or root menu as fallback)
try {
const refNode = nativeInnerMenu || rootMenu;
const refCS = window.getComputedStyle(refNode);
if (refCS) {
const radius = refCS.borderRadius || '8px';
const shadow = refCS.boxShadow && refCS.boxShadow !== 'none' ? refCS.boxShadow : '0 8px 24px rgba(0,0,0,0.12), 0 2px 4px rgba(0,0,0,0.08)';
const bg = refCS.backgroundColor || '#fff';
menu.style.borderRadius = radius;
menu.style.backgroundColor = bg;
menu.style.overflow = 'hidden';
// Some themes place the shadow on the outer wrapper — mirror it there too
outerWrap.style.boxShadow = shadow;
// If native uses filter-based shadow, copy that as well
const filt = refCS.filter;
if (filt && filt !== 'none') outerWrap.style.filter = filt;
}
} catch (_) { }
// Build items (anchors) similar to native using our anchored builder
const refRoot = nativeInnerMenu || rootMenu || document;
const container = document.createElement('div');
items.forEach(it => {
let item = buildAnchoredMenuItem(refRoot, it.label, it.href, null);
if (item) {
const anchor = item.querySelector('a[role="menuitem"]');
if (anchor) {
// Close our custom submenu right after the new tab is opened
anchor.addEventListener('click', (e) => {
try { console.log('[NQA] submenu anchor click captured', { type: e.type }); } catch (_) {}
try { console.log('[NQA][bus] current placeholder:', window.nqaPlaceHolder); } catch (_) {}
try { e.preventDefault(); } catch (_) {}
try { e.stopPropagation(); } catch (_) {}
let url = '';
try { url = anchor.href || ''; } catch (_) { url = ''; }
try { console.log('[NQA] will open URL in new tab', url); } catch (_) {}
try {
if (url) window.open(url, '_blank', 'noopener,noreferrer');
} catch (_) {
try { console.warn('[NQA] window.open failed'); } catch (__) {}
}
setTimeout(() => { try { console.log('[NQA] closing custom submenu'); } catch(_){} hideCustomSubmenu(); }, 0);
// e.stopPropagation();
// setTimeout(() => hideCustomSubmenu(), 0);
}, { capture: true });
}
}
container.appendChild(item);
});
menu.appendChild(container);
midWrap.appendChild(menu);
document.body.appendChild(outerWrap);
// Track trigger and reflect expanded state for a11y
currentSubmenuTrigger = triggerEl;
try { triggerEl.setAttribute('aria-expanded', 'true'); } catch (_) {}
let rafId = null;
const isRootMenuVisible = () => {
try {
if (!rootMenu || !rootMenu.isConnected) return false;
const cs = window.getComputedStyle(rootMenu);
if (!cs || cs.display === 'none' || cs.visibility === 'hidden') return false;
const op = parseFloat(cs.opacity || '1');
if (op === 0) return false;
const r = rootMenu.getBoundingClientRect();
return r && r.width > 0 && r.height > 0;
} catch (_) { return false; }
};
let closeTimer = null; // debounce submenu close on transient invisibility
const cancelCloseTimer = () => { try { if (closeTimer) { clearTimeout(closeTimer); closeTimer = null; } } catch (_) {} };
const scheduleClose = () => {
if (closeTimer) return;
closeTimer = setTimeout(() => {
try {
if (!isRootMenuVisible()) hideCustomSubmenu();
} finally { closeTimer = null; }
}, 150);
};
const reposition = () => {
try {
// If the root menu becomes temporarily invisible while scrolling, do not close immediately
if (!isRootMenuVisible()) { scheduleClose(); rafId = null; return; }
// If visible again, cancel any pending delayed close
cancelCloseTimer();
const itemRectNow = itemContainer.getBoundingClientRect();
const rootMenuRectNow = rootMenu.getBoundingClientRect();
outerWrap.style.top = `${Math.round(itemRectNow.top)}px`;
outerWrap.style.left = `${Math.round(rootMenuRectNow.right)}px`;
} catch (_) { /* ignore */ }
rafId = null;
};
const onWinMove = () => {
if (rafId == null) rafId = requestAnimationFrame(reposition);
};
// Close on click outside or Escape; and keep submenu aligned on scroll/resize
const onDocClick = (e) => {
if (!outerWrap.contains(e.target) && e.target !== triggerEl) hideCustomSubmenu();
};
const onKey = (e) => {
const isEsc = e.key === 'Escape' || e.key === 'Esc' || e.code === 'Escape';
if (isEsc) hideCustomSubmenu();
};
// If the native root menu gets detached/hidden, also close our submenu
// Maybe not strictly necessary but safer to avoid floating menus
const mo = new MutationObserver(() => {
try { if (!rootMenu.isConnected || !isRootMenuVisible()) scheduleClose(); } catch (_) {}
});
setTimeout(() => {
document.addEventListener('mousedown', onDocClick, { capture: true });
// Right-click (context menu) should also close our submenu immediately
const onContextMenu = (e) => { try { hideCustomSubmenu(); } catch (_) {} };
document.addEventListener('contextmenu', onContextMenu, { capture: true });
document.addEventListener('keydown', onKey, { capture: true });
document.addEventListener('keyup', onKey, { capture: true });
// (wheel/touchmove): realign during internal container scrolling
// (without interfering with clicks, passive capture handlers)
document.addEventListener('wheel', onWinMove, { capture: true, passive: true });
document.addEventListener('touchmove', onWinMove, { capture: true, passive: true });
// (scroll/resize): realign via window events only
window.addEventListener('resize', onWinMove, { passive: true });
window.addEventListener('scroll', onWinMove, { passive: true });
try { mo.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); } catch (_) {}
}, 0);
// Store a cleanup to remove listeners when hiding
if (cleanupFn) { try { cleanupFn(); } catch (_) {} }
cleanupFn = () => {
try { document.removeEventListener('mousedown', onDocClick, { capture: true }); } catch (_) {}
try { document.removeEventListener('contextmenu', onContextMenu, { capture: true }); } catch (_) {}
try { document.removeEventListener('keydown', onKey, { capture: true }); } catch (_) {}
try { document.removeEventListener('keyup', onKey, { capture: true }); } catch (_) {}
// Remove the listeners actually attached
try { document.removeEventListener('wheel', onWinMove, { capture: true }); } catch (_) {}
try { document.removeEventListener('touchmove', onWinMove, { capture: true }); } catch (_) {}
try { window.removeEventListener('resize', onWinMove); } catch (_) {}
try { window.removeEventListener('scroll', onWinMove); } catch (_) {}
try { mo.disconnect(); } catch (_) {}
try { if (rafId != null) cancelAnimationFrame(rafId); } catch (_) {}
cancelCloseTimer();
};
}
// Reset the injected submenu (and cleanup listeners) when the user leaves the menu.
function hideCustomSubmenu() {
const wrap = document.getElementById('nca-custom-submenu-wrap');
if (wrap && wrap.parentNode) {
wrap.parentNode.removeChild(wrap);
try { if (cleanupFn) cleanupFn(); } catch (_) {}
try { if (currentSubmenuTrigger) currentSubmenuTrigger.setAttribute('aria-expanded', 'false'); } catch (_) {}
currentSubmenuTrigger = null;
return;
}
const m = document.getElementById('nca-custom-submenu');
if (m && m.parentNode) m.parentNode.removeChild(m);
try { if (cleanupFn) cleanupFn(); } catch (_) {}
try { if (currentSubmenuTrigger) currentSubmenuTrigger.setAttribute('aria-expanded', 'false'); } catch (_) {}
currentSubmenuTrigger = null;
}
// Build the inline SVG icon used for the root "Quick Actions" menu entry
// Returns an SVGElement sized by the caller (buildSubmenuTrigger normalizes to 16px)
function buildQuickActionsIconSvg(twoStates) {
// Backward compatibility: default to single-state icon
const withTwoStates = !!twoStates;
const svgNS = 'http://www.w3.org/2000/svg';
const svg = document.createElementNS(svgNS, 'svg');
svg.setAttribute('xmlns', svgNS);
svg.setAttribute('viewBox', '0 0 16 16');
svg.setAttribute('aria-hidden', 'true');
svg.setAttribute('focusable', 'false');
svg.setAttribute('role', 'img');
const pathData = [
'M640.413,554.743',
'C640.413,554.743 323.582,908.073 252.487,986.743',
'C300.191,933.956 202.138,1059.237 160.199,1038.401',
'C138.305,1027.524 162.343,969.106 162.343,969.106',
'C162.343,969.106 238.126,727.204 256.832,690.802',
'C282.451,640.950 284.878,630.334 242.366,627.569',
'C232.189,627.757 220.916,628.135 208.1000,627.923',
'L91.473,627.923',
'C-7.042,627.807 -7.057,591.495 81.914,502.524',
'C81.914,502.524 398.685,149.131 469.766,70.447',
'C422.071,123.243 520.105,-2.060 562.037,18.780',
'C583.927,29.659 559.893,88.088 559.893,88.088',
'C559.893,88.088 484.124,330.032 465.422,366.440',
'C439.720,416.471 437.371,426.990 480.327,429.712',
'C490.402,429.522 501.538,429.156 513.303,429.365',
'L630.852,429.365',
'C729.385,429.481 729.401,465.787 640.413,554.743',
'Z'
].join(' ');
if (withTwoStates) {
// Inactive: outline stroke (current behavior)
const gInactive = document.createElementNS(svgNS, 'g');
gInactive.setAttribute('id', 'icon-inactive');
gInactive.setAttribute('transform', 'translate(2.47,0) scale(0.015017) translate(7.057, 2.06)');
const pathInactive = document.createElementNS(svgNS, 'path');
pathInactive.setAttribute('fill', 'none');
pathInactive.setAttribute('stroke', 'currentColor');
pathInactive.setAttribute('stroke-width', '0.8');
pathInactive.setAttribute('vector-effect', 'non-scaling-stroke');
pathInactive.setAttribute('stroke-linecap', 'round');
pathInactive.setAttribute('stroke-linejoin', 'round');
pathInactive.setAttribute('d', pathData);
gInactive.appendChild(pathInactive);
// Active: filled shape
const gActive = document.createElementNS(svgNS, 'g');
gActive.setAttribute('id', 'icon-active');
gActive.setAttribute('transform', 'translate(2.47,0) scale(0.015017) translate(7.057, 2.06)');
const pathActive = document.createElementNS(svgNS, 'path');
pathActive.setAttribute('fill', 'currentColor');
pathActive.setAttribute('d', pathData);
gActive.appendChild(pathActive);
svg.appendChild(gInactive);
svg.appendChild(gActive);
} else {
const g = document.createElementNS(svgNS, 'g');
g.setAttribute('transform', 'translate(2.47,0) scale(0.015017) translate(7.057, 2.06)');
const path = document.createElementNS(svgNS, 'path');
path.setAttribute('fill', 'none');
// Inherit color from context to match menu theme (light/dark)
path.setAttribute('stroke', 'currentColor');
path.setAttribute('stroke-width', '0.8');
path.setAttribute('vector-effect', 'non-scaling-stroke');
path.setAttribute('stroke-linecap', 'round');
path.setAttribute('stroke-linejoin', 'round');
path.setAttribute('d', pathData);
g.appendChild(path);
svg.appendChild(g);
}
return svg;
}
// Build a 16px right-pointing chevron SVG used on submenu rows
function buildChevronRightIconSvg() {
const svgNS = 'http://www.w3.org/2000/svg';
const svg = document.createElementNS(svgNS, 'svg');
svg.setAttribute('viewBox', '0 0 16 16');
svg.setAttribute('aria-hidden', 'true');
svg.setAttribute('focusable', 'false');
svg.setAttribute('width', '16');
svg.setAttribute('height', '16');
svg.style.width = '16px';
svg.style.height = '16px';
svg.style.display = 'block';
const path = document.createElementNS(svgNS, 'path');
path.setAttribute('fill', 'currentColor');
path.setAttribute(
'd',
'M6.57045 4.5C6.51546 4.5 6.45361 4.52806 6.41237 4.57014L6.06873 4.92084C6.02749 4.96293 6 5.02605 6 5.08216C6 5.13828 6.02749 5.2014 6.06873 5.24349L8.76976 8L6.06873 10.7565C6.02749 10.7986 6 10.8617 6 10.9178C6 10.981 6.02749 11.0371 6.06873 11.0792L6.41237 11.4299C6.45361 11.4719 6.51546 11.5 6.57045 11.5C6.62543 11.5 6.68729 11.4719 6.72852 11.4299L9.93127 8.16132C9.97251 8.11924 10 8.05611 10 8C10 7.94389 9.97251 7.88076 9.93127 7.83868L6.72852 4.57014C6.68728 4.52806 6.62543 4.5 6.57045 4.5Z'
);
svg.appendChild(path);
return svg;
}
// Returns the column name for the kebab button element (rootMenuEl)
function getNqaColumnNameFromKebab(rootMenuEl) {
try {
const btn = rootMenuEl && rootMenuEl.nodeType === 1 ? rootMenuEl : null;
if (!btn) return '';
// 1) Parse explicit column name from aria-label
const aria = btn.getAttribute('aria-label') || '';
if (aria) {
const m = /column\s+(.+)$/i.exec(aria);
if (m && m[1]) return normalizeColumnKey(m[1]);
}