-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCSS Selector.user.js
More file actions
2458 lines (2244 loc) · 80.2 KB
/
Copy pathCSS Selector.user.js
File metadata and controls
2458 lines (2244 loc) · 80.2 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
// ==UserScript==
// @name CSS Selector Picker (v1.22.0)
// @namespace https://greasyfork.org/
// @version 1.22.0
// @description A CSS selector picker for web pages, allowing you to select elements and generate useful CSS selectors on both Desktop and Mobile.
// @match *://*/*
// @run-at document-end
// @grant GM_setClipboard
// @grant GM_addStyle
// @grant GM.addStyle
// ==/UserScript==
(() => {
"use strict";
// ---------- utils ----------
const addStyle = (css) => {
try {
if (typeof GM_addStyle === "function") return GM_addStyle(css);
} catch (_) {}
try {
if (typeof GM !== "undefined" && typeof GM.addStyle === "function")
return GM.addStyle(css);
} catch (_) {}
const s = document.createElement("style");
s.textContent = css;
document.head.appendChild(s);
};
async function copyText(text) {
if (typeof text !== "string") text = String(text ?? "");
try {
if (typeof GM_setClipboard === "function") {
GM_setClipboard(text, "text");
return true;
}
} catch (_) {}
if (
navigator.clipboard &&
window.isSecureContext &&
navigator.clipboard.writeText
) {
try {
await navigator.clipboard.writeText(text);
return true;
} catch (_) {}
}
try {
const ta = document.createElement("textarea");
ta.value = text;
ta.setAttribute("readonly", "");
Object.assign(ta.style, {
position: "fixed",
top: "0",
left: "0",
width: "1px",
height: "1px",
opacity: "0",
pointerEvents: "none",
zIndex: 2147483647,
});
document.body.appendChild(ta);
ta.focus();
ta.select();
const ok = document.execCommand("copy");
document.body.removeChild(ta);
if (ok) return true;
} catch (_) {}
try {
const div = document.createElement("div");
div.contentEditable = "true";
div.innerText = text;
Object.assign(div.style, {
position: "fixed",
top: "0",
left: "0",
opacity: "0",
zIndex: 2147483647,
});
document.body.appendChild(div);
const range = document.createRange();
range.selectNodeContents(div);
const sel = getSelection();
sel.removeAllRanges();
sel.addRange(range);
const ok = document.execCommand("copy");
sel.removeAllRanges();
div.remove();
if (ok) return true;
} catch (_) {}
return false;
}
const esc =
CSS && CSS.escape
? (s) => CSS.escape(s)
: (s) => String(s).replace(/[^a-zA-Z0-9_-]/g, (ch) => "\\" + ch);
const PILL_MAX_CHARS = 100;
const trim = (s, n = PILL_MAX_CHARS) => {
if (s == null || s === undefined) return "";
const str = String(s);
return str.length <= n ? str : str.slice(0, n - 1) + "…";
};
const looksUniqueToken = (v) => {
if (!v) return false;
const s = String(v);
if (
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s)
)
return true;
if (/\d{3,}/.test(s)) return true;
if (/[a-f0-9]{6,}/i.test(s) && /\d/.test(s)) return true;
if (/[A-Za-z]/.test(s) && /\d/.test(s) && s.length >= 8) return true;
if (s.length >= 16 && /^[A-Za-z0-9_-]+$/.test(s)) return true;
return false;
};
// ---------- finder (CSS selector generator) ----------
// License: MIT
// Author: Anton Medvedev <anton@medv.io>
// Source: https://github.com/antonmedv/finder
const acceptedAttrNames = new Set(['role', 'name', 'aria-label', 'rel', 'href']);
/** Check if attribute name and value are word-like. */
function attr(name, value) {
let nameIsOk = acceptedAttrNames.has(name);
nameIsOk ||= name.startsWith('data-') && wordLike(name);
let valueIsOk = wordLike(value) && value.length < 100;
valueIsOk ||= value.startsWith('#') && wordLike(value.slice(1));
return nameIsOk && valueIsOk;
}
/** Check if id name is word-like. */
function idName(name) {
return wordLike(name);
}
/** Check if class name is word-like. */
function className(name) {
return wordLike(name);
}
/** Check if tag name is word-like. */
function tagName(name) {
return true;
}
/** Finds unique CSS selectors for the given element. */
function finder(input, options) {
if (input.nodeType !== Node.ELEMENT_NODE) {
throw new Error(`Can't generate CSS selector for non-element node type.`);
}
if (input.tagName.toLowerCase() === 'html') {
return 'html';
}
const defaults = {
root: document.body,
idName: idName,
className: className,
tagName: tagName,
attr: attr,
timeoutMs: 1000,
seedMinLength: 3,
optimizedMinLength: 2,
maxNumberOfPathChecks: Infinity,
};
const startTime = new Date();
const config = { ...defaults, ...options };
const rootDocument = findRootDocument(config.root, defaults);
let foundPath;
let count = 0;
for (const candidate of search(input, config, rootDocument)) {
const elapsedTimeMs = new Date().getTime() - startTime.getTime();
if (elapsedTimeMs > config.timeoutMs ||
count >= config.maxNumberOfPathChecks) {
const fPath = fallback(input, rootDocument);
if (!fPath) {
throw new Error(`Timeout: Can't find a unique selector after ${config.timeoutMs}ms`);
}
return selector(fPath);
}
count++;
if (unique(candidate, rootDocument)) {
foundPath = candidate;
break;
}
}
if (!foundPath) {
throw new Error(`Selector was not found.`);
}
const optimized = [
...optimize(foundPath, input, config, rootDocument, startTime),
];
optimized.sort(byPenalty);
if (optimized.length > 0) {
return selector(optimized[0]);
}
return selector(foundPath);
}
function* search(input, config, rootDocument) {
const stack = [];
let paths = [];
let current = input;
let i = 0;
while (current && current !== rootDocument) {
const level = tie(current, config);
for (const node of level) {
node.level = i;
}
stack.push(level);
current = current.parentElement;
i++;
paths.push(...combinations(stack));
if (i >= config.seedMinLength) {
paths.sort(byPenalty);
for (const candidate of paths) {
yield candidate;
}
paths = [];
}
}
paths.sort(byPenalty);
for (const candidate of paths) {
yield candidate;
}
}
function wordLike(name) {
if (/^[a-z\-]{3,}$/i.test(name)) {
const words = name.split(/-|[A-Z]/);
for (const word of words) {
if (word.length <= 2) {
return false;
}
if (/[^aeiou]{4,}/i.test(word)) {
return false;
}
}
return true;
}
return false;
}
function tie(element, config) {
const level = [];
const elementId = element.getAttribute('id');
if (elementId && config.idName(elementId)) {
level.push({
name: '#' + CSS.escape(elementId),
penalty: 0,
});
}
for (let i = 0; i < element.classList.length; i++) {
const name = element.classList[i];
if (config.className(name)) {
level.push({
name: '.' + CSS.escape(name),
penalty: 1,
});
}
}
for (let i = 0; i < element.attributes.length; i++) {
const attr = element.attributes[i];
if (config.attr(attr.name, attr.value)) {
level.push({
name: `[${CSS.escape(attr.name)}="${CSS.escape(attr.value)}"]`,
penalty: 2,
});
}
}
const tagName = element.tagName.toLowerCase();
if (config.tagName(tagName)) {
level.push({
name: tagName,
penalty: 5,
});
const index = indexOf(element, tagName);
if (index !== undefined) {
level.push({
name: nthOfType(tagName, index),
penalty: 10,
});
}
}
const nth = indexOf(element);
if (nth !== undefined) {
level.push({
name: nthChild(tagName, nth),
penalty: 50,
});
}
return level;
}
function selector(path) {
let node = path[0];
let query = node.name;
for (let i = 1; i < path.length; i++) {
const level = path[i].level || 0;
if (node.level === level - 1) {
query = `${path[i].name} > ${query}`;
}
else {
query = `${path[i].name} ${query}`;
}
node = path[i];
}
return query;
}
function penalty(path) {
return path.map((node) => node.penalty).reduce((acc, i) => acc + i, 0);
}
function byPenalty(a, b) {
return penalty(a) - penalty(b);
}
function indexOf(input, tagName) {
const parent = input.parentNode;
if (!parent) {
return undefined;
}
let child = parent.firstChild;
if (!child) {
return undefined;
}
let i = 0;
while (child) {
if (child.nodeType === Node.ELEMENT_NODE &&
(tagName === undefined ||
child.tagName.toLowerCase() === tagName)) {
i++;
}
if (child === input) {
break;
}
child = child.nextSibling;
}
return i;
}
function fallback(input, rootDocument) {
let i = 0;
let current = input;
const path = [];
while (current && current !== rootDocument) {
const tagName = current.tagName.toLowerCase();
const index = indexOf(current, tagName);
if (index === undefined) {
return;
}
path.push({
name: nthOfType(tagName, index),
penalty: NaN,
level: i,
});
current = current.parentElement;
i++;
}
if (unique(path, rootDocument)) {
return path;
}
}
function nthChild(tagName, index) {
if (tagName === 'html') {
return 'html';
}
return `${tagName}:nth-child(${index})`;
}
function nthOfType(tagName, index) {
if (tagName === 'html') {
return 'html';
}
return `${tagName}:nth-of-type(${index})`;
}
function* combinations(stack, path = []) {
if (stack.length > 0) {
for (let node of stack[0]) {
yield* combinations(stack.slice(1, stack.length), path.concat(node));
}
}
else {
yield path;
}
}
function findRootDocument(rootNode, defaults) {
if (rootNode.nodeType === Node.DOCUMENT_NODE) {
return rootNode;
}
if (rootNode === defaults.root) {
return rootNode.ownerDocument;
}
return rootNode;
}
function unique(path, rootDocument) {
const css = selector(path);
switch (rootDocument.querySelectorAll(css).length) {
case 0:
throw new Error(`Can't select any node with this selector: ${css}`);
case 1:
return true;
default:
return false;
}
}
function* optimize(path, input, config, rootDocument, startTime) {
if (path.length > 2 && path.length > config.optimizedMinLength) {
for (let i = 1; i < path.length - 1; i++) {
const elapsedTimeMs = new Date().getTime() - startTime.getTime();
if (elapsedTimeMs > config.timeoutMs) {
return;
}
const newPath = [...path];
newPath.splice(i, 1);
if (unique(newPath, rootDocument) &&
rootDocument.querySelector(selector(newPath)) === input) {
yield newPath;
yield* optimize(newPath, input, config, rootDocument, startTime);
}
}
}
}
// ---------- styles ----------
addStyle(`
/* Scoped root for picker variables */
#css-selector-picker-root{
--pill-h: 46px;
--pill-pad-x: 16px;
--font: -apple-system, BlinkMacSystemFont,"SF Pro Text","Segoe UI",Roboto,Helvetica,Arial,sans-serif;
--font-size: 15px;
--blue-bg:#1a73e8; --blue-bd:#1259b0;
--orange-bg:#ff8c00; --orange-bd:#cc7000;
--text-light:#fff;
--btn-bg:#2f2f2f; --btn-bd:#1c1c1c; --btn-fg:#fff;
--grabber-size: 56px;
--grabber-bg:#2f2f2f;
--grabber-active:#444;
--grabber-bd:#111;
--grabber-fg:#fff;
}
#css-selector-picker-root .selector-pill{
height:var(--pill-h)!important; padding:0 var(--pill-pad-x)!important;
font-family:var(--font)!important; font-size:var(--font-size)!important; line-height:1!important;
box-sizing:border-box!important; display:inline-flex!important; align-items:center!important; justify-content:flex-start!important;
-webkit-tap-highlight-color:transparent; user-select:none; white-space:nowrap; cursor:pointer;
border-radius:999px!important; font-weight:800; max-width:min(64vw,520px); min-width:0; overflow:hidden; text-overflow:ellipsis; text-align:left;
box-shadow:0 3px 10px rgba(0,0,0,.10); outline:none; -webkit-user-select:none;
pointer-events:auto;
position:relative !important;
}
#css-selector-picker-root .selector-pill.generic{ background:var(--orange-bg) !important; border:2px solid var(--orange-bd) !important; color:var(--text-light) !important; }
#css-selector-picker-root .selector-pill.specific{ background:var(--blue-bg) !important; border:2px solid var(--blue-bd) !important; color:var(--text-light) !important; }
#css-selector-picker-root .picker-results{
position:fixed!important; right:16px; bottom:20px; z-index:2147483648;
display:none; flex-direction:column; gap:12px;
pointer-events:none;
}
#css-selector-picker-root .picker-row{ display:flex; gap:8px; align-items:center; justify-content:flex-end; }
#css-selector-picker-root .action-group{ display:flex; gap:6px; pointer-events:none; }
#css-selector-picker-root .action-btn{
height:var(--pill-h)!important; width:var(--pill-h)!important;
min-width:var(--pill-h)!important; min-height:var(--pill-h)!important;
display:inline-flex; align-items:center; justify-content:center;
border-radius:999px!important; font-family:var(--font); font-size:18px; font-weight:700; cursor:pointer; user-select:none;
background:var(--btn-bg); color:var(--btn-fg); border:2px solid var(--btn-bd);
box-shadow:0 3px 10px rgba(0,0,0,.10);
pointer-events:auto;
}
#css-selector-picker-root .action-btn.generic{ border-color:var(--orange-bd); }
#css-selector-picker-root .action-btn.specific{ border-color:var(--blue-bd); }
#css-selector-picker-root .action-btn.generic.active{ background:var(--orange-bg)!important; border-color:var(--orange-bd)!important; }
#css-selector-picker-root .action-btn.specific.active{ background:var(--blue-bg)!important; border-color:var(--blue-bd)!important; }
#css-selector-picker-root .picker-results:not(.locked) .action-btn[data-action="css"]{ display:none!important; }
#css-selector-picker-root .picker-hover-box{
position:fixed; z-index:2147483646; pointer-events:none;
border:1px dotted rgba(26,115,232,.95) !important; background:rgba(26,115,232,.20);
border-radius:3px; box-shadow:inset 0 0 0 1px rgba(255,255,255,.35);
transition:transform .06s ease,width .06s ease,height .06s ease,left .06s ease,top .06s ease;
}
#css-selector-picker-root .picker-matches-layer{position:fixed;left:0;top:0;width:0;height:0;z-index:2147483645;pointer-events:none;}
#css-selector-picker-root .picker-match-box{
position:fixed; pointer-events:none; border:1px dotted rgba(255,140,0,.95) !important;
background:rgba(255,140,0,.22); border-radius:3px; box-shadow:inset 0 0 0 1px rgba(255,255,255,.25);
}
#css-selector-picker-root .picker-hover-box.locked{ border-style:solid !important; }
#css-selector-picker-root .picker-match-box.locked{ border-style:solid !important; }
#css-selector-picker-root .picker-grabber{
position:fixed; left:12px; bottom:20px; z-index:2147483649;
width:var(--grabber-size); height:var(--grabber-size);
display:flex; align-items:center; justify-content:center;
border-radius:50%; background:var(--grabber-bg); color:var(--grabber-fg); border:2px solid var(--grabber-bd);
box-shadow:0 6px 18px rgba(0,0,0,.25);
font-family:var(--font); font-size:calc(var(--grabber-size)*0.5); font-weight:900; cursor:pointer; user-select:none;
-webkit-tap-highlight-color:transparent;
pointer-events:auto;
}
#css-selector-picker-root .picker-grabber.active{ background:var(--grabber-active); }
#css-selector-picker-root .selector-pill .pill-text{ display:block; overflow:hidden; text-overflow:ellipsis; word-break:break-all; white-space:nowrap;}
#css-selector-picker-root .selector-pill .pill-lock{
display:none; align-items:center; justify-content:center;
position:absolute; right:0px; top:0px;
width:50px; height:100%; padding:0; margin:0; border-radius:0 10px 10px 0;
font-size:20px; font-weight: bold; line-height:1; cursor:pointer; user-select:none;
pointer-events:auto;
}
#css-selector-picker-root .selector-pill.generic .pill-lock{ border-color:var(--orange-bd); }
#css-selector-picker-root .selector-pill.specific .pill-lock{ border-color:var(--blue-bd); }
#css-selector-picker-root .picker-results.locked .pill-lock{ display:flex; }
#css-selector-picker-root .picker-css-overlay{
position:fixed; z-index:2147483650; max-width:min(72vw, 640px);
background:#101114; color:#f5f7fb; border:1px solid rgba(255,255,255,.15);
border-radius:10px; box-shadow:0 14px 40px rgba(0,0,0,.45);
font-family:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
pointer-events:auto; display:none;
max-height:60vh;
overflow:scroll;
}
#css-selector-picker-root .picker-css-overlay .css-ov-header{
display:flex !important; align-items:center !important; justify-content:space-between !important;
gap:8px !important; padding:10px 14px !important; background:rgba(255,255,255,.04) !important;
border-bottom:1px solid rgba(255,255,255,.08) !important;
font-family:var(--font) !important; font-weight:700 !important; font-size:13px !important;
}
#css-selector-picker-root .picker-css-overlay .css-ov-title{ opacity:.85 !important; }
#css-selector-picker-root .picker-css-overlay .css-ov-copy{
appearance:none !important; -webkit-appearance:none !important; border:none !important; outline:none !important;
background:#2b2f38 !important; color:#fff !important; border:1px solid #1d2129 !important;;
padding:6px 9px !important; border-radius:8px !important; cursor:pointer !important; font-weight:700 !important; font-size:12px !important;
}
#css-selector-picker-root .picker-css-overlay .css-ov-copy:active{ transform:translateY(1px) !important; }
#css-selector-picker-root .picker-css-overlay pre{ margin:0 !important; padding:8px 16px !important; background: inherit !important; border: none !important; color: inherit !important;}
#css-selector-picker-root .picker-css-overlay code{ font-size: 10px !important; max-width: 340px !important; white-space: nowrap; text-overflow: ellipsis; display:block !important; border: none !important; white-space:pre !important; padding:8px !important; overflow-y:auto !important; overflow-x: hidden !important; word-break:break-word !important; background:inherit !important;}
`);
// Create isolated root container so styles don't leak.
const pickerRoot = document.createElement('div');
pickerRoot.id = 'css-selector-picker-root';
pickerRoot.setAttribute('data-picker-ui','1'); // keep existing detection
document.documentElement.appendChild(pickerRoot);
// ---------- UI ----------
const results = document.createElement("div");
results.className = "picker-results";
results.setAttribute("data-picker-ui", "1");
results.innerHTML = `
<div class="picker-row" data-kind="generic" data-picker-ui="1">
<div class="selector-pill generic" data-role="label" data-picker-ui="1">
<span class="pill-text" data-role="label-text" data-picker-ui="1"></span>
</div>
<div class="action-group" data-picker-ui="1">
<div class="action-btn generic" data-action="parent" title="Parent ▲" data-picker-ui="1">▲</div>
<div class="action-btn generic" data-action="child" title="Child ▼" data-picker-ui="1">▼</div>
<div class="action-btn generic" data-action="css" title="Computed Styles" data-picker-ui="1">ⓘ</div>
<div class="action-btn generic" data-action="hide" title="Hide ✕" data-picker-ui="1">✕</div>
</div>
</div>
<div class="picker-row" data-kind="specific" data-picker-ui="1">
<div class="selector-pill specific" data-role="label" data-picker-ui="1">
<span class="pill-text" data-role="label-text" data-picker-ui="1"></span>
</div>
<div class="action-group" data-picker-ui="1">
<div class="action-btn specific" data-action="prev" title="Prev ◀" data-picker-ui="1">◀</div>
<div class="action-btn specific" data-action="next" title="Next ▶" data-picker-ui="1">▶</div>
<div class="action-btn specific" data-action="css" title="Computed Styles" data-picker-ui="1">ⓘ</div>
<div class="action-btn specific" data-action="hide" title="Hide ✕" data-picker-ui="1">✕</div>
</div>
</div>
`;
pickerRoot.appendChild(results);
const hoverBox = document.createElement("div");
hoverBox.className = "picker-hover-box";
hoverBox.setAttribute("data-picker-ui", "1");
hoverBox.style.display = "none";
pickerRoot.appendChild(hoverBox);
const matchesLayer = document.createElement("div");
matchesLayer.className = "picker-matches-layer";
matchesLayer.setAttribute("data-picker-ui", "1");
pickerRoot.appendChild(matchesLayer);
// Grabber
const grabber = document.createElement("div");
grabber.className = "picker-grabber";
grabber.setAttribute("data-picker-ui", "1");
grabber.setAttribute("title", "Start/Stop Picker");
grabber.textContent = "⊹";
pickerRoot.appendChild(grabber);
// Computed CSS overlay
const cssOverlay = document.createElement("div");
cssOverlay.className = "picker-css-overlay";
cssOverlay.setAttribute("data-picker-ui", "1");
cssOverlay.innerHTML = `
<div class="css-ov-header" data-picker-ui="1">
<div class="css-ov-title" data-picker-ui="1">Computed Styles</div>
<button class="css-ov-copy" data-picker-ui="1" title="Copy CSS">Copy</button>
</div>
<pre data-picker-ui="1"><code class="css-ov-code" data-picker-ui="1"></code></pre>
`;
pickerRoot.appendChild(cssOverlay);
// Hide rules style
const hideStyle = document.createElement("style");
hideStyle.setAttribute("data-picker-ui", "1");
document.head.appendChild(hideStyle);
const hiddenRules = new Set();
const addHideRule = (sel) => {
if (!sel || hiddenRules.has(sel)) return;
hiddenRules.add(sel);
hideStyle.appendChild(
document.createTextNode(`${sel}{display:none !important;}\n`)
);
};
// ---------- state ----------
let pickMode = false;
let locked = false;
let lockedTarget = null;
// Keep overlay open when user explicitly taps/clicks the lock
let overlayPinned = false;
let lastOverlayKind = null; // 'generic' | 'specific'
let activeTouchCount = 0;
let hoveredTarget = null;
let selectorGeneric = "";
let selectorSpecific = "";
// hover RAF
let rafScheduledHover = false,
pendingXY = null;
// pinch-zoom suppression (picker ON)
let zoomSuppressOn = false;
// tap detection
let pdX = 0,
pdY = 0,
pdTime = 0;
const TAP_MS = 300,
TAP_DIST = 10;
const uiContains = (node) => !!(node && node.closest('[data-picker-ui="1"]'));
// ---------- config (named constants) ----------
/** Human-readable named constants replacing magic numbers */
const CONFIG = Object.freeze({
CACHE_CLEANUP_MS: 30_000,
MAX_SELECTOR_TEST_CACHE: 500,
MAX_MATCHES_ARRAY_CACHE: 50,
MAX_QUERY_MATCHES: 1200,
MAX_CHILDREN_CHECK: 30,
MAX_SIBLINGS_ANALYZE: 8,
CONTAINER_MAX_DEPTH: 3,
LABEL_RESTORE_MS: 900,
OVERLAY_HIDE_DELAY: 160,
OVERLAY_POINTERLEAVE_DELAY: 120,
SCROLL_SETTLE_MS: 140,
MIN_GENERIC_MATCHES: 2,
MAX_GENERIC_MATCHES: 200,
});
// ---------- performance helpers ----------
// Cache for expensive computations
const selectorCache = new WeakMap();
const semanticCache = new WeakMap();
const selectorTestCache = new Map(); // Cache for selector test results
const boundingRectCache = new WeakMap(); // Cache for getBoundingClientRect
// Performance throttle for cache cleaning
let cacheCleanupTimer = null;
const scheduleCleanup = () => {
if (cacheCleanupTimer) return;
cacheCleanupTimer = setTimeout(() => {
// Clean selector test cache if it gets too large
if (selectorTestCache.size > CONFIG.MAX_SELECTOR_TEST_CACHE) {
selectorTestCache.clear();
}
cacheCleanupTimer = null;
}, CONFIG.CACHE_CLEANUP_MS);
};
/** Convenience: flash a pill text with a temporary message then restore */
function flashPillText(labelEl, tempText, restoreText, timeout = CONFIG.LABEL_RESTORE_MS) {
if (!labelEl) return;
const prev = restoreText ?? labelEl.textContent ?? "";
labelEl.textContent = tempText;
setTimeout(() => {
labelEl.textContent = trim(prev, PILL_MAX_CHARS);
}, timeout);
}
/** Overlay helpers to avoid duplicating pin/show/hide logic */
let cssOverlayHideTimer = null;
function cancelCssOverlayHideTimer() {
if (cssOverlayHideTimer) {
clearTimeout(cssOverlayHideTimer);
cssOverlayHideTimer = null;
}
}
function scheduleCssOverlayHide(delay = CONFIG.OVERLAY_HIDE_DELAY) {
cancelCssOverlayHideTimer();
cssOverlayHideTimer = setTimeout(hideCssOverlay, delay);
}
function pinOverlay(kind) {
overlayPinned = true;
lastOverlayKind = kind;
cancelCssOverlayHideTimer();
clearAllCssButtonActive();
setCssButtonActive(kind, true);
showCssOverlayFor(kind);
}
function unpinOverlay() {
overlayPinned = false;
lastOverlayKind = null;
clearAllCssButtonActive();
hideCssOverlay();
}
function toggleOverlayPin(kind) {
if (!overlayPinned) {
pinOverlay(kind);
} else if (lastOverlayKind === kind) {
unpinOverlay();
} else {
pinOverlay(kind);
}
}
/** Utility to detect typing contexts */
function isTypingFocus() {
const ae = document.activeElement;
return (
ae &&
(ae.tagName === "INPUT" || ae.tagName === "TEXTAREA" || ae.isContentEditable)
);
}
// Optimized helper functions with caching
const getSemanticClasses = (() => {
const cache = new WeakMap();
return (element) => {
if (!element || !element.classList) return [];
if (cache.has(element)) return cache.get(element);
const result = [];
for (const cls of element.classList) {
if (!looksUniqueToken(cls) && /^[a-z][a-z-]*$/i.test(cls)) {
result.push(cls);
}
}
cache.set(element, result);
return result;
};
})();
const getSameTagSiblings = (() => {
const cache = new WeakMap();
return (element) => {
const parent = element.parentElement;
if (!parent) return [];
const cacheKey = `${parent.tagName}-${element.tagName}`;
if (cache.has(parent)) {
const cached = cache.get(parent);
if (cached.key === cacheKey) return cached.siblings;
}
const siblings = [];
for (const child of parent.children) {
if (child.tagName === element.tagName) {
siblings.push(child);
}
}
cache.set(parent, { key: cacheKey, siblings });
return siblings;
};
})();
const getCachedBoundingRect = (element) => {
if (boundingRectCache.has(element)) {
return boundingRectCache.get(element);
}
const rect = element.getBoundingClientRect();
boundingRectCache.set(element, rect);
// Clear cache after a short time since rects can change
setTimeout(() => boundingRectCache.delete(element), 1000);
return rect;
};
const testSelector = (selector, expectedElement = null, minMatches = 1, maxMatches = 200) => {
// Create cache key
const cacheKey = `${selector}|${minMatches}|${maxMatches}`;
// Check cache first
if (selectorTestCache.has(cacheKey)) {
const cached = selectorTestCache.get(cacheKey);
if (expectedElement) {
// Need to verify the expected element is still in the matches
return {
...cached,
valid: cached.valid && cached.matches && cached.matches.includes(expectedElement)
};
}
return cached;
}
try {
const matches = document.querySelectorAll(selector);
const count = matches.length;
const matchesArray = count <= CONFIG.MAX_MATCHES_ARRAY_CACHE ? Array.from(matches) : null; // Only cache small arrays
const result = {
valid: count >= minMatches && count <= maxMatches,
count,
matches: matchesArray
};
if (expectedElement && matchesArray) {
result.valid = result.valid && matchesArray.includes(expectedElement);
}
// Cache the result
selectorTestCache.set(cacheKey, result);
scheduleCleanup();
return result;
} catch(_) {
const result = { valid: false, count: 0 };
selectorTestCache.set(cacheKey, result);
return result;
}
};
// ---------- selector builders ----------
/** Build a generic selector that matches similar elements (not unique) */
function buildGeneric(el) {
if (!(el instanceof Element)) return "*";
// Check cache first
if (selectorCache.has(el)) {
const cached = selectorCache.get(el);
if (cached && cached.generic && typeof cached.generic === 'string') {
return cached.generic;
}
}
try {
const MAX_MATCHES_TARGET = CONFIG.MAX_GENERIC_MATCHES;
const MIN_MATCHES_TARGET = CONFIG.MIN_GENERIC_MATCHES;
// Get cached semantic signature
let signature = semanticCache.get(el);
if (!signature) {
signature = getSemanticSignature(el);
semanticCache.set(el, signature);
}
const tag = el.tagName.toLowerCase();
const isOverlyBroad = ['div', 'span', 'p', 'a', 'li', 'td', 'th', 'tr', 'img', 'input', 'button'].includes(tag);
// Quick path for unique elements with good attributes
if (signature.classes.length > 0) {
for (let i = 0; i < Math.min(signature.classes.length, 2); i++) {
const selector = `${tag}.${CSS.escape(signature.classes[i])}`;
const result = testSelector(selector, el, MIN_MATCHES_TARGET, MAX_MATCHES_TARGET);
if (result.valid) {
selectorCache.set(el, { generic: selector });
return selector;
}
}
}
// Try semantic container approach only if needed
const containerInfo = findSemanticContainer(el);
if (containerInfo) {
const { container, commonClasses, commonDataAttrs } = containerInfo;
const containerSelector = getMinimalContainerSelector(container);
let targetSelector = tag;
if (commonClasses.length > 0) {
targetSelector += '.' + commonClasses.slice(0, 2).map(c => CSS.escape(c)).join('.');
}
if (commonDataAttrs.length > 0) {
targetSelector += commonDataAttrs.slice(0, 1).map(attr =>
`[${CSS.escape(attr.name)}="${CSS.escape(attr.value)}"]`
).join('');
}
const fullSelector = containerSelector ? `${containerSelector} ${targetSelector}` : targetSelector;
const result = testSelector(fullSelector, el, MIN_MATCHES_TARGET, MAX_MATCHES_TARGET);
if (result.valid) {
selectorCache.set(el, { generic: fullSelector });
return fullSelector;
}
// Try simpler version
if (containerSelector && targetSelector !== tag) {
const simpleResult = testSelector(targetSelector, el, MIN_MATCHES_TARGET, MAX_MATCHES_TARGET);
if (simpleResult.valid) {
selectorCache.set(el, { generic: targetSelector });
return targetSelector;
}
}
}
// Fallback logic - only if tag isn't too broad
const tagResult = testSelector(tag, null, MIN_MATCHES_TARGET, MAX_MATCHES_TARGET);
if (tagResult.valid && !isOverlyBroad) {
selectorCache.set(el, { generic: tag });
return tag;
}
// Last resort - build constrained selector
const constrainedSelector = buildConstrainedGenericSelector(el);
selectorCache.set(el, { generic: constrainedSelector });
return constrainedSelector;
} catch (err) {
// Ultimate fallback
try {
const finderResult = finder(el).replace(/:nth-[^(]+\([^)]+\)/g, "");
selectorCache.set(el, { generic: finderResult });
return finderResult;
} catch (_) {
const fallback = el.tagName.toLowerCase();
selectorCache.set(el, { generic: fallback });
return fallback;
}
}
}
// Helper: analyze semantic patterns in attributes and content
const getSemanticSignature = (() => {
const contentPatternCache = new Map();
return (node) => {
if (semanticCache.has(node)) {
return semanticCache.get(node);
}
const signature = {
classes: getSemanticClasses(node),
dataAttrs: [],
roles: [],
contentPattern: null
};
// Collect semantic data attributes and roles (optimized loop)
const attrs = node.attributes;
for (let i = 0; i < attrs.length; i++) {
const attr = attrs[i];
if (attr.name.startsWith('data-') && !looksUniqueToken(attr.value)) {
signature.dataAttrs.push({name: attr.name, value: attr.value});
} else if (attr.name === 'role' || attr.name === 'aria-label') {
signature.roles.push({name: attr.name, value: attr.value});
}
// Limit collection to prevent excessive data
if (signature.dataAttrs.length >= 3) break;
}
// Analyze content patterns for text-heavy elements (with caching)
const text = node.textContent?.trim();
if (text && text.length > 0 && text.length < 100) {
if (contentPatternCache.has(text)) {
signature.contentPattern = contentPatternCache.get(text);
} else {
let pattern = null;
if (/^\$[\d,]+\.?\d*$/.test(text)) pattern = 'price';
else if (/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(text)) pattern = 'date';
else if (/^\d+$/.test(text)) pattern = 'number';
else if (/^[A-Z][a-z]+ \d+$/.test(text)) pattern = 'month-day';
signature.contentPattern = pattern;
// Cache pattern result
if (contentPatternCache.size < 200) {
contentPatternCache.set(text, pattern);
}
}
}
semanticCache.set(node, signature);
return signature;
};
})();
// Helper: find the best semantic container for similar elements (optimized)
const findSemanticContainer = (() => {
const containerCache = new WeakMap();
return (element) => {
if (containerCache.has(element)) {
return containerCache.get(element);
}
let current = element.parentElement;
const candidates = [];
let depth = 0;
const MAX_DEPTH = CONFIG.CONTAINER_MAX_DEPTH;