An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
Improve word count (#17572)
Jeffrey Chen57e566babe24
diff --git a/app/src/layout/Wnd.ts b/app/src/layout/Wnd.tsindex 53ae19942a..88e96e1f36 100644--- a/app/src/layout/Wnd.ts+++ b/app/src/layout/Wnd.ts@@ -768,92 +768,95 @@ export class Wnd {}private removeTabAction = (id: string, isBatchClose = false, animate = true, isSaveLayout = true) => {- clearCounter();this.children.find((item, index) => {- if (item.id === id) {- if (window.siyuan.storage[Constants.LOCAL_CLOSED_TABS].length > Constants.SIZE_UNDO) {- window.siyuan.storage[Constants.LOCAL_CLOSED_TABS].pop();- }- if (item.headElement) {- const tabJSON = {};- layoutToJSON(item, tabJSON);- window.siyuan.storage[Constants.LOCAL_CLOSED_TABS].push(tabJSON);- setStorageVal(Constants.LOCAL_CLOSED_TABS, window.siyuan.storage[Constants.LOCAL_CLOSED_TABS]);- }- if (item.model instanceof Custom && item.model.beforeDestroy) {- item.model.beforeDestroy();+ if (item.id !== id) {+ return;+ }+ if (item.model instanceof Editor) {+ clearCounter(item.model.editor.protyle.block.rootID);+ }+ if (window.siyuan.storage[Constants.LOCAL_CLOSED_TABS].length > Constants.SIZE_UNDO) {+ window.siyuan.storage[Constants.LOCAL_CLOSED_TABS].pop();+ }+ if (item.headElement) {+ const tabJSON = {};+ layoutToJSON(item, tabJSON);+ window.siyuan.storage[Constants.LOCAL_CLOSED_TABS].push(tabJSON);+ setStorageVal(Constants.LOCAL_CLOSED_TABS, window.siyuan.storage[Constants.LOCAL_CLOSED_TABS]);+ }+ if (item.model instanceof Custom && item.model.beforeDestroy) {+ item.model.beforeDestroy();+ }+ if (item.model instanceof Editor) {+ saveScroll(item.model.editor.protyle);+ // 更新文档关闭时间(批量关闭页签时由 closeTabByType 批量处理,这里不单独调用)+ if (!isBatchClose) {+ fetchPost("/api/storage/updateRecentDocCloseTime", {rootID: item.model.editor.protyle.block.rootID});}- if (item.model instanceof Editor) {- saveScroll(item.model.editor.protyle);- // 更新文档关闭时间(批量关闭页签时由 closeTabByType 批量处理,这里不单独调用)- if (!isBatchClose) {- fetchPost("/api/storage/updateRecentDocCloseTime", {rootID: item.model.editor.protyle.block.rootID});- }+ }+ if (this.children.length === 1) {+ this.destroyModel(this.children[0].model);+ this.children = [];+ if (["bottom", "left", "right"].includes(this.parent.type)) {+ item.panelElement.remove();+ } else {+ recordBeforeResizeTop();+ this.remove();}- if (this.children.length === 1) {- this.destroyModel(this.children[0].model);- this.children = [];- if (["bottom", "left", "right"].includes(this.parent.type)) {- item.panelElement.remove();- } else {- recordBeforeResizeTop();- this.remove();- }- // 关闭分屏页签后光标消失- const editors = getAllModels().editor;- if (editors.length === 0) {- clearOBG();- } else {- editors.forEach(item => {- if (!item.element.classList.contains("fn__none")) {- setPanelFocus(item.parent.parent.headersElement.parentElement.parentElement);- updatePanelByEditor({- protyle: item.editor.protyle,- focus: true,- pushBackStack: true,- reload: false,- resize: true,- });- return;- }- });- }- return;+ // 关闭分屏页签后光标消失+ const editors = getAllModels().editor;+ if (editors.length === 0) {+ clearOBG();+ } else {+ editors.forEach(item => {+ if (!item.element.classList.contains("fn__none")) {+ setPanelFocus(item.parent.parent.headersElement.parentElement.parentElement);+ updatePanelByEditor({+ protyle: item.editor.protyle,+ focus: true,+ pushBackStack: true,+ reload: false,+ resize: true,+ });+ return;+ }+ });}- if (item.headElement) {- if (item.headElement.classList.contains("item--focus")) {- let latestHeadElement: HTMLElement;- Array.from(item.headElement.parentElement.children).forEach((headItem: HTMLElement) => {- if (headItem !== item.headElement &&- headItem.style.maxWidth !== "0px" // 不对比已移除但还在动画效果中的元素 https://github.com/siyuan-note/siyuan/issues/7878- ) {- if (!latestHeadElement) {- latestHeadElement = headItem;- } else if (headItem.getAttribute("data-activetime") > latestHeadElement.getAttribute("data-activetime")) {- latestHeadElement = headItem;- }+ return;+ }+ if (item.headElement) {+ if (item.headElement.classList.contains("item--focus")) {+ let latestHeadElement: HTMLElement;+ Array.from(item.headElement.parentElement.children).forEach((headItem: HTMLElement) => {+ if (headItem !== item.headElement &&+ headItem.style.maxWidth !== "0px" // 不对比已移除但还在动画效果中的元素 https://github.com/siyuan-note/siyuan/issues/7878+ ) {+ if (!latestHeadElement) {+ latestHeadElement = headItem;+ } else if (headItem.getAttribute("data-activetime") > latestHeadElement.getAttribute("data-activetime")) {+ latestHeadElement = headItem;}- });- if (latestHeadElement && !isBatchClose) {- this.switchTab(latestHeadElement, true, true, false, false);- this.showHeading();}+ });+ if (latestHeadElement && !isBatchClose) {+ this.switchTab(latestHeadElement, true, true, false, false);+ this.showHeading();}- if (animate) {- item.headElement.setAttribute("style", "max-width: 0px;");- setTimeout(() => {- item.headElement.remove();- }, 200);- } else {+ }+ if (animate) {+ item.headElement.setAttribute("style", "max-width: 0px;");+ setTimeout(() => {item.headElement.remove();- }+ }, 200);+ } else {+ item.headElement.remove();}- item.panelElement.remove();- this.destroyModel(item.model);- this.children.splice(index, 1);- resizeTabs(false);- return true;}+ item.panelElement.remove();+ this.destroyModel(item.model);+ this.children.splice(index, 1);+ resizeTabs(false);+ return true;});// 初始化移除窗口,但 centerLayout 还没有赋值 https://ld246.com/article/1658718634416if (window.siyuan.layout.centerLayout) {diff --git a/app/src/layout/status.ts b/app/src/layout/status.tsindex 991c73c3ee..b04360974f 100644--- a/app/src/layout/status.ts+++ b/app/src/layout/status.ts@@ -133,64 +133,81 @@ export const initStatus = (isWindow = false) => {/// #endif};-let countRootId: string;let countTimeout: number;-export const countSelectWord = (range: Range, rootID?: string) => {- /// #if !MOBILE- if (document.getElementById("status").classList.contains("fn__none")) {- return;- }+let countAbortController: AbortController | null = null;+let statusStatRootId: string; // 状态栏最后显示的统计信息所属文档 ID++const scheduleStatusStat = (rootID: string, content?: string, ids?: string[]) => {+ statusStatRootId = rootID;clearTimeout(countTimeout);countTimeout = window.setTimeout(() => {- const selectText = range.toString();- if (selectText) {- fetchPost("/api/block/getContentWordCount", {"content": range.toString()}, (response) => {- renderStatusbarCounter(response.data.stat);- });- countRootId = "";- } else if (rootID && rootID !== countRootId) {- countRootId = rootID;- fetchPost("/api/block/getTreeStat", {id: rootID}, (response) => {- renderStatusbarCounter(response.data.stat);- });+ if (countAbortController) {+ countAbortController.abort();+ countAbortController = null;+ }+ countAbortController = new AbortController();+ const signal = countAbortController.signal;+ const capturedController = countAbortController;++ const onFetched = (response: IWebSocketData) => {+ if (signal.aborted) {+ return;+ }+ renderStatusbarCounter(response.data.stat);+ if (countAbortController === capturedController) {+ countAbortController = null;+ }+ };++ if (content) {+ fetchPost("/api/block/getContentWordCount", {content}, onFetched, undefined, undefined, signal);+ } else if (ids && ids.length > 0) {+ fetchPost("/api/block/getBlocksWordCount", {ids}, onFetched, undefined, undefined, signal);+ } else {+ fetchPost("/api/block/getTreeStat", {id: rootID}, onFetched, undefined, undefined, signal);}}, Constants.TIMEOUT_COUNT);+};++export const countSelectWord = (range: Range, rootID: string) => {+ /// #if !MOBILE+ if (document.getElementById("status").classList.contains("fn__none")) {+ return;+ }+ scheduleStatusStat(rootID, range.toString());/// #endif};-export const countBlockWord = (ids: string[], rootID?: string, clearCache = false) => {+export const countBlockWord = (ids: (string | null)[], rootID: string) => {/// #if !MOBILEif (document.getElementById("status").classList.contains("fn__none")) {return;}- if (getSelection().rangeCount > 0 && getSelection().getRangeAt(0).toString() && ids.length === 0) {- countSelectWord(getSelection().getRangeAt(0));+ ids = ids.filter((id) => Boolean(id));+ if (ids.length > 0) {+ scheduleStatusStat(rootID, undefined, ids);return;}- clearTimeout(countTimeout);- countTimeout = window.setTimeout(() => {- if (clearCache) {- countRootId = "";- }- if (ids.length > 0) {- fetchPost("/api/block/getBlocksWordCount", {ids}, (response) => {- renderStatusbarCounter(response.data.stat);- });- countRootId = "";- } else if (rootID && rootID !== countRootId) {- countRootId = rootID;- fetchPost("/api/block/getTreeStat", {id: rootID}, (response) => {- renderStatusbarCounter(response.data.stat);- });- }- }, Constants.TIMEOUT_COUNT);+ const selectText = getSelection().rangeCount > 0 ? getSelection().getRangeAt(0).toString() : "";+ if (selectText) {+ scheduleStatusStat(rootID, selectText);+ return;+ }+ scheduleStatusStat(rootID);/// #endif};-export const clearCounter = () => {- countRootId = "";- document.querySelector("#status .status__counter").innerHTML = "";+export const clearCounter = (rootID: string) => {+ if (statusStatRootId !== rootID) {+ return;+ }+ statusStatRootId = undefined;clearTimeout(countTimeout);+ if (countAbortController) {+ countAbortController.abort();+ countAbortController = null;+ }+ document.querySelector("#status .status__counter").innerHTML = "";};export const renderStatusbarCounter = (stat: {diff --git a/app/src/protyle/util/selection.ts b/app/src/protyle/util/selection.tsindex bfd834702f..f3af6ab801 100644--- a/app/src/protyle/util/selection.ts+++ b/app/src/protyle/util/selection.ts@@ -115,7 +115,7 @@ export const selectAll = (protyle: IProtyle, nodeElement: Element, range: Range)return true;}hideElements(["select"], protyle);- const ids: string [] = [];+ const ids: string[] = [];Array.from(protyle.wysiwyg.element.children).forEach(item => {const nodeId = item.getAttribute("data-node-id");if (nodeId) {diff --git a/app/src/protyle/wysiwyg/commonHotkey.ts b/app/src/protyle/wysiwyg/commonHotkey.tsindex 549317b80b..c481bdcbc5 100644--- a/app/src/protyle/wysiwyg/commonHotkey.ts+++ b/app/src/protyle/wysiwyg/commonHotkey.ts@@ -167,7 +167,7 @@ export const upSelect = (options: {} else {options.cb(selectElements);}- const ids: string[] = [];+ const ids: (string | null)[] = [];options.protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select").forEach(item => {ids.push(item.getAttribute("data-node-id"));});@@ -221,7 +221,7 @@ export const downSelect = (options: {} else {options.cb(selectElements);}- const ids: string[] = [];+ const ids: (string | null)[] = [];options.protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select").forEach(item => {ids.push(item.getAttribute("data-node-id"));});diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.tsindex 75e6fbff6b..0562535bed 100644--- a/app/src/protyle/wysiwyg/index.ts+++ b/app/src/protyle/wysiwyg/index.ts@@ -281,7 +281,7 @@ export class WYSIWYG {if (selectElements.length === 0 && range.toString() === "" && !range.cloneContents().querySelector("img") &&!selectImgElement && !selectAVElement && !selectTableElement) {nodeElement.classList.add("protyle-wysiwyg--select");- countBlockWord([nodeElement.getAttribute("data-node-id")]);+ countBlockWord([nodeElement.getAttribute("data-node-id")], protyle.block.rootID);selectElements = [nodeElement];}let html = "";@@ -642,7 +642,7 @@ export class WYSIWYG {!selectElements[0].classList.contains("sb")) {// 单个 p 不选中} else {- const ids: string[] = [];+ const ids: (string | null)[] = [];if (!hasSelectClassElement && protyle.scroll && !protyle.scroll.element.classList.contains("fn__none") && !protyle.scroll.keepLazyLoad &&(startElement.getBoundingClientRect().top < -protyle.contentElement.clientHeight * 2 || endElement.getBoundingClientRect().bottom > protyle.contentElement.clientHeight * 2)) {showMessage(window.siyuan.languages.crossKeepLazyLoad);@@ -657,7 +657,7 @@ export class WYSIWYG {});}});- countBlockWord(ids);+ countBlockWord(ids, protyle.block.rootID);if (toDown) {focusBlock(selectElements[selectElements.length - 1], protyle.wysiwyg.element, false);} else {@@ -702,11 +702,11 @@ export class WYSIWYG {ctrlParentElement.removeAttribute("select-start");ctrlParentElement.removeAttribute("select-end");}- const ids: string[] = [];+ const ids: (string | null)[] = [];protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select").forEach(item => {ids.push(item.getAttribute("data-node-id"));});- countBlockWord(ids);+ countBlockWord(ids, protyle.block.rootID);}return;}@@ -1734,12 +1734,12 @@ export class WYSIWYG {}}- const ids: string[] = [];+ const ids: (string | null)[] = [];const selectElement = protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select");selectElement.forEach(item => {ids.push(item.getAttribute("data-node-id"));});- countBlockWord(ids);+ countBlockWord(ids, protyle.block.rootID);// 划选后不能存在跨块的 range https://github.com/siyuan-note/siyuan/issues/4473if (getSelection().rangeCount > 0) {const range = getSelection().getRangeAt(0);@@ -2584,7 +2584,7 @@ export class WYSIWYG {if ((event.shiftKey || isOnlyMeta(event)) && !event.isComposing && range.toString() !== "") {// 工具栏protyle.toolbar.render(protyle, range, event);- countSelectWord(range);+ countSelectWord(range, protyle.block.rootID);}if (event.eventPhase !== 3 && !event.shiftKey && (event.key.indexOf("Arrow") > -1 || event.key === "Home" || event.key === "End" || event.key === "PageUp" || event.key === "PageDown") && !event.isComposing) {diff --git a/app/src/protyle/wysiwyg/keydown.ts b/app/src/protyle/wysiwyg/keydown.tsindex de9ad9f855..bd81c14c34 100644--- a/app/src/protyle/wysiwyg/keydown.ts+++ b/app/src/protyle/wysiwyg/keydown.ts@@ -240,7 +240,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {}nextElement.classList.add("protyle-wysiwyg--select");- countBlockWord([nextElement.getAttribute("data-node-id")]);+ countBlockWord([nextElement.getAttribute("data-node-id")], protyle.block.rootID);const bottom = nextElement.getBoundingClientRect().bottom - protyle.contentElement.getBoundingClientRect().bottom;if (bottom > 0) {protyle.contentElement.scrollTop = protyle.contentElement.scrollTop + bottom;@@ -281,7 +281,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {}if (previousElement) {previousElement.classList.add("protyle-wysiwyg--select");- countBlockWord([previousElement.getAttribute("data-node-id")]);+ countBlockWord([previousElement.getAttribute("data-node-id")], protyle.block.rootID);const top = previousElement.getBoundingClientRect().top - protyle.contentElement.getBoundingClientRect().top;if (top < 0) {protyle.contentElement.scrollTop = protyle.contentElement.scrollTop + top;@@ -502,11 +502,15 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {item.classList.remove("protyle-wysiwyg--select");});topElement.classList.add("protyle-wysiwyg--select");+ const ids: (string | null)[] = [];+ ids.push(topElement.getAttribute("data-node-id"));let nextElement = event.key === "Home" ? topElement.previousElementSibling : topElement.nextElementSibling;while (nextElement) {nextElement.classList.add("protyle-wysiwyg--select");+ ids.push(nextElement.getAttribute("data-node-id"));nextElement = event.key === "Home" ? nextElement.previousElementSibling : nextElement.nextElementSibling;}+ countBlockWord(ids, protyle.block.rootID);if (event.key === "Home") {protyle.wysiwyg.element.firstElementChild.scrollIntoView();} else {diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.tsindex 5147fef458..7bd61127b4 100644--- a/app/src/protyle/wysiwyg/transaction.ts+++ b/app/src/protyle/wysiwyg/transaction.ts@@ -81,7 +81,11 @@ const promiseTransaction = () => {}]}, (response) => {if (window.siyuan.transactions.length === 0) {- countBlockWord([], protyle.block.rootID, true);+ const ids: (string | null)[] = [];+ protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select").forEach(item => {+ ids.push(item.getAttribute("data-node-id"));+ });+ countBlockWord(ids, protyle.block.rootID);} else {promiseTransaction();}diff --git a/app/src/util/fetch.ts b/app/src/util/fetch.tsindex 2b1077762b..4570ad1d17 100644--- a/app/src/util/fetch.ts+++ b/app/src/util/fetch.ts@@ -10,9 +10,11 @@ export const fetchPost = (data?: any,cb?: (response: IWebSocketData) => void,headers?: IObject,- failCallback?: (response: IWebSocketData) => void) => {+ failCallback?: (response: IWebSocketData) => void,+ abortSignal?: AbortSignal) => {const init: RequestInit = {method: "POST",+ signal: abortSignal,};if (data) {if (["/api/search/searchRefBlock", "/api/graph/getGraph", "/api/graph/getLocalGraph",@@ -93,6 +95,9 @@ export const fetchPost = (cb(response);}}).catch((e) => {+ if (e?.name === "AbortError") {+ return;+ }if (failCallback && url === "/api/file/getFile") {failCallback({data: null,