diff --git a/src/events.ts b/src/events.ts index 28c6f9e..23c160c 100644 --- a/src/events.ts +++ b/src/events.ts @@ -981,34 +981,34 @@ class AddonEvents extends AddonBase { let currentLineIndex = getChildIndex(focusNode); - const tableElements = Array.prototype.filter.call( + // Parse list + const diveTagNames = ["OL", "UL", "LI"]; + + // Find list elements before current line + const listElements = Array.prototype.filter.call( Array.prototype.slice.call( focusNode.parentElement.childNodes, 0, currentLineIndex ), - (e) => { - return e.tagName === "UL" || e.tagName === "OL"; - } + (e) => diveTagNames.includes(e.tagName) ); - console.log(currentLineIndex, tableElements); - for (const tableElement of tableElements) { - currentLineIndex += tableElement.childElementCount - 1; + for (const e of listElements) { + currentLineIndex += this._Addon.views.diveNode(e).length - 1; } - const tagName = focusNode.tagName; - if (tagName === "UL" || tagName === "OL") { - let liElement = selection.focusNode as XUL.Element; - while ( - liElement.tagName !== "LI" || - !liElement.parentElement.parentElement.className.includes( - "primary-editor" - ) - ) { - liElement = liElement.parentElement; + // Find list index if current line is inside a list + if (diveTagNames.includes(focusNode.tagName)) { + const eleList = this._Addon.views.diveNode(focusNode); + for (const i in eleList) { + if ( + selection.focusNode.parentElement.parentElement === eleList[i] + ) { + currentLineIndex += Number(i); + break; + } } - currentLineIndex += getChildIndex(liElement); } Zotero.debug(`Knowledge4Zotero: line ${currentLineIndex} selected.`); console.log(currentLineIndex); diff --git a/src/views.ts b/src/views.ts index ae72cf0..1a48bc9 100644 --- a/src/views.ts +++ b/src/views.ts @@ -255,26 +255,36 @@ class AddonViews extends AddonBase { } } + // TODO: move these parse functions to a seperate file + diveNode( + e: Element, + eleList: Element[] = undefined, + diveTagNames: string[] = ["OL", "UL", "LI"] + ) { + if (!eleList) { + eleList = []; + } + for (let _e of e.children) { + if (diveTagNames.includes(_e.tagName)) { + this.diveNode(_e, eleList); + } else { + eleList.push(e); + } + } + return eleList; + } + async scrollToLine(instance: EditorInstance, lineIndex: number) { await instance._initPromise; let editorElement = this.getEditorElement(instance._iframeWindow.document); const eleList = []; const diveTagNames = ["OL", "UL", "LI"]; - function dive(e: Element, targetIndex: string) { - for (let _e of e.children) { - if (diveTagNames.includes(_e.tagName)) { - dive(_e, targetIndex); - } else { - eleList.push(e); - } - } - } const nodes = Array.from(editorElement.children); for (let i in nodes) { const ele = nodes[i]; if (diveTagNames.includes(ele.tagName)) { - dive(ele, i); + this.diveNode(ele, eleList, diveTagNames); } else { eleList.push(ele); }