@kivacore/dom-selector-client 0.0.0 → 0.7.0

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.
@@ -0,0 +1,604 @@
1
+ /*
2
+ * Browser-injected helper that proxies every console method (log/info/warn/error/debug)
3
+ * to the parent window, so it must reference console[level] dynamically.
4
+ */
5
+ /* eslint-disable no-console */
6
+ ;(() => {
7
+ const MESSAGE_TYPE = 'DOCY_SELECTOR';
8
+ const state = {
9
+ enabled: false,
10
+ parentOrigin: '*',
11
+ overlay: null,
12
+ originalCursor: '',
13
+ onMove: null,
14
+ onClick: null,
15
+ onLeave: null
16
+ };
17
+ const acceptedAttrNames = new Set([
18
+ 'role',
19
+ 'name',
20
+ 'aria-label',
21
+ 'rel',
22
+ 'href'
23
+ ]);
24
+
25
+ // Forward console logs to parent window (once)
26
+ try {
27
+ if (!window.__docy_console_patched__) {
28
+ Object.defineProperty(window, '__docy_console_patched__', {
29
+ value: true,
30
+ writable: false,
31
+ configurable: false,
32
+ enumerable: false
33
+ })
34
+ ;[
35
+ 'log',
36
+ 'info',
37
+ 'warn',
38
+ 'error',
39
+ 'debug'
40
+ ].forEach((level) => {
41
+ const orig = console[level];
42
+
43
+ if (typeof orig !== 'function') return;
44
+ console[level] = (...args) => {
45
+ try {
46
+ window.parent.postMessage(
47
+ {
48
+ kind: 'console',
49
+ level,
50
+ args,
51
+ ts: Date.now()
52
+ },
53
+ '*'
54
+ );
55
+ } catch (_) {
56
+ // ignore postMessage errors
57
+ }
58
+
59
+ return orig.apply(console, args);
60
+ };
61
+ });
62
+ }
63
+ } catch (_) {
64
+ // ignore
65
+ }
66
+
67
+ function ensureOverlay() {
68
+ if (state.overlay) return state.overlay;
69
+ const ov = document.createElement('div');
70
+
71
+ ov.className = 'docy-element-selector-overlay';
72
+ Object.assign(ov.style, {
73
+ position: 'absolute',
74
+ pointerEvents: 'none',
75
+ border: '2px solid #3b82f6',
76
+ backgroundColor: 'rgba(59,130,246,0.25)',
77
+ zIndex: '2147483647',
78
+ transition: 'all 0.1s ease',
79
+ display: 'none',
80
+ left: '0px',
81
+ top: '0px',
82
+ width: '0px',
83
+ height: '0px'
84
+ });
85
+ document.body.appendChild(ov);
86
+
87
+ return (state.overlay = ov);
88
+ }
89
+
90
+ function wordLike(name) {
91
+ if (!/^[a-z\-]{3,}$/i.test(name)) {
92
+ return false;
93
+ }
94
+
95
+ const words = name.split(/-|[A-Z]/);
96
+
97
+ for (const word of words) {
98
+ if (word.length <= 2) {
99
+ return false;
100
+ }
101
+ if (/[^aeiou]{4,}/i.test(word)) {
102
+ return false;
103
+ }
104
+ }
105
+
106
+ return true;
107
+ }
108
+
109
+ function isAcceptedAttr(name, value) {
110
+ let nameIsOk = acceptedAttrNames.has(name);
111
+
112
+ nameIsOk ||= name.startsWith('data-') && wordLike(name);
113
+
114
+ let valueIsOk = wordLike(value) && value.length < 100;
115
+
116
+ valueIsOk ||= value.startsWith('#') && wordLike(value.slice(1));
117
+
118
+ return nameIsOk && valueIsOk;
119
+ }
120
+
121
+ function isAcceptedIdName(name) {
122
+ return wordLike(name);
123
+ }
124
+
125
+ function isAcceptedClassName(name) {
126
+ return wordLike(name);
127
+ }
128
+
129
+ function isAcceptedTagName() {
130
+ return true;
131
+ }
132
+
133
+ function getCssEscape() {
134
+ if (typeof CSS !== 'undefined' && typeof CSS.escape === 'function') {
135
+ return CSS.escape.bind(CSS);
136
+ }
137
+
138
+ return value => String(value).replace(/[^a-zA-Z0-9_-]/g, '\\$&');
139
+ }
140
+
141
+ function createFinderConfig(options) {
142
+ return {
143
+ root: document.body,
144
+ idName: isAcceptedIdName,
145
+ className: isAcceptedClassName,
146
+ tagName: isAcceptedTagName,
147
+ attr: isAcceptedAttr,
148
+ timeoutMs: 1000,
149
+ seedMinLength: 3,
150
+ optimizedMinLength: 2,
151
+ maxNumberOfPathChecks: Number.POSITIVE_INFINITY,
152
+ ...options
153
+ };
154
+ }
155
+
156
+ function createKnotSelector(path) {
157
+ let node = path[0];
158
+ let query = node.name;
159
+
160
+ for (let i = 1; i < path.length; i++) {
161
+ const level = path[i].level || 0;
162
+
163
+ if (node.level === level - 1) {
164
+ query = `${path[i].name} > ${query}`;
165
+ } else {
166
+ query = `${path[i].name} ${query}`;
167
+ }
168
+ node = path[i];
169
+ }
170
+
171
+ return query;
172
+ }
173
+
174
+ function getPathPenalty(path) {
175
+ return path
176
+ .map(node => node.penalty)
177
+ .reduce((acc, value) => acc + value, 0);
178
+ }
179
+
180
+ function compareByPenalty(a, b) {
181
+ return getPathPenalty(a) - getPathPenalty(b);
182
+ }
183
+
184
+ function indexOfElement(input, tagName) {
185
+ const parent = input.parentNode;
186
+
187
+ if (!parent) {
188
+ return undefined;
189
+ }
190
+
191
+ let child = parent.firstChild;
192
+
193
+ if (!child) {
194
+ return undefined;
195
+ }
196
+
197
+ let index = 0;
198
+
199
+ while (child) {
200
+ if (
201
+ child.nodeType === Node.ELEMENT_NODE
202
+ && (
203
+ tagName === undefined
204
+ || child.tagName.toLowerCase() === tagName
205
+ )
206
+ ) {
207
+ index++;
208
+ }
209
+ if (child === input) {
210
+ break;
211
+ }
212
+ child = child.nextSibling;
213
+ }
214
+
215
+ return index;
216
+ }
217
+
218
+ function nthChild(tagName, index) {
219
+ if (tagName === 'html') {
220
+ return 'html';
221
+ }
222
+
223
+ return `${tagName}:nth-child(${index})`;
224
+ }
225
+
226
+ function nthOfType(tagName, index) {
227
+ if (tagName === 'html') {
228
+ return 'html';
229
+ }
230
+
231
+ return `${tagName}:nth-of-type(${index})`;
232
+ }
233
+
234
+ function tie(element, config) {
235
+ const level = [];
236
+ const escapeCss = getCssEscape();
237
+ const elementId = element.getAttribute('id');
238
+
239
+ if (elementId && config.idName(elementId)) {
240
+ level.push({
241
+ name: `#${escapeCss(elementId)}`,
242
+ penalty: 0
243
+ });
244
+ }
245
+
246
+ for (let i = 0; i < element.classList.length; i++) {
247
+ const name = element.classList[i];
248
+
249
+ if (config.className(name)) {
250
+ level.push({
251
+ name: `.${escapeCss(name)}`,
252
+ penalty: 1
253
+ });
254
+ }
255
+ }
256
+
257
+ for (let i = 0; i < element.attributes.length; i++) {
258
+ const attribute = element.attributes[i];
259
+
260
+ if (config.attr(attribute.name, attribute.value)) {
261
+ level.push({
262
+ name: `[${escapeCss(attribute.name)}="${escapeCss(attribute.value)}"]`,
263
+ penalty: 2
264
+ });
265
+ }
266
+ }
267
+
268
+ const tagName = element.tagName.toLowerCase();
269
+
270
+ if (config.tagName(tagName)) {
271
+ level.push({
272
+ name: tagName,
273
+ penalty: 5
274
+ });
275
+
276
+ const index = indexOfElement(element, tagName);
277
+
278
+ if (index !== undefined) {
279
+ level.push({
280
+ name: nthOfType(tagName, index),
281
+ penalty: 10
282
+ });
283
+ }
284
+ }
285
+
286
+ const nth = indexOfElement(element);
287
+
288
+ if (nth !== undefined) {
289
+ level.push({
290
+ name: nthChild(tagName, nth),
291
+ penalty: 50
292
+ });
293
+ }
294
+
295
+ return level;
296
+ }
297
+
298
+ function* combinations(stack, path = []) {
299
+ if (stack.length === 0) {
300
+ yield path;
301
+
302
+ return;
303
+ }
304
+
305
+ for (const node of stack[0]) {
306
+ yield* combinations(stack.slice(1), path.concat(node));
307
+ }
308
+ }
309
+
310
+ function* search(input, config, rootDocument) {
311
+ const stack = [];
312
+ let paths = [];
313
+ let current = input;
314
+ let levelIndex = 0;
315
+
316
+ while (current && current !== rootDocument) {
317
+ const level = tie(current, config);
318
+
319
+ for (const node of level) {
320
+ node.level = levelIndex;
321
+ }
322
+ stack.push(level);
323
+ current = current.parentElement;
324
+ levelIndex++;
325
+
326
+ paths.push(...combinations(stack));
327
+
328
+ if (levelIndex >= config.seedMinLength) {
329
+ paths.sort(compareByPenalty);
330
+ for (const candidate of paths) {
331
+ yield candidate;
332
+ }
333
+ paths = [];
334
+ }
335
+ }
336
+
337
+ paths.sort(compareByPenalty);
338
+ for (const candidate of paths) {
339
+ yield candidate;
340
+ }
341
+ }
342
+
343
+ function findRootDocument(rootNode, defaults, input) {
344
+ const root = input.getRootNode ? input.getRootNode() : null;
345
+
346
+ if (root && root.constructor && root.constructor.name === 'ShadowRoot') {
347
+ return root;
348
+ }
349
+ if (rootNode.nodeType === Node.DOCUMENT_NODE) {
350
+ return rootNode;
351
+ }
352
+ if (rootNode === defaults.root) {
353
+ return rootNode.ownerDocument;
354
+ }
355
+
356
+ return rootNode;
357
+ }
358
+
359
+ function isUniquePath(path, rootDocument) {
360
+ const css = createKnotSelector(path);
361
+ const count = rootDocument.querySelectorAll(css).length;
362
+
363
+ if (count === 0) {
364
+ throw new Error(`Can't select any node with this selector: ${css}`);
365
+ }
366
+
367
+ return count === 1;
368
+ }
369
+
370
+ function fallbackPath(input, rootDocument) {
371
+ let current = input;
372
+ let levelIndex = 0;
373
+ const path = [];
374
+
375
+ while (current && current !== rootDocument) {
376
+ const tagName = current.tagName.toLowerCase();
377
+ const index = indexOfElement(current, tagName);
378
+
379
+ if (index === undefined) {
380
+ return undefined;
381
+ }
382
+
383
+ path.push({
384
+ name: nthOfType(tagName, index),
385
+ penalty: Number.NaN,
386
+ level: levelIndex
387
+ });
388
+ current = current.parentElement;
389
+ levelIndex++;
390
+ }
391
+
392
+ if (isUniquePath(path, rootDocument)) {
393
+ return path;
394
+ }
395
+
396
+ return undefined;
397
+ }
398
+
399
+ function* optimize(path, input, config, rootDocument, startTime) {
400
+ if (path.length <= 2 || path.length <= config.optimizedMinLength) {
401
+ return;
402
+ }
403
+
404
+ for (let i = 1; i < path.length - 1; i++) {
405
+ if (Date.now() - startTime > config.timeoutMs) {
406
+ return;
407
+ }
408
+
409
+ const nextPath = [...path];
410
+
411
+ nextPath.splice(i, 1);
412
+
413
+ if (
414
+ isUniquePath(nextPath, rootDocument)
415
+ && rootDocument.querySelector(createKnotSelector(nextPath)) === input
416
+ ) {
417
+ yield nextPath;
418
+ yield* optimize(nextPath, input, config, rootDocument, startTime);
419
+ }
420
+ }
421
+ }
422
+
423
+ function finder(input, options = {}) {
424
+ if (input.nodeType !== Node.ELEMENT_NODE) {
425
+ throw new Error(`Can't generate CSS selector for non-element node type.`);
426
+ }
427
+ if (input.tagName.toLowerCase() === 'html') {
428
+ return 'html';
429
+ }
430
+
431
+ const defaults = createFinderConfig();
432
+ const config = { ...defaults, ...options };
433
+ const startTime = Date.now();
434
+ const rootDocument = findRootDocument(config.root, defaults, input);
435
+ let foundPath;
436
+ let count = 0;
437
+
438
+ for (const candidate of search(input, config, rootDocument)) {
439
+ if (
440
+ Date.now() - startTime > config.timeoutMs
441
+ || count >= config.maxNumberOfPathChecks
442
+ ) {
443
+ const fallback = fallbackPath(input, rootDocument);
444
+
445
+ if (!fallback) {
446
+ throw new Error(
447
+ `Timeout: Can't find a unique selector after ${config.timeoutMs}ms`
448
+ );
449
+ }
450
+
451
+ return createKnotSelector(fallback);
452
+ }
453
+
454
+ count++;
455
+ if (isUniquePath(candidate, rootDocument)) {
456
+ foundPath = candidate;
457
+ break;
458
+ }
459
+ }
460
+
461
+ if (!foundPath) {
462
+ throw new Error('Selector was not found.');
463
+ }
464
+
465
+ const optimized = [...optimize(foundPath, input, config, rootDocument, startTime)];
466
+
467
+ optimized.sort(compareByPenalty);
468
+
469
+ if (optimized.length > 0) {
470
+ return createKnotSelector(optimized[0]);
471
+ }
472
+
473
+ return createKnotSelector(foundPath);
474
+ }
475
+
476
+ function getElementFilePath(el) {
477
+ return (
478
+ el.getAttribute('data-current-file-path')
479
+ || el.getAttribute('data-component-path')
480
+ );
481
+ }
482
+
483
+ function getElementSelector(el) {
484
+ try {
485
+ return finder(el);
486
+ } catch {
487
+ return null;
488
+ }
489
+ }
490
+
491
+ function enableSelector(parentOrigin) {
492
+ if (state.enabled) return;
493
+ state.enabled = true;
494
+ state.parentOrigin = parentOrigin || '*';
495
+
496
+ const overlay = ensureOverlay();
497
+
498
+ state.originalCursor = document.body.style.cursor || '';
499
+ document.body.style.cursor = 'crosshair';
500
+
501
+ state.onMove = (e) => {
502
+ const { target } = e;
503
+
504
+ if (!(target instanceof Element)) return;
505
+ if (target === overlay) return;
506
+
507
+ const rect = target.getBoundingClientRect();
508
+
509
+ overlay.style.display = 'block';
510
+ // Position overlay in page coordinates
511
+ overlay.style.left = `${rect.left + window.scrollX}px`;
512
+ overlay.style.top = `${rect.top + window.scrollY}px`;
513
+ overlay.style.width = `${rect.width}px`;
514
+ overlay.style.height = `${rect.height}px`;
515
+ };
516
+
517
+ state.onClick = (e) => {
518
+ e.preventDefault();
519
+ e.stopPropagation();
520
+
521
+ const { target } = e;
522
+
523
+ if (!(target instanceof Element)) return;
524
+ const rect = target.getBoundingClientRect();
525
+
526
+ const hasTextContent
527
+ = target.childNodes.length === 1
528
+ && target.childNodes[0].nodeType === Node.TEXT_NODE;
529
+
530
+ const payload = {
531
+ // Viewport-relative rect (parent will translate using iframe position)
532
+ rect: {
533
+ left: rect.left,
534
+ top: rect.top,
535
+ right: rect.right,
536
+ bottom: rect.bottom,
537
+ width: rect.width,
538
+ height: rect.height
539
+ },
540
+ componentName: target.getAttribute('data-component-name'),
541
+ filePath: getElementFilePath(target),
542
+ componentPath: target.getAttribute('data-component-path'),
543
+ selector: getElementSelector(target),
544
+ tagName: target.tagName.toLowerCase(),
545
+ className: target.className || '',
546
+ hasTextContent: !!hasTextContent,
547
+ textContent: hasTextContent ? (target.textContent ?? '') : null,
548
+ src:
549
+ target.tagName.toLowerCase() === 'img' ? (target.getAttribute('src') ?? '') : null
550
+ };
551
+
552
+ try {
553
+ window.parent.postMessage(
554
+ { type: MESSAGE_TYPE, action: 'elementSelected', payload },
555
+ state.parentOrigin
556
+ );
557
+ } catch {
558
+ // No-op
559
+ }
560
+
561
+ overlay.style.display = 'none';
562
+ };
563
+
564
+ state.onLeave = () => {
565
+ if (state.overlay) state.overlay.style.display = 'none';
566
+ };
567
+
568
+ document.addEventListener('pointermove', state.onMove, { passive: true });
569
+ document.addEventListener('click', state.onClick, true);
570
+ document.addEventListener('mouseleave', state.onLeave);
571
+ }
572
+
573
+ function disableSelector() {
574
+ if (!state.enabled) return;
575
+ state.enabled = false;
576
+
577
+ document.removeEventListener('pointermove', state.onMove, { passive: true });
578
+ document.removeEventListener('click', state.onClick, true);
579
+ document.removeEventListener('mouseleave', state.onLeave);
580
+
581
+ state.onMove = state.onClick = state.onLeave = null;
582
+
583
+ if (state.overlay) {
584
+ state.overlay.remove();
585
+ state.overlay = null;
586
+ }
587
+ document.body.style.cursor = state.originalCursor || '';
588
+ }
589
+
590
+ function onMessage(event) {
591
+ const { data } = event;
592
+
593
+ if (!data || data.type !== MESSAGE_TYPE) return;
594
+
595
+ if (data.action === 'enable') {
596
+ // Store initiator origin for secure replies
597
+ enableSelector(event.origin);
598
+ } else if (data.action === 'disable') {
599
+ disableSelector();
600
+ }
601
+ }
602
+
603
+ window.addEventListener('message', onMessage);
604
+ })();