* 更新节点
(node: ProseMirrorNode)
| 1676 | * 更新节点 |
| 1677 | */ |
| 1678 | update(node: ProseMirrorNode): boolean { |
| 1679 | if (node.type !== this.node.type) return false; |
| 1680 | |
| 1681 | const prevLanguage = this.node.attrs.language; |
| 1682 | this.node = node; |
| 1683 | const newText = node.textContent; |
| 1684 | |
| 1685 | if (newText !== this.cm.state.doc.toString()) { |
| 1686 | this.updating = true; |
| 1687 | this.cm.dispatch({ |
| 1688 | changes: { |
| 1689 | from: 0, |
| 1690 | to: this.cm.state.doc.length, |
| 1691 | insert: newText, |
| 1692 | }, |
| 1693 | }); |
| 1694 | this.updating = false; |
| 1695 | } |
| 1696 | |
| 1697 | // 更新源码模式下的文本内容 |
| 1698 | if (this.sourceViewMode && this.sourceTextElement) { |
| 1699 | const language = node.attrs.language || ""; |
| 1700 | const content = node.textContent; |
| 1701 | const fullMarkdown = `\`\`\`${language}\n${content}\n\`\`\``; |
| 1702 | const lines = fullMarkdown.split("\n"); |
| 1703 | |
| 1704 | // 收集当前的文本内容 |
| 1705 | const currentLines: string[] = []; |
| 1706 | const childDivs = this.sourceTextElement.querySelectorAll("div.milkup-with-line-number"); |
| 1707 | childDivs.forEach((div) => { |
| 1708 | currentLines.push(div.textContent || ""); |
| 1709 | }); |
| 1710 | const currentText = currentLines.join("\n"); |
| 1711 | |
| 1712 | // 只在内容真正变化时更新 |
| 1713 | if (currentText !== fullMarkdown) { |
| 1714 | // 保存光标位置 |
| 1715 | const selection = window.getSelection(); |
| 1716 | let cursorOffset = 0; |
| 1717 | if (selection && selection.rangeCount > 0) { |
| 1718 | const range = selection.getRangeAt(0); |
| 1719 | if (range.startContainer.nodeType === Node.TEXT_NODE) { |
| 1720 | cursorOffset = range.startOffset; |
| 1721 | // 计算相对于整个文本的偏移量 |
| 1722 | let node: Node | null = range.startContainer; |
| 1723 | while (node && node !== this.sourceTextElement && node.previousSibling) { |
| 1724 | node = node.previousSibling; |
| 1725 | cursorOffset += node.textContent?.length || 0; |
| 1726 | } |
| 1727 | } |
| 1728 | } |
| 1729 | |
| 1730 | this.updating = true; |
| 1731 | |
| 1732 | // 清空容器并重新创建行 |
| 1733 | this.sourceTextElement.innerHTML = ""; |
| 1734 | lines.forEach((line) => { |
| 1735 | const lineDiv = document.createElement("div"); |
nothing calls this directly
no test coverage detected