@customviews-js/customviews 1.2.0 → 1.3.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.
Files changed (42) hide show
  1. package/dist/custom-views.core.cjs.js +1235 -14
  2. package/dist/custom-views.core.cjs.js.map +1 -1
  3. package/dist/custom-views.core.esm.js +1235 -14
  4. package/dist/custom-views.core.esm.js.map +1 -1
  5. package/dist/custom-views.esm.js +1235 -14
  6. package/dist/custom-views.esm.js.map +1 -1
  7. package/dist/custom-views.js +1235 -14
  8. package/dist/custom-views.js.map +1 -1
  9. package/dist/custom-views.min.js +2 -2
  10. package/dist/custom-views.min.js.map +1 -1
  11. package/dist/types/core/anchor-engine.d.ts +55 -0
  12. package/dist/types/core/anchor-engine.d.ts.map +1 -0
  13. package/dist/types/core/config.d.ts +3 -0
  14. package/dist/types/core/config.d.ts.map +1 -0
  15. package/dist/types/core/core.d.ts +10 -1
  16. package/dist/types/core/core.d.ts.map +1 -1
  17. package/dist/types/core/custom-elements.d.ts +2 -2
  18. package/dist/types/core/custom-elements.d.ts.map +1 -1
  19. package/dist/types/core/focus-manager.d.ts +38 -0
  20. package/dist/types/core/focus-manager.d.ts.map +1 -0
  21. package/dist/types/core/share-button.d.ts +13 -0
  22. package/dist/types/core/share-button.d.ts.map +1 -0
  23. package/dist/types/core/share-manager.d.ts +70 -0
  24. package/dist/types/core/share-manager.d.ts.map +1 -0
  25. package/dist/types/core/toast-manager.d.ts +12 -0
  26. package/dist/types/core/toast-manager.d.ts.map +1 -0
  27. package/dist/types/core/url-state-manager.d.ts +6 -2
  28. package/dist/types/core/url-state-manager.d.ts.map +1 -1
  29. package/dist/types/core/widget.d.ts.map +1 -1
  30. package/dist/types/styles/focus-mode-styles.d.ts +8 -0
  31. package/dist/types/styles/focus-mode-styles.d.ts.map +1 -0
  32. package/dist/types/styles/share-button-styles.d.ts +3 -0
  33. package/dist/types/styles/share-button-styles.d.ts.map +1 -0
  34. package/dist/types/styles/share-mode-styles.d.ts +10 -0
  35. package/dist/types/styles/share-mode-styles.d.ts.map +1 -0
  36. package/dist/types/styles/toast-styles.d.ts +4 -0
  37. package/dist/types/styles/toast-styles.d.ts.map +1 -0
  38. package/dist/types/types/types.d.ts +7 -0
  39. package/dist/types/types/types.d.ts.map +1 -1
  40. package/dist/types/utils/icons.d.ts +2 -0
  41. package/dist/types/utils/icons.d.ts.map +1 -1
  42. package/package.json +2 -2
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * @customviews-js/customviews v1.2.0
2
+ * @customviews-js/customviews v1.3.0
3
3
  * (c) 2025 Chan Ger Teck
4
4
  * Released under the MIT License.
5
5
  */
@@ -154,7 +154,9 @@ class URLStateManager {
154
154
  return url.toString();
155
155
  }
156
156
  /**
157
- * Encode state into URL-safe string (Toggles and Tabs only currently)
157
+ * Encode state into URL-safe string
158
+ *
159
+ * (Covers Toggles, Tabs and Focus currently)
158
160
  */
159
161
  static encodeState(state) {
160
162
  try {
@@ -168,6 +170,10 @@ class URLStateManager {
168
170
  if (state.tabs && Object.keys(state.tabs).length > 0) {
169
171
  compact.g = Object.entries(state.tabs);
170
172
  }
173
+ // Add focus if present
174
+ if (state.focus && state.focus.length > 0) {
175
+ compact.f = state.focus;
176
+ }
171
177
  // Convert to JSON and encode
172
178
  const json = JSON.stringify(compact);
173
179
  let encoded;
@@ -189,7 +195,9 @@ class URLStateManager {
189
195
  }
190
196
  }
191
197
  /**
192
- * Decode custom state from URL parameter (Toggles and Tabs only currently)
198
+ * Decode custom state from URL parameter
199
+ *
200
+ * (Covers Toggles, Tabs and Focus currently)
193
201
  */
194
202
  static decodeState(encoded) {
195
203
  try {
@@ -228,6 +236,10 @@ class URLStateManager {
228
236
  }
229
237
  }
230
238
  }
239
+ // Reconstruct Focus
240
+ if (Array.isArray(compact.f)) {
241
+ state.focus = compact.f;
242
+ }
231
243
  return state;
232
244
  }
233
245
  catch (error) {
@@ -412,6 +424,12 @@ function getPinIcon(isPinned = false) {
412
424
  </svg>
413
425
  `.trim();
414
426
  }
427
+ function getShareIcon() {
428
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
429
+ <path fill="currentColor" d="M18 8h-2a1 1 0 0 0 0 2h2v8H6v-8h2a1 1 0 0 0 0-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8a2 2 0 0 0-2-2z"/>
430
+ <path fill="currentColor" d="M11 6.41V12a1 1 0 0 0 2 0V6.41l1.29 1.3a1 1 0 0 0 1.42 0a1 1 0 0 0 0-1.42l-3-3a1 1 0 0 0-1.42 0l-3 3a1 1 0 1 0 1.42 1.42L11 6.41z"/>
431
+ </svg>`;
432
+ }
415
433
 
416
434
  // Constants for selectors
417
435
  const TABGROUP_SELECTOR$1 = 'cv-tabgroup';
@@ -1376,6 +1394,1185 @@ function injectCoreStyles() {
1376
1394
  document.head.appendChild(style);
1377
1395
  }
1378
1396
 
1397
+ const TOAST_STYLE_ID = 'cv-toast-styles';
1398
+ const TOAST_CLASS = 'cv-toast-notification';
1399
+ const TOAST_STYLES = `
1400
+ .cv-toast-notification {
1401
+ position: fixed;
1402
+ top: 20px;
1403
+ left: 50%;
1404
+ transform: translateX(-50%);
1405
+ background-color: #323232;
1406
+ color: white;
1407
+ padding: 12px 24px;
1408
+ border-radius: 4px;
1409
+ z-index: 100000;
1410
+ box-shadow: 0 4px 12px rgba(0,0,0,0.15);
1411
+ opacity: 0;
1412
+ transition: opacity 0.3s ease;
1413
+ pointer-events: none; /* Let clicks pass through if needed, though usually it blocks */
1414
+ font-family: system-ui, -apple-system, sans-serif;
1415
+ font-size: 14px;
1416
+ }
1417
+ `;
1418
+
1419
+ /**
1420
+ * Manages toast notifications for the application.
1421
+ */
1422
+ class ToastManager {
1423
+ static isStyleInjected = false;
1424
+ static toastEl = null;
1425
+ static navTimeout = null;
1426
+ static fadeTimeout = null;
1427
+ static show(message, duration = 2500) {
1428
+ this.injectStyles();
1429
+ // specific reuse logic
1430
+ if (!this.toastEl) {
1431
+ this.toastEl = document.createElement('div');
1432
+ this.toastEl.className = TOAST_CLASS;
1433
+ document.body.appendChild(this.toastEl);
1434
+ }
1435
+ // Reset state
1436
+ this.toastEl.textContent = message;
1437
+ this.toastEl.style.opacity = '0';
1438
+ this.toastEl.style.display = 'block';
1439
+ // Clear any pending dismissal
1440
+ if (this.navTimeout)
1441
+ clearTimeout(this.navTimeout);
1442
+ if (this.fadeTimeout)
1443
+ clearTimeout(this.fadeTimeout);
1444
+ // Trigger reflow & fade in
1445
+ requestAnimationFrame(() => {
1446
+ if (this.toastEl)
1447
+ this.toastEl.style.opacity = '1';
1448
+ });
1449
+ // Schedule fade out
1450
+ this.navTimeout = setTimeout(() => {
1451
+ if (this.toastEl)
1452
+ this.toastEl.style.opacity = '0';
1453
+ this.fadeTimeout = setTimeout(() => {
1454
+ if (this.toastEl)
1455
+ this.toastEl.style.display = 'none';
1456
+ }, 300);
1457
+ }, duration);
1458
+ }
1459
+ static injectStyles() {
1460
+ if (this.isStyleInjected)
1461
+ return;
1462
+ if (document.getElementById(TOAST_STYLE_ID)) {
1463
+ this.isStyleInjected = true;
1464
+ return;
1465
+ }
1466
+ const style = document.createElement('style');
1467
+ style.id = TOAST_STYLE_ID;
1468
+ style.innerHTML = TOAST_STYLES;
1469
+ document.head.appendChild(style);
1470
+ this.isStyleInjected = true;
1471
+ }
1472
+ }
1473
+
1474
+ /**
1475
+ * Engine for generating and resolving robust anchors.
1476
+ *
1477
+ * It implements a simple anchor generation and resolution algorithm that uses a combination of
1478
+ * structural, contextual, and content-based hints to generate a unique anchor for a given DOM element.
1479
+ *
1480
+ * The anchor is generated by first creating an AnchorDescriptor for the element, which contains
1481
+ * information about the element's tag, index, parent ID, and text content. This descriptor is then
1482
+ * serialized into a URL-safe string using a minification algorithm.
1483
+ *
1484
+ * The anchor is then resolved by searching for the element in the DOM using the serialized string.
1485
+ *
1486
+ */
1487
+ class AnchorEngine {
1488
+ /**
1489
+ * Generates a simple hash code for a string.
1490
+ *
1491
+ * It takes each character's Unicode code point and uses it to update the hash value.
1492
+ */
1493
+ static hashCode(str) {
1494
+ let hash = 0;
1495
+ if (str.length === 0)
1496
+ return hash;
1497
+ for (let i = 0; i < str.length; i++) {
1498
+ const char = str.charCodeAt(i);
1499
+ hash = ((hash << 5) - hash) + char;
1500
+ hash = hash & hash; // Convert to 32bit integer
1501
+ }
1502
+ return hash;
1503
+ }
1504
+ /**
1505
+ * Normalizes text content by removing excessive whitespace.
1506
+ *
1507
+ * It trims leading and trailing whitespace and replaces multiple spaces with a single space.
1508
+ */
1509
+ static normalizeText(text) {
1510
+ return text.trim().replace(/\s+/g, ' ');
1511
+ }
1512
+ /**
1513
+ * Creates an AnchorDescriptor for a given DOM element.
1514
+ */
1515
+ static createDescriptor(el) {
1516
+ const tag = el.tagName;
1517
+ const textContent = el.textContent || "";
1518
+ const normalizedText = this.normalizeText(textContent);
1519
+ // Find nearest parent with an ID
1520
+ let parentId;
1521
+ let parent = el.parentElement;
1522
+ while (parent) {
1523
+ if (parent.id) {
1524
+ parentId = parent.id;
1525
+ break;
1526
+ }
1527
+ parent = parent.parentElement;
1528
+ }
1529
+ // Calculate index relative to the container (either the found parent or document.body)
1530
+ const container = parent || document.body;
1531
+ const siblings = Array.from(container.querySelectorAll(tag));
1532
+ // Index is the position of the element in the list of siblings, where siblings are those of the same tag.
1533
+ const index = siblings.indexOf(el);
1534
+ const descriptor = {
1535
+ tag,
1536
+ index: index !== -1 ? index : 0,
1537
+ textSnippet: normalizedText.substring(0, 32),
1538
+ textHash: this.hashCode(normalizedText)
1539
+ };
1540
+ if (parentId) {
1541
+ descriptor.parentId = parentId;
1542
+ }
1543
+ return descriptor;
1544
+ }
1545
+ /**
1546
+ * Serializes a list of AnchorDescriptors into a URL-safe string.
1547
+ */
1548
+ static serialize(descriptors) {
1549
+ // Minify keys for compactness
1550
+ const minified = descriptors.map(d => ({
1551
+ t: d.tag,
1552
+ i: d.index,
1553
+ p: d.parentId,
1554
+ s: d.textSnippet,
1555
+ h: d.textHash
1556
+ }));
1557
+ const json = JSON.stringify(minified);
1558
+ // Base64 encode
1559
+ return btoa(encodeURIComponent(json));
1560
+ }
1561
+ /**
1562
+ * Deserializes a URL-safe string back into a list of AnchorDescriptors.
1563
+ */
1564
+ static deserialize(encoded) {
1565
+ try {
1566
+ const json = decodeURIComponent(atob(encoded));
1567
+ const minified = JSON.parse(json);
1568
+ return minified.map((m) => ({
1569
+ tag: m.t,
1570
+ index: m.i,
1571
+ parentId: m.p,
1572
+ textSnippet: m.s,
1573
+ textHash: m.h
1574
+ }));
1575
+ }
1576
+ catch (e) {
1577
+ console.error("Failed to deserialize anchor:", e);
1578
+ return [];
1579
+ }
1580
+ }
1581
+ /**
1582
+ * Finds the best DOM element match for a descriptor.
1583
+ */
1584
+ static resolve(root, descriptor) {
1585
+ // 1. Scope
1586
+ let scope = root;
1587
+ if (descriptor.parentId) {
1588
+ const foundParent = root.querySelector(`#${descriptor.parentId}`);
1589
+ if (foundParent instanceof HTMLElement) {
1590
+ scope = foundParent;
1591
+ }
1592
+ else {
1593
+ // Fallback: if parent ID not found, search global root - document.body
1594
+ const globalParent = document.getElementById(descriptor.parentId);
1595
+ if (globalParent) {
1596
+ scope = globalParent;
1597
+ }
1598
+ }
1599
+ }
1600
+ // 2. Candidate Search
1601
+ const candidates = Array.from(scope.querySelectorAll(descriptor.tag));
1602
+ // 3. Scoring
1603
+ let bestMatch = null;
1604
+ let highestScore = 0;
1605
+ candidates.forEach((candidate) => {
1606
+ let score = 0;
1607
+ const text = this.normalizeText(candidate.textContent || "");
1608
+ // Exact Text Match (Hash check is faster proxy for full string compare, but let's check hash first)
1609
+ if (this.hashCode(text) === descriptor.textHash) {
1610
+ score += 50;
1611
+ }
1612
+ else if (text.startsWith(descriptor.textSnippet)) {
1613
+ // Fuzzy Text Match (Snippet) - +30 score
1614
+ score += 30;
1615
+ }
1616
+ // Structural Match (Index)
1617
+ // We need to re-calculate index of this candidate to compare with descriptor.index
1618
+ // The descriptor.index is relative to the *found* parentId container.
1619
+ // So we must compare index within the scope we are searching.
1620
+ const siblings = Array.from(scope.querySelectorAll(descriptor.tag));
1621
+ const index = siblings.indexOf(candidate);
1622
+ if (index === descriptor.index) {
1623
+ score += 10;
1624
+ }
1625
+ if (score > highestScore) {
1626
+ highestScore = score;
1627
+ bestMatch = candidate;
1628
+ }
1629
+ });
1630
+ // 4. Winner
1631
+ if (highestScore > 30) {
1632
+ return bestMatch;
1633
+ }
1634
+ return null;
1635
+ }
1636
+ }
1637
+
1638
+ const SHARE_MODE_STYLE_ID = 'cv-share-mode-styles';
1639
+ const FLOATING_ACTION_BAR_ID = 'cv-floating-action-bar';
1640
+ const HOVER_HELPER_ID = 'cv-hover-helper';
1641
+ const HIGHLIGHT_TARGET_CLASS = 'cv-highlight-target';
1642
+ const SELECTED_CLASS = 'cv-share-selected';
1643
+ /**
1644
+ * CSS styles to be injected during Share Mode.
1645
+ */
1646
+ const SHARE_MODE_STYLES = `
1647
+ body.cv-share-mode {
1648
+ cursor: default;
1649
+ }
1650
+
1651
+ /* Highlight outlines */
1652
+ .${HIGHLIGHT_TARGET_CLASS} {
1653
+ outline: 2px dashed #0078D4 !important;
1654
+ outline-offset: 2px;
1655
+ cursor: crosshair;
1656
+ }
1657
+
1658
+ .${SELECTED_CLASS} {
1659
+ outline: 3px solid #005a9e !important;
1660
+ outline-offset: 2px;
1661
+ background-color: rgba(0, 120, 212, 0.05);
1662
+ }
1663
+
1664
+ /* Floating Action Bar */
1665
+ #${FLOATING_ACTION_BAR_ID} {
1666
+ position: fixed;
1667
+ bottom: 20px;
1668
+ left: 50%;
1669
+ transform: translateX(-50%);
1670
+ background-color: #2c2c2c;
1671
+ color: #f1f1f1;
1672
+ border-radius: 8px;
1673
+ padding: 12px 20px;
1674
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
1675
+ display: flex;
1676
+ align-items: center;
1677
+ gap: 16px;
1678
+ z-index: 99999;
1679
+ font-family: system-ui, -apple-system, sans-serif;
1680
+ font-size: 14px;
1681
+ border: 1px solid #4a4a4a;
1682
+ }
1683
+
1684
+ #${FLOATING_ACTION_BAR_ID} .cv-action-button {
1685
+ background-color: #0078D4;
1686
+ color: white;
1687
+ border: none;
1688
+ padding: 8px 14px;
1689
+ border-radius: 5px;
1690
+ cursor: pointer;
1691
+ font-weight: 500;
1692
+ transition: background-color 0.2s;
1693
+ }
1694
+
1695
+ #${FLOATING_ACTION_BAR_ID} .cv-action-button:hover {
1696
+ background-color: #005a9e;
1697
+ }
1698
+
1699
+ #${FLOATING_ACTION_BAR_ID} .cv-action-button.clear {
1700
+ background-color: #5a5a5a;
1701
+ }
1702
+ #${FLOATING_ACTION_BAR_ID} .cv-action-button.clear:hover {
1703
+ background-color: #4a4a4a;
1704
+ }
1705
+ #${FLOATING_ACTION_BAR_ID} .cv-action-button.clear:hover {
1706
+ background-color: #4a4a4a;
1707
+ }
1708
+
1709
+ #${FLOATING_ACTION_BAR_ID} .cv-action-button.preview {
1710
+ background-color: #106ebe;
1711
+ }
1712
+ #${FLOATING_ACTION_BAR_ID} .cv-action-button.preview:hover {
1713
+ background-color: #005a9e;
1714
+ }
1715
+ #${FLOATING_ACTION_BAR_ID} .cv-action-button.exit {
1716
+ background-color: #d13438;
1717
+ }
1718
+ #${FLOATING_ACTION_BAR_ID} .cv-action-button.exit:hover {
1719
+ background-color: #a42628;
1720
+ }
1721
+
1722
+ /* Hover Helper (Smart Label & Level Up) */
1723
+ #${HOVER_HELPER_ID} {
1724
+ position: fixed;
1725
+ z-index: 99999;
1726
+ background-color: #333;
1727
+ color: white;
1728
+ padding: 4px 8px;
1729
+ border-radius: 4px;
1730
+ font-size: 12px;
1731
+ font-family: monospace;
1732
+ display: none;
1733
+ pointer-events: auto; /* Allow clicking buttons inside */
1734
+ align-items: center;
1735
+ gap: 8px;
1736
+ box-shadow: 0 2px 5px rgba(0,0,0,0.2);
1737
+ }
1738
+
1739
+ #${HOVER_HELPER_ID} button {
1740
+ background: #555;
1741
+ border: none;
1742
+ color: white;
1743
+ border-radius: 3px;
1744
+ cursor: pointer;
1745
+ padding: 2px 6px;
1746
+ font-size: 14px;
1747
+ line-height: 1;
1748
+ }
1749
+ #${HOVER_HELPER_ID} button:hover {
1750
+ background: #777;
1751
+ }
1752
+
1753
+ `;
1754
+
1755
+ const CV_CUSTOM_ELEMENTS = 'cv-tabgroup, cv-toggle';
1756
+ const SHAREABLE_SELECTOR = 'div, p, blockquote, pre, li, h1, h2, h3, h4, h5, h6, [data-share], ' + CV_CUSTOM_ELEMENTS;
1757
+ /**
1758
+ * Manages the "Share Mode" for creating custom focus links.
1759
+ * Implementing Robust Granular Sharing with "Innermost Wins" and "Level Up" UI.
1760
+ */
1761
+ class ShareManager {
1762
+ isActive = false;
1763
+ selectedElements = new Set();
1764
+ floatingBarEl = null;
1765
+ helperEl = null;
1766
+ currentHoverTarget = null;
1767
+ excludedTags;
1768
+ excludedIds;
1769
+ boundHandleHover;
1770
+ boundHandleClick;
1771
+ boundHandleKeydown;
1772
+ constructor(options) {
1773
+ this.excludedTags = new Set(options.excludedTags.map(t => t.toUpperCase()));
1774
+ this.excludedIds = new Set(options.excludedIds);
1775
+ this.boundHandleHover = this.handleHover.bind(this);
1776
+ this.boundHandleClick = this.handleClick.bind(this);
1777
+ this.boundHandleKeydown = this.handleKeydown.bind(this);
1778
+ }
1779
+ listeners = [];
1780
+ addStateChangeListener(listener) {
1781
+ this.listeners.push(listener);
1782
+ }
1783
+ removeStateChangeListener(listener) {
1784
+ this.listeners = this.listeners.filter(l => l !== listener);
1785
+ }
1786
+ notifyListeners() {
1787
+ this.listeners.forEach(listener => listener(this.isActive));
1788
+ }
1789
+ toggleShareMode() {
1790
+ this.isActive = !this.isActive;
1791
+ if (this.isActive) {
1792
+ this.activate();
1793
+ }
1794
+ else {
1795
+ this.cleanup();
1796
+ }
1797
+ this.notifyListeners();
1798
+ }
1799
+ /**
1800
+ * Activates the share mode.
1801
+ * Injects styles, creates floating bar, and helper element.
1802
+ * Adds event listeners for hover and click.
1803
+ */
1804
+ activate() {
1805
+ this.injectStyles();
1806
+ this.createFloatingBar();
1807
+ this.helperEl = this.createHelperPopover();
1808
+ // Event Listeners
1809
+ document.addEventListener('mouseover', this.boundHandleHover, true);
1810
+ document.addEventListener('click', this.boundHandleClick, true);
1811
+ document.addEventListener('keydown', this.boundHandleKeydown, true);
1812
+ }
1813
+ injectStyles() {
1814
+ const styleElement = document.createElement('style');
1815
+ styleElement.id = SHARE_MODE_STYLE_ID;
1816
+ styleElement.innerHTML = SHARE_MODE_STYLES;
1817
+ document.head.appendChild(styleElement);
1818
+ }
1819
+ /**
1820
+ * Creates the hover helper element that shows up when hovering over a shareable element.
1821
+ */
1822
+ createHelperPopover() {
1823
+ const div = document.createElement('div');
1824
+ div.id = HOVER_HELPER_ID;
1825
+ div.innerHTML = `
1826
+ <span id="cv-helper-tag">TAG</span>
1827
+ <button id="cv-helper-select-btn" title="Select This Element">✓</button>
1828
+ <button id="cv-helper-up-btn" title="Select Parent">↰</button>
1829
+ `;
1830
+ document.body.appendChild(div);
1831
+ // Select parent button
1832
+ div.querySelector('#cv-helper-up-btn')?.addEventListener('click', (e) => {
1833
+ e.preventDefault();
1834
+ e.stopPropagation();
1835
+ this.handleSelectParent();
1836
+ });
1837
+ // Select element button
1838
+ div.querySelector('#cv-helper-select-btn')?.addEventListener('click', (e) => {
1839
+ e.preventDefault();
1840
+ e.stopPropagation();
1841
+ if (this.currentHoverTarget) {
1842
+ this.toggleSelection(this.currentHoverTarget);
1843
+ }
1844
+ });
1845
+ return div;
1846
+ }
1847
+ /**
1848
+ * Handles mouse hover events.
1849
+ *
1850
+ * This function is called when the user hovers over an element.
1851
+ * It checks if the element is shareable and highlights it.
1852
+ * If a parent element is already selected, it highlights the parent instead,
1853
+ * allowing the helper to remain visible for the selected parent.
1854
+ *
1855
+ * @param e The mouse event triggered by the hover.
1856
+ */
1857
+ handleHover(e) {
1858
+ if (!this.isActive)
1859
+ return;
1860
+ // Check if we are hovering over the helper itself
1861
+ if (this.helperEl && this.helperEl.contains(e.target)) {
1862
+ return;
1863
+ }
1864
+ const target = e.target;
1865
+ // Exclude by Tag or ID
1866
+ const upperTag = target.tagName.toUpperCase();
1867
+ if (this.excludedTags.has(upperTag) || (target.id && this.excludedIds.has(target.id))) {
1868
+ return;
1869
+ }
1870
+ // Check closest excluded (for nested elements in excluded regions)
1871
+ let ancestor = target.parentElement;
1872
+ while (ancestor) {
1873
+ if (this.excludedTags.has(ancestor.tagName.toUpperCase()) || (ancestor.id && this.excludedIds.has(ancestor.id))) {
1874
+ return;
1875
+ }
1876
+ ancestor = ancestor.parentElement;
1877
+ }
1878
+ // Find closest shareable parent element
1879
+ const shareablePart = target.closest(SHAREABLE_SELECTOR);
1880
+ if (!shareablePart) {
1881
+ this.clearHover();
1882
+ return;
1883
+ }
1884
+ // Cast to HTMLElement
1885
+ const finalTarget = shareablePart;
1886
+ // Check if any ancestor is already selected. If so, do NOT highlight this child.
1887
+ // Instead, highlight (or keep highlighted) the SELECTED PARENT so the user can see the helper for it.
1888
+ let parent = finalTarget.parentElement;
1889
+ let selectedAncestor = null;
1890
+ // Loop outwards until we find a selected parent or reach the top
1891
+ while (parent) {
1892
+ if (this.selectedElements.has(parent)) {
1893
+ selectedAncestor = parent;
1894
+ break;
1895
+ }
1896
+ parent = parent.parentElement;
1897
+ }
1898
+ if (selectedAncestor) {
1899
+ // If we are hovering deep inside a selected block, show the helper for that block
1900
+ this.setNewHoverTarget(selectedAncestor);
1901
+ return;
1902
+ }
1903
+ // stop bubbling to parent
1904
+ // when element found for highlight
1905
+ e.stopPropagation();
1906
+ // If we are already on this target, do nothing (and keep it selected/highlighted)
1907
+ if (this.currentHoverTarget === finalTarget)
1908
+ return;
1909
+ // Highlight
1910
+ this.setNewHoverTarget(finalTarget);
1911
+ }
1912
+ setNewHoverTarget(target) {
1913
+ if (this.currentHoverTarget) {
1914
+ this.currentHoverTarget.classList.remove(HIGHLIGHT_TARGET_CLASS);
1915
+ }
1916
+ this.currentHoverTarget = target;
1917
+ this.currentHoverTarget.classList.add(HIGHLIGHT_TARGET_CLASS);
1918
+ this.positionHelper(target);
1919
+ }
1920
+ positionHelper(target) {
1921
+ if (!this.helperEl)
1922
+ return;
1923
+ const rect = target.getBoundingClientRect();
1924
+ const tagLabel = this.helperEl.querySelector('#cv-helper-tag');
1925
+ const upBtn = this.helperEl.querySelector('#cv-helper-up-btn');
1926
+ if (tagLabel)
1927
+ tagLabel.textContent = target.tagName;
1928
+ // Position at top-right of the element
1929
+ // Prevent going off-screen
1930
+ let top = rect.top - 20;
1931
+ if (top < 0)
1932
+ top = rect.top + 10; // Flip down if too close to top
1933
+ let left = rect.right - 80;
1934
+ if (left < 0)
1935
+ left = 10;
1936
+ this.helperEl.style.display = 'flex';
1937
+ this.helperEl.style.top = `${top}px`;
1938
+ this.helperEl.style.left = `${left}px`;
1939
+ // Update Select Button State (Tick or Cross)
1940
+ const selectBtn = this.helperEl.querySelector('#cv-helper-select-btn');
1941
+ if (selectBtn) {
1942
+ if (this.selectedElements.has(target)) {
1943
+ selectBtn.textContent = '✕';
1944
+ selectBtn.title = 'Deselect This Element';
1945
+ selectBtn.style.backgroundColor = '#d13438'; // Reddish
1946
+ }
1947
+ else {
1948
+ selectBtn.textContent = '✓';
1949
+ selectBtn.title = 'Select This Element';
1950
+ selectBtn.style.backgroundColor = ''; // Reset
1951
+ }
1952
+ }
1953
+ // Ancestry Check
1954
+ const parent = target.parentElement;
1955
+ const parentIsShareable = parent && parent.matches(SHAREABLE_SELECTOR);
1956
+ if (parentIsShareable) {
1957
+ upBtn.style.display = 'inline-block';
1958
+ }
1959
+ else {
1960
+ upBtn.style.display = 'none';
1961
+ }
1962
+ }
1963
+ handleSelectParent() {
1964
+ if (this.currentHoverTarget && this.currentHoverTarget.parentElement) {
1965
+ const parent = this.currentHoverTarget.parentElement;
1966
+ if (parent.matches(SHAREABLE_SELECTOR)) {
1967
+ this.setNewHoverTarget(parent);
1968
+ }
1969
+ }
1970
+ }
1971
+ handleClick(e) {
1972
+ if (!this.isActive)
1973
+ return;
1974
+ // If clicking helper
1975
+ if (this.helperEl && this.helperEl.contains(e.target))
1976
+ return;
1977
+ // If clicking floating bar
1978
+ if (this.floatingBarEl && this.floatingBarEl.contains(e.target))
1979
+ return;
1980
+ e.preventDefault();
1981
+ e.stopPropagation();
1982
+ if (this.currentHoverTarget) {
1983
+ this.toggleSelection(this.currentHoverTarget);
1984
+ }
1985
+ }
1986
+ handleKeydown(e) {
1987
+ if (!this.isActive)
1988
+ return;
1989
+ if (e.key === 'Escape') {
1990
+ e.preventDefault();
1991
+ e.stopPropagation();
1992
+ this.toggleShareMode();
1993
+ }
1994
+ }
1995
+ /**
1996
+ * Toggles the selection state of a given HTML element.
1997
+ * Implements selection logic:
1998
+ * - If an ancestor of the element is already selected, the click is ignored.
1999
+ * - If the element being selected is a parent of already selected elements, those children are deselected.
2000
+ * @param el The HTMLElement to toggle selection for.
2001
+ */
2002
+ toggleSelection(el) {
2003
+ if (this.selectedElements.has(el)) {
2004
+ this.selectedElements.delete(el);
2005
+ el.classList.remove(SELECTED_CLASS);
2006
+ }
2007
+ else {
2008
+ // Selection Logic
2009
+ // Scenario A: Selecting a Parent -> Remove children selected while selecting parent
2010
+ // Scenario B: Selecting a Child -> Ignore if ancestor selected (or handle)
2011
+ // B. Check if any ancestor is already selected, return if any (Scenario B)
2012
+ let parent = el.parentElement;
2013
+ while (parent) {
2014
+ if (this.selectedElements.has(parent)) {
2015
+ // Ancestor is selected. Ignore click.
2016
+ return;
2017
+ }
2018
+ parent = parent.parentElement;
2019
+ }
2020
+ // A. Check if any children are selected (Scenario A)
2021
+ // We must iterate over currently selected elements
2022
+ const toRemove = [];
2023
+ this.selectedElements.forEach(selected => {
2024
+ if (el.contains(selected) && el !== selected) {
2025
+ toRemove.push(selected);
2026
+ }
2027
+ });
2028
+ toRemove.forEach(child => {
2029
+ this.selectedElements.delete(child);
2030
+ child.classList.remove(SELECTED_CLASS);
2031
+ });
2032
+ // Add new selection
2033
+ this.selectedElements.add(el);
2034
+ el.classList.add(SELECTED_CLASS);
2035
+ }
2036
+ this.updateFloatingBarCount();
2037
+ }
2038
+ createFloatingBar() {
2039
+ const bar = document.createElement('div');
2040
+ bar.id = FLOATING_ACTION_BAR_ID;
2041
+ bar.innerHTML = `
2042
+ <span id="cv-selected-count">0 items selected</span>
2043
+ <button class="cv-action-button clear">Clear All</button>
2044
+ <button class="cv-action-button preview">Preview</button>
2045
+ <button class="cv-action-button generate">Generate Link</button>
2046
+ <button class="cv-action-button exit">Exit</button>
2047
+ `;
2048
+ document.body.appendChild(bar);
2049
+ this.floatingBarEl = bar;
2050
+ bar.querySelector('.clear')?.addEventListener('click', () => this.clearAll());
2051
+ bar.querySelector('.preview')?.addEventListener('click', () => this.previewLink());
2052
+ bar.querySelector('.generate')?.addEventListener('click', () => this.generateLink());
2053
+ bar.querySelector('.exit')?.addEventListener('click', () => this.toggleShareMode());
2054
+ }
2055
+ updateFloatingBarCount() {
2056
+ if (this.floatingBarEl) {
2057
+ const countElement = this.floatingBarEl.querySelector('#cv-selected-count');
2058
+ if (countElement) {
2059
+ const count = this.selectedElements.size;
2060
+ countElement.textContent = `${count} item${count === 1 ? '' : 's'} selected`;
2061
+ }
2062
+ }
2063
+ }
2064
+ clearAll() {
2065
+ this.selectedElements.forEach(el => el.classList.remove('cv-share-selected'));
2066
+ this.selectedElements.clear();
2067
+ this.updateFloatingBarCount();
2068
+ }
2069
+ getShareUrl() {
2070
+ if (this.selectedElements.size === 0) {
2071
+ return null;
2072
+ }
2073
+ const descriptors = Array.from(this.selectedElements).map(el => AnchorEngine.createDescriptor(el));
2074
+ const serialized = AnchorEngine.serialize(descriptors);
2075
+ const url = new URL(window.location.href);
2076
+ url.searchParams.set('cv-focus', serialized);
2077
+ return url;
2078
+ }
2079
+ async generateLink() {
2080
+ const url = this.getShareUrl();
2081
+ if (!url) {
2082
+ ToastManager.show('Please select at least one item.');
2083
+ return;
2084
+ }
2085
+ try {
2086
+ await navigator.clipboard.writeText(url.toString());
2087
+ ToastManager.show('Link copied to clipboard!');
2088
+ }
2089
+ catch (e) {
2090
+ console.error('Clipboard failed', e);
2091
+ ToastManager.show('Failed to copy link.');
2092
+ }
2093
+ }
2094
+ previewLink() {
2095
+ const url = this.getShareUrl();
2096
+ if (!url) {
2097
+ ToastManager.show('Please select at least one item.');
2098
+ return;
2099
+ }
2100
+ window.open(url.toString(), '_blank');
2101
+ }
2102
+ clearHover() {
2103
+ if (this.currentHoverTarget) {
2104
+ this.currentHoverTarget.classList.remove(HIGHLIGHT_TARGET_CLASS);
2105
+ this.currentHoverTarget = null;
2106
+ }
2107
+ if (this.helperEl) {
2108
+ this.helperEl.style.display = 'none';
2109
+ }
2110
+ }
2111
+ cleanup() {
2112
+ document.body.classList.remove('cv-share-mode');
2113
+ this.clearAll();
2114
+ const style = document.getElementById(SHARE_MODE_STYLE_ID);
2115
+ if (style)
2116
+ document.head.removeChild(style);
2117
+ if (this.floatingBarEl) {
2118
+ document.body.removeChild(this.floatingBarEl);
2119
+ this.floatingBarEl = null;
2120
+ }
2121
+ if (this.helperEl) {
2122
+ document.body.removeChild(this.helperEl);
2123
+ this.helperEl = null;
2124
+ }
2125
+ if (this.currentHoverTarget) {
2126
+ this.currentHoverTarget.classList.remove(HIGHLIGHT_TARGET_CLASS);
2127
+ this.currentHoverTarget = null;
2128
+ }
2129
+ document.removeEventListener('mouseover', this.boundHandleHover, true);
2130
+ document.removeEventListener('click', this.boundHandleClick, true);
2131
+ document.removeEventListener('keydown', this.boundHandleKeydown, true);
2132
+ this.isActive = false;
2133
+ }
2134
+ }
2135
+
2136
+ const SHARE_BUTTON_ID = 'cv-share-button';
2137
+ const SHARE_BUTTON_STYLES = `
2138
+ #${SHARE_BUTTON_ID} {
2139
+ position: fixed;
2140
+ bottom: 20px;
2141
+ right: 100px;
2142
+ width: 50px;
2143
+ height: 50px;
2144
+ border-radius: 50%;
2145
+ background-color: #007bff; /* Primary Blue */
2146
+ color: white;
2147
+ border: none;
2148
+ box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 1px 3px rgba(0, 0, 0, 0.08); /* Drop shadow */
2149
+ z-index: 9998; /* Below modals (9999) but above content */
2150
+ cursor: pointer;
2151
+ display: flex;
2152
+ align-items: center;
2153
+ justify-content: center;
2154
+ transition: opacity 0.3s ease, transform 0.3s ease, background-color 0.2s;
2155
+ opacity: 1;
2156
+ transform: scale(1);
2157
+ padding: 0;
2158
+ margin: 0;
2159
+ }
2160
+
2161
+ #${SHARE_BUTTON_ID}:hover {
2162
+ background-color: #0056b3; /* Darker blue on hover */
2163
+ transform: scale(1.05);
2164
+ }
2165
+
2166
+ #${SHARE_BUTTON_ID}:active {
2167
+ transform: scale(0.95);
2168
+ }
2169
+
2170
+ #${SHARE_BUTTON_ID}.cv-hidden {
2171
+ opacity: 0;
2172
+ pointer-events: none;
2173
+ transform: scale(0.8);
2174
+ }
2175
+
2176
+ @media print {
2177
+ #${SHARE_BUTTON_ID} {
2178
+ display: none !important;
2179
+ }
2180
+ }
2181
+
2182
+ #${SHARE_BUTTON_ID} svg {
2183
+ width: 24px;
2184
+ height: 24px;
2185
+ fill: currentColor;
2186
+ }
2187
+ `;
2188
+
2189
+ class ShareButton {
2190
+ shareManager;
2191
+ button = null;
2192
+ boundHandleClick;
2193
+ constructor(shareManager) {
2194
+ this.shareManager = shareManager;
2195
+ this.boundHandleClick = () => this.shareManager.toggleShareMode();
2196
+ }
2197
+ init() {
2198
+ if (this.button)
2199
+ return;
2200
+ this.injectStyles();
2201
+ this.button = this.createButton();
2202
+ document.body.appendChild(this.button);
2203
+ // Subscribe to share manager state changes
2204
+ this.shareManager.addStateChangeListener((isActive) => {
2205
+ this.setShareModeActive(isActive);
2206
+ });
2207
+ }
2208
+ destroy() {
2209
+ if (this.button) {
2210
+ this.button.remove();
2211
+ this.button = null;
2212
+ }
2213
+ }
2214
+ createButton() {
2215
+ const btn = document.createElement('button');
2216
+ btn.id = SHARE_BUTTON_ID;
2217
+ btn.setAttribute('aria-label', 'Share specific sections');
2218
+ btn.title = 'Select sections to share';
2219
+ // Using the link icon from utils, ensuring it's white via CSS currentColor
2220
+ btn.innerHTML = getShareIcon();
2221
+ btn.addEventListener('click', this.boundHandleClick);
2222
+ return btn;
2223
+ }
2224
+ injectStyles() {
2225
+ if (!document.getElementById('cv-share-button-styles')) {
2226
+ const style = document.createElement('style');
2227
+ style.id = 'cv-share-button-styles';
2228
+ style.textContent = SHARE_BUTTON_STYLES;
2229
+ document.head.appendChild(style);
2230
+ }
2231
+ }
2232
+ setShareModeActive(isActive) {
2233
+ if (!this.button)
2234
+ return;
2235
+ if (isActive) {
2236
+ this.button.classList.add('cv-hidden');
2237
+ }
2238
+ else {
2239
+ this.button.classList.remove('cv-hidden');
2240
+ }
2241
+ }
2242
+ }
2243
+
2244
+ const FOCUS_MODE_STYLE_ID = 'cv-focus-mode-styles';
2245
+ const BODY_FOCUS_CLASS = 'cv-focus-mode';
2246
+ const HIDDEN_CLASS = 'cv-focus-hidden';
2247
+ const FOCUSED_CLASS = 'cv-focused-element';
2248
+ const DIVIDER_CLASS = 'cv-context-divider';
2249
+ const EXIT_BANNER_ID = 'cv-exit-focus-banner';
2250
+ const styles = `
2251
+ body.${BODY_FOCUS_CLASS} {
2252
+ /* e.g. potentially hide scrollbars or adjust layout */
2253
+ }
2254
+
2255
+ .${HIDDEN_CLASS} {
2256
+ display: none !important;
2257
+ }
2258
+
2259
+ .${FOCUSED_CLASS} {
2260
+ /* No visual style for focused elements, just logic class for now. Can add borders for debugging*/
2261
+ }
2262
+
2263
+ .${DIVIDER_CLASS} {
2264
+ padding: 12px;
2265
+ margin: 16px 0;
2266
+ background-color: #f8f8f8;
2267
+ border-top: 1px dashed #ccc;
2268
+ border-bottom: 1px dashed #ccc;
2269
+ color: #555;
2270
+ text-align: center;
2271
+ cursor: pointer;
2272
+ font-family: system-ui, sans-serif;
2273
+ font-size: 13px;
2274
+ transition: background-color 0.2s;
2275
+ }
2276
+ .${DIVIDER_CLASS}:hover {
2277
+ background-color: #e8e8e8;
2278
+ color: #333;
2279
+ }
2280
+
2281
+ #${EXIT_BANNER_ID} {
2282
+ position: sticky;
2283
+ top: 0;
2284
+ left: 0;
2285
+ right: 0;
2286
+ background-color: #0078D4;
2287
+ color: white;
2288
+ padding: 10px 20px;
2289
+ display: flex;
2290
+ align-items: center;
2291
+ justify-content: center;
2292
+ gap: 16px;
2293
+ z-index: 100000;
2294
+ font-family: system-ui, sans-serif;
2295
+ box-shadow: 0 2px 8px rgba(0,0,0,0.2);
2296
+ }
2297
+
2298
+ #${EXIT_BANNER_ID} button {
2299
+ background: white;
2300
+ color: #0078D4;
2301
+ border: none;
2302
+ padding: 4px 12px;
2303
+ border-radius: 4px;
2304
+ cursor: pointer;
2305
+ font-weight: 600;
2306
+ }
2307
+ #${EXIT_BANNER_ID} button:hover {
2308
+ background: #f0f0f0;
2309
+ }
2310
+ `;
2311
+ const FOCUS_MODE_STYLES = styles;
2312
+
2313
+ /**
2314
+ * Manages the "Focus Mode" (Presentation View).
2315
+ * Parses the URL for robust anchors, resolves them, hides irrelevant content, and inserts context dividers.
2316
+ */
2317
+ const FOCUS_PARAM = 'cv-focus';
2318
+ class FocusManager {
2319
+ rootEl;
2320
+ hiddenElements = new Set();
2321
+ dividers = [];
2322
+ exitBanner = null;
2323
+ excludedTags;
2324
+ excludedIds;
2325
+ constructor(rootEl, options) {
2326
+ this.rootEl = rootEl;
2327
+ this.excludedTags = new Set(options.excludedTags.map(t => t.toUpperCase()));
2328
+ this.excludedIds = new Set(options.excludedIds);
2329
+ }
2330
+ /**
2331
+ * Initializes the Focus Manager. Checks URL for focus parameter.
2332
+ */
2333
+ init() {
2334
+ this.handleUrlChange();
2335
+ }
2336
+ handleUrlChange() {
2337
+ const urlParams = new URLSearchParams(window.location.search);
2338
+ const encodedDescriptors = urlParams.get(FOCUS_PARAM);
2339
+ if (encodedDescriptors) {
2340
+ this.applyFocusMode(encodedDescriptors);
2341
+ }
2342
+ else {
2343
+ // encoding missing, ensure we exit focus mode if active
2344
+ if (document.body.classList.contains(BODY_FOCUS_CLASS)) {
2345
+ this.exitFocusMode();
2346
+ }
2347
+ }
2348
+ }
2349
+ /**
2350
+ * Applies Focus Mode based on encoded descriptors.
2351
+ */
2352
+ applyFocusMode(encodedDescriptors) {
2353
+ const descriptors = AnchorEngine.deserialize(encodedDescriptors);
2354
+ if (!descriptors || descriptors.length === 0)
2355
+ return;
2356
+ // Resolve anchors to DOM elements
2357
+ const targets = [];
2358
+ descriptors.forEach(desc => {
2359
+ const el = AnchorEngine.resolve(this.rootEl, desc);
2360
+ if (el) {
2361
+ targets.push(el);
2362
+ }
2363
+ });
2364
+ if (targets.length === 0) {
2365
+ ToastManager.show("Some shared sections could not be found.");
2366
+ return;
2367
+ }
2368
+ if (targets.length < descriptors.length) {
2369
+ ToastManager.show("Some shared sections could not be found.");
2370
+ }
2371
+ this.injectStyles();
2372
+ document.body.classList.add(BODY_FOCUS_CLASS);
2373
+ this.renderFocusedView(targets);
2374
+ this.showExitBanner();
2375
+ }
2376
+ injectStyles() {
2377
+ if (document.getElementById(FOCUS_MODE_STYLE_ID))
2378
+ return;
2379
+ const style = document.createElement('style');
2380
+ style.id = FOCUS_MODE_STYLE_ID;
2381
+ style.textContent = FOCUS_MODE_STYLES;
2382
+ document.head.appendChild(style);
2383
+ }
2384
+ /**
2385
+ * Hides irrelevant content and adds dividers.
2386
+ */
2387
+ renderFocusedView(targets) {
2388
+ // 1. Mark targets
2389
+ targets.forEach(t => t.classList.add(FOCUSED_CLASS));
2390
+ // 2. We need to hide siblings of targets (and their ancestors up to root generally,
2391
+ // but "siblings between focused zones" suggests we are mostly looking at a flat list or specific nesting).
2392
+ //
2393
+ // "All sibling elements between the focused zones are collapsed and hidden."
2394
+ // "If a user selects a parent element, all of its child elements must be visible."
2395
+ //
2396
+ // Algorithm:
2397
+ // Walk up from each target to finding the common container?
2398
+ // Or just assume targets are somewhat related.
2399
+ //
2400
+ // Let's implement a robust "Hide Siblings" approach.
2401
+ // For every target, we ensure it is visible.
2402
+ // We look at its siblings. If a sibling is NOT a target AND NOT an ancestor of a target, we hide it.
2403
+ // We need to identify all "Keep Visible" elements (targets + ancestors)
2404
+ const keepVisible = new Set();
2405
+ targets.forEach(t => {
2406
+ let curr = t;
2407
+ while (curr && curr !== document.body && curr !== document.documentElement) {
2408
+ keepVisible.add(curr);
2409
+ curr = curr.parentElement;
2410
+ }
2411
+ });
2412
+ // Now iterate through siblings of "Keep Visible" elements?
2413
+ // Actually, we can just walk the tree or iterate siblings of targets/ancestors?
2414
+ //
2415
+ // Improved Algorithm:
2416
+ // 1. Collect all direct siblings of every element in keepVisible set.
2417
+ // 2. If a sibling is NOT in keepVisible, hide it.
2418
+ // To avoid processing the entire DOM, we start from targets and walk up.
2419
+ keepVisible.forEach(el => {
2420
+ if (el === document.body)
2421
+ return; // Don't hide siblings of body (scripts etc) unless we are sure.
2422
+ // Actually usually we want to hide siblings of the content container.
2423
+ const parent = el.parentElement;
2424
+ if (!parent)
2425
+ return;
2426
+ // FIX: "Parent Dominance"
2427
+ // If the parent itself is a target (or we otherwise decided its whole content is meaningful),
2428
+ // then we should NOT hide anything inside it.
2429
+ // We check if 'parent' is one of the explicitly resolved targets.
2430
+ // We can check if it has the FOCUSED_CLASS class, since we added it in step 1.
2431
+ if (parent.classList.contains(FOCUSED_CLASS)) {
2432
+ return;
2433
+ }
2434
+ // Using children because we want element nodes
2435
+ Array.from(parent.children).forEach(child => {
2436
+ if (child instanceof HTMLElement && !keepVisible.has(child)) {
2437
+ this.hideElement(child);
2438
+ }
2439
+ });
2440
+ });
2441
+ // 3. Insert Dividers
2442
+ // We process each container that has hidden elements
2443
+ const processedContainers = new Set();
2444
+ keepVisible.forEach(el => {
2445
+ const parent = el.parentElement;
2446
+ if (parent && !processedContainers.has(parent)) {
2447
+ this.insertDividersForContainer(parent);
2448
+ processedContainers.add(parent);
2449
+ }
2450
+ });
2451
+ }
2452
+ hideElement(el) {
2453
+ if (this.hiddenElements.has(el))
2454
+ return; // Already hidden
2455
+ // Exclude by Tag
2456
+ if (this.excludedTags.has(el.tagName.toUpperCase()))
2457
+ return;
2458
+ // Exclude by ID (if strictly matching)
2459
+ if (el.id && this.excludedIds.has(el.id))
2460
+ return;
2461
+ // Also don't hide things that are aria-hidden
2462
+ if (el.getAttribute('aria-hidden') === 'true')
2463
+ return;
2464
+ // Exclude Toast Notification
2465
+ if (el.classList.contains(TOAST_CLASS))
2466
+ return;
2467
+ // We check if it is already hidden (e.g. by previous focus mode run? No, isActive check handles that)
2468
+ // Just mark it.
2469
+ el.classList.add(HIDDEN_CLASS);
2470
+ this.hiddenElements.add(el);
2471
+ }
2472
+ insertDividersForContainer(container) {
2473
+ const children = Array.from(container.children);
2474
+ let hiddenCount = 0;
2475
+ let hiddenGroupStart = null;
2476
+ children.forEach((child) => {
2477
+ if (child.classList.contains(HIDDEN_CLASS)) {
2478
+ if (hiddenCount === 0)
2479
+ hiddenGroupStart = child;
2480
+ hiddenCount++;
2481
+ }
2482
+ else {
2483
+ // Found a visible element. Was there a hidden group before this?
2484
+ if (hiddenCount > 0 && hiddenGroupStart) {
2485
+ this.createDivider(container, hiddenGroupStart, hiddenCount);
2486
+ hiddenCount = 0;
2487
+ hiddenGroupStart = null;
2488
+ }
2489
+ }
2490
+ });
2491
+ // Trailing hidden group
2492
+ if (hiddenCount > 0 && hiddenGroupStart) {
2493
+ this.createDivider(container, hiddenGroupStart, hiddenCount);
2494
+ }
2495
+ }
2496
+ createDivider(container, insertBeforeEl, count) {
2497
+ const divider = document.createElement('div');
2498
+ divider.className = DIVIDER_CLASS;
2499
+ divider.textContent = `... ${count} section${count > 1 ? 's' : ''} hidden (Click to expand) ...`;
2500
+ divider.onclick = () => this.expandContext(insertBeforeEl, count, divider);
2501
+ container.insertBefore(divider, insertBeforeEl);
2502
+ this.dividers.push(divider);
2503
+ }
2504
+ expandContext(firstHidden, count, divider) {
2505
+ // Divider is inserted BEFORE firstHidden.
2506
+ // So firstHidden is the first element to reveal.
2507
+ let curr = firstHidden;
2508
+ let expanded = 0;
2509
+ while (curr && expanded < count) {
2510
+ if (curr instanceof HTMLElement && curr.classList.contains(HIDDEN_CLASS)) {
2511
+ curr.classList.remove(HIDDEN_CLASS);
2512
+ this.hiddenElements.delete(curr);
2513
+ }
2514
+ curr = curr.nextElementSibling;
2515
+ // Note: If nested dividers or other elements exist, they shouldn't count?
2516
+ // "Children" iteration in insertDividers covered direct children.
2517
+ // sibling iteration also covers direct children.
2518
+ // We assume contiguous hidden siblings.
2519
+ expanded++;
2520
+ }
2521
+ divider.remove();
2522
+ const idx = this.dividers.indexOf(divider);
2523
+ if (idx > -1)
2524
+ this.dividers.splice(idx, 1);
2525
+ // If no more hidden elements, remove the banner
2526
+ if (this.hiddenElements.size === 0) {
2527
+ this.removeExitBanner();
2528
+ }
2529
+ }
2530
+ removeExitBanner() {
2531
+ if (this.exitBanner) {
2532
+ this.exitBanner.remove();
2533
+ this.exitBanner = null;
2534
+ }
2535
+ }
2536
+ /**
2537
+ * Override of renderFocusedView with robust logic
2538
+ */
2539
+ // (We use the class method `renderFocusedView` and internal helpers)
2540
+ showExitBanner() {
2541
+ if (document.getElementById(EXIT_BANNER_ID))
2542
+ return;
2543
+ const banner = document.createElement('div');
2544
+ banner.id = EXIT_BANNER_ID;
2545
+ banner.innerHTML = `
2546
+ <span>You are viewing a focused selection.</span>
2547
+ <button id="cv-exit-focus-btn">Show Full Page</button>
2548
+ `;
2549
+ document.body.prepend(banner); // Top of body
2550
+ banner.querySelector('button')?.addEventListener('click', () => this.exitFocusMode());
2551
+ this.exitBanner = banner;
2552
+ }
2553
+ exitFocusMode() {
2554
+ document.body.classList.remove(BODY_FOCUS_CLASS);
2555
+ // Show all hidden elements
2556
+ this.hiddenElements.forEach(el => el.classList.remove(HIDDEN_CLASS));
2557
+ this.hiddenElements.clear();
2558
+ // Remove dividers
2559
+ this.dividers.forEach(d => d.remove());
2560
+ this.dividers = [];
2561
+ // Remove styling from targets
2562
+ const targets = document.querySelectorAll(`.${FOCUSED_CLASS}`);
2563
+ targets.forEach(t => t.classList.remove(FOCUSED_CLASS));
2564
+ // Remove banner
2565
+ this.removeExitBanner();
2566
+ // Update URL
2567
+ const url = new URL(window.location.href);
2568
+ url.searchParams.delete(FOCUS_PARAM);
2569
+ window.history.pushState({}, '', url.toString());
2570
+ }
2571
+ }
2572
+
2573
+ const DEFAULT_EXCLUDED_TAGS = ['HEADER', 'NAV', 'FOOTER', 'SCRIPT', 'STYLE'];
2574
+ const DEFAULT_EXCLUDED_IDS = ['cv-floating-action-bar', 'cv-hover-helper', 'cv-toast-notification'];
2575
+
1379
2576
  const TOGGLE_SELECTOR = "[data-cv-toggle], [data-customviews-toggle], cv-toggle";
1380
2577
  const TABGROUP_SELECTOR = 'cv-tabgroup';
1381
2578
  class CustomViewsCore {
@@ -1384,6 +2581,9 @@ class CustomViewsCore {
1384
2581
  persistenceManager;
1385
2582
  visibilityManager;
1386
2583
  observer = null;
2584
+ shareManager;
2585
+ shareButton;
2586
+ focusManager;
1387
2587
  componentRegistry = {
1388
2588
  toggles: new Set(),
1389
2589
  tabGroups: new Set(),
@@ -1400,6 +2600,22 @@ class CustomViewsCore {
1400
2600
  this.visibilityManager = new VisibilityManager();
1401
2601
  this.showUrlEnabled = opt.showUrl ?? false;
1402
2602
  this.lastAppliedState = this.cloneState(this.getComputedDefaultState());
2603
+ // Resolve Exclusions
2604
+ const excludedTags = [...DEFAULT_EXCLUDED_TAGS, ...(this.config.shareExclusions?.tags || [])];
2605
+ const excludedIds = [...DEFAULT_EXCLUDED_IDS, ...(this.config.shareExclusions?.ids || [])];
2606
+ const commonOptions = { excludedTags, excludedIds };
2607
+ this.shareManager = new ShareManager(commonOptions);
2608
+ this.shareButton = new ShareButton(this.shareManager);
2609
+ this.focusManager = new FocusManager(this.rootEl, commonOptions);
2610
+ }
2611
+ getShareManager() {
2612
+ return this.shareManager;
2613
+ }
2614
+ /**
2615
+ * Toggles the share mode on or off.
2616
+ */
2617
+ toggleShareMode() {
2618
+ this.shareManager.toggleShareMode();
1403
2619
  }
1404
2620
  /**
1405
2621
  * Scan the given element for toggles and tab groups, register them
@@ -1432,7 +2648,7 @@ class CustomViewsCore {
1432
2648
  return newComponentsFound;
1433
2649
  }
1434
2650
  /**
1435
- * Unscan the given element for toggles and tab groups, de-register them
2651
+ * Unscan the given element for toggles and tab groups, de-register them from registry
1436
2652
  */
1437
2653
  unscan(element) {
1438
2654
  // Unscan for toggles
@@ -1536,8 +2752,11 @@ class CustomViewsCore {
1536
2752
  // For session history, clicks on back/forward button
1537
2753
  window.addEventListener("popstate", () => {
1538
2754
  this.loadAndCallApplyState();
2755
+ this.focusManager.handleUrlChange();
1539
2756
  });
1540
2757
  this.loadAndCallApplyState();
2758
+ this.focusManager.init();
2759
+ this.shareButton.init();
1541
2760
  this.initObserver();
1542
2761
  }
1543
2762
  initializeNewComponents() {
@@ -1559,7 +2778,7 @@ class CustomViewsCore {
1559
2778
  const currentToggles = this.getCurrentActiveToggles();
1560
2779
  const newState = {
1561
2780
  toggles: currentToggles,
1562
- tabs: currentTabs
2781
+ tabs: currentTabs,
1563
2782
  };
1564
2783
  // 2. Apply state with scroll anchor information
1565
2784
  this.applyState(newState, {
@@ -1827,10 +3046,11 @@ function prependBaseUrl(path, baseUrl) {
1827
3046
  }
1828
3047
 
1829
3048
  /**
1830
- * Custom Elements for Tab Groups and Tabs
3049
+ * Defines the custom elements used by CustomViews.
1831
3050
  */
1832
3051
  /**
1833
- * <cv-tab> element - represents a single tab panel
3052
+ * `<cv-tab>`: A custom element representing a single tab panel within a tab group.
3053
+ * Its content is displayed when the corresponding tab is active.
1834
3054
  */
1835
3055
  class CVTab extends HTMLElement {
1836
3056
  connectedCallback() {
@@ -1838,7 +3058,8 @@ class CVTab extends HTMLElement {
1838
3058
  }
1839
3059
  }
1840
3060
  /**
1841
- * <cv-tabgroup> element - represents a group of tabs
3061
+ * `<cv-tabgroup>`: A custom element that encapsulates a set of tabs (`<cv-tab>`).
3062
+ * It manages the tab navigation and content visibility for the group.
1842
3063
  */
1843
3064
  class CVTabgroup extends HTMLElement {
1844
3065
  connectedCallback() {
@@ -1854,7 +3075,7 @@ class CVTabgroup extends HTMLElement {
1854
3075
  }
1855
3076
  }
1856
3077
  /**
1857
- * <cv-toggle> element - represents a toggleable content block
3078
+ * `<cv-toggle>`: A custom element for creating a toggleable content block.
1858
3079
  */
1859
3080
  class CVToggle extends HTMLElement {
1860
3081
  connectedCallback() {
@@ -1862,8 +3083,8 @@ class CVToggle extends HTMLElement {
1862
3083
  }
1863
3084
  }
1864
3085
  /**
1865
- * <cv-tab-header> element - represents tab header with rich HTML formatting
1866
- * Content is extracted and used in the navigation link
3086
+ * `<cv-tab-header>`: A semantic container for a tab's header content.
3087
+ * The content of this element is used to create the navigation link for the tab.
1867
3088
  */
1868
3089
  class CVTabHeader extends HTMLElement {
1869
3090
  connectedCallback() {
@@ -1871,8 +3092,7 @@ class CVTabHeader extends HTMLElement {
1871
3092
  }
1872
3093
  }
1873
3094
  /**
1874
- * <cv-tab-body> element - represents tab body content
1875
- * Semantic container for tab panel content
3095
+ * `<cv-tab-body>`: A semantic container for the main content of a tab panel.
1876
3096
  */
1877
3097
  class CVTabBody extends HTMLElement {
1878
3098
  connectedCallback() {
@@ -1880,7 +3100,7 @@ class CVTabBody extends HTMLElement {
1880
3100
  }
1881
3101
  }
1882
3102
  /**
1883
- * Register custom elements
3103
+ * Registers all CustomViews custom elements with the CustomElementRegistry.
1884
3104
  */
1885
3105
  function registerCustomElements() {
1886
3106
  // Only register if not already defined
@@ -3304,6 +4524,7 @@ class CustomViewsWidget {
3304
4524
  <span>Copy Shareable URL</span>
3305
4525
  <span class="cv-share-btn-icon">${getCopyIcon()}</span>
3306
4526
  </button>
4527
+
3307
4528
  </footer>
3308
4529
  </div>
3309
4530
  `;