]> BookStack Code Mirror - bookstack/blobdiff - resources/js/services/dom.ts
ZIP Imports: Added API examples, finished testing
[bookstack] / resources / js / services / dom.ts
index 77c19a761058aa2aa9d2f08f8ba4f55e996a5298..8696fe81639c84aea40294dc9b3c1db376ca129f 100644 (file)
@@ -225,7 +225,7 @@ export function findTargetNodeAndOffset(parentNode: HTMLElement, offset: number)
         if (currentNode.nodeType === Node.TEXT_NODE) {
             // For text nodes, count the length of their content
             // Returns if within range
-            const textLength = currentNode.textContent.length;
+            const textLength = (currentNode.textContent || '').length;
             if (currentOffset + textLength >= offset) {
                 return {
                     node: currentNode,
@@ -237,9 +237,9 @@ export function findTargetNodeAndOffset(parentNode: HTMLElement, offset: number)
         } else if (currentNode.nodeType === Node.ELEMENT_NODE) {
             // Otherwise, if an element, track the text length and search within
             // if in range for the target offset
-            const elementTextLength = currentNode.textContent.length;
+            const elementTextLength = (currentNode.textContent || '').length;
             if (currentOffset + elementTextLength >= offset) {
-                return findTargetNodeAndOffset(currentNode, offset - currentOffset);
+                return findTargetNodeAndOffset(currentNode as HTMLElement, offset - currentOffset);
             }
 
             currentOffset += elementTextLength;
@@ -256,4 +256,22 @@ export function findTargetNodeAndOffset(parentNode: HTMLElement, offset: number)
 export function hashElement(element: HTMLElement): string {
     const normalisedElemText = (element.textContent || '').replace(/\s{2,}/g, '');
     return cyrb53(normalisedElemText);
+}
+
+/**
+ * Find the closest scroll container parent for the given element
+ * otherwise will default to the body element.
+ */
+export function findClosestScrollContainer(start: HTMLElement): HTMLElement {
+    let el: HTMLElement|null = start;
+    do {
+        const computed = window.getComputedStyle(el);
+        if (computed.overflowY === 'scroll') {
+            return el;
+        }
+
+        el = el.parentElement;
+    } while (el);
+
+    return document.body;
 }
\ No newline at end of file