An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Keep relation search keyboard actions off selected entries https://github.com/siyuan-note/siyuan/issues/19904
Daniel55563c3d0932
diff --git a/app/src/protyle/render/av/relation.ts b/app/src/protyle/render/av/relation.tsindex 254449a175..464009116b 100644--- a/app/src/protyle/render/av/relation.ts+++ b/app/src/protyle/render/av/relation.ts@@ -1,7 +1,7 @@import {isTableLikeView} from "./viewType";import {Menu} from "../../../plugin/Menu";import {hasClosestByAttribute, hasClosestByClassName, hasTopClosestByClassName} from "../../util/hasClosest";-import {UDLRHint, upDownHint} from "../../../util/upDownHint";+import {UDLRHint} from "../../../util/upDownHint";import {fetchPost, fetchSyncPost} from "../../../util/fetch";import type {AVRelationItemPreview, AVRelationItemCellInput} from "../../../types/api";import {escapeAttr, escapeHtml, escapeLessThans, escapeHtmlTextAndAttr} from "../../../util/escape";@@ -27,6 +27,7 @@ import {renderAVRichTextElements} from "./richText";import {getAVBlockIconHTML} from "./blockIcon";import {unicode2Emoji} from "../../../emoji";import {bindRelationLayout} from "./relationLayout";+import {getRelationKeyboardTarget} from "./relationKeyboard";import {getTopBarHeight} from "../../../layout/getTopBarHeight";interface IAVItem {@@ -736,9 +737,7 @@ ${genRelationLoaderHTML(false)}`;.find(header => header.dataset.relationColumn === focusedColumn)?.focus();}renderFooter();- if (!listElement.querySelector(".b3-menu__item--current")) {- listElement.querySelector('[data-type="setRelationCell"]')?.classList.add("b3-menu__item--current");- }+ getRelationKeyboardTarget(listElement, state.keyword.trim() !== "");updateCopyRelatedItems(options.menuElement);};const loadPage = (reset: boolean) => {@@ -869,6 +868,7 @@ ${genRelationLoaderHTML(false)}`;});const search = () => {state.keyword = inputElement.value;+ listElement.querySelectorAll(".b3-menu__item--current").forEach(item => item.classList.remove("b3-menu__item--current"));relationItemPreviews.delete(options.menuElement);renderFooter();state.controller?.abort();@@ -879,20 +879,24 @@ ${genRelationLoaderHTML(false)}`;clearTimeout(searchTimer);}searchTimer = window.setTimeout(() => {+ searchTimer = undefined;loadPage(true);}, Constants.TIMEOUT_INPUT);};inputElement.addEventListener("keydown", (event) => {- if (event.isComposing) {+ if (event.isComposing || !["Enter", "ArrowDown", "ArrowUp"].includes(event.key)) {+ return;+ }+ event.preventDefault();+ event.stopPropagation();+ // 搜索防抖或首页请求完成前,不允许键盘操作旧候选项。+ if (searchTimer || state.page === 0 || inputElement.value !== state.keyword) {return;}- upDownHint(listElement, event, "b3-menu__item--current");- const currentElement = options.menuElement.querySelector(".b3-menu__item--current") as HTMLElement;- if (event.key === "Enter" && currentElement && currentElement.getAttribute("data-type") === "setRelationCell") {+ const currentElement = getRelationKeyboardTarget(listElement, state.keyword.trim() !== "", event.key);+ if (event.key === "Enter" && currentElement) {setRelationCell(options.protyle, options.blockElement as HTMLElement, currentElement, options.cellElements);- event.preventDefault();- event.stopPropagation();}});inputElement.addEventListener("input", (event: InputEvent) => {diff --git a/app/src/protyle/render/av/relationKeyboard.ts b/app/src/protyle/render/av/relationKeyboard.tsnew file mode 100644index 0000000000..690f31b1f7--- /dev/null+++ b/app/src/protyle/render/av/relationKeyboard.ts@@ -0,0 +1,21 @@+const CURRENT_CLASS = "b3-menu__item--current";++export const getRelationKeyboardTarget = (list: HTMLElement, searching: boolean, key?: string) => {+ const items = Array.from(list.querySelectorAll<HTMLElement>('[data-type="setRelationCell"]')).filter(item =>+ !item.hasAttribute("disabled") && item.getClientRects().length > 0 &&+ (!searching || item.dataset.relationType !== "selected"));+ const current = list.querySelector<HTMLElement>("." + CURRENT_CLASS);+ const index = items.indexOf(current);+ let target = index >= 0 ? current : items.find(item => item.dataset.relationType !== "selected");+ if (key === "ArrowDown") {+ target = items[index < 0 ? 0 : (index + 1) % items.length];+ } else if (key === "ArrowUp") {+ target = items[index < 0 ? items.length - 1 : (index + items.length - 1) % items.length];+ }+ list.querySelectorAll("." + CURRENT_CLASS).forEach(item => item.classList.remove(CURRENT_CLASS));+ target?.classList.add(CURRENT_CLASS);+ if (target && (key === "ArrowDown" || key === "ArrowUp")) {+ target.scrollIntoView({block: "nearest"});+ }+ return target;+};diff --git a/app/tests/avRelationTemplate.test.js b/app/tests/avRelationTemplate.test.jsindex 4f2d8fd148..091620819e 100644--- a/app/tests/avRelationTemplate.test.js+++ b/app/tests/avRelationTemplate.test.js@@ -42,6 +42,60 @@ const runCases = sources => {return dependencies[name];};const {renderCell, genCellValueByElement} = load("./cell");+ const {bindKeyboard} = load("./relationKeyboardBinding");+ const keyboardList = document.createElement("div");+ keyboardList.innerHTML = '<div><div data-type="setRelationCell" data-relation-type="selected" class="b3-menu__item--current">Selected one</div>' ++ '<div data-type="setRelationCell" data-relation-type="selected">Selected two</div></div>' ++ '<div><div data-type="setRelationCell" data-relation-type="candidate">Match</div></div>' ++ '<button data-type="setRelationCell" data-relation-type="create">Create</button>' ++ '<button data-type="setRelationCell" data-relation-type="create" disabled>Disabled</button>';+ document.body.replaceChildren(keyboardList);+ const keyboardInput = document.createElement("input");+ keyboardInput.value = "query";+ const keyboardState = {keyword: "query", loading: false, page: 1};+ const activated = [];+ bindKeyboard(keyboardList, keyboardInput, keyboardState, (_protyle, _block, item) => activated.push(item));+ const press = (key, input = keyboardInput, isComposing = false) => {+ const event = new KeyboardEvent("keydown", {key, cancelable: true, isComposing});+ input.dispatchEvent(event);+ return event;+ };+ press("Enter");+ assert.equal(activated.at(-1).dataset.relationType, "candidate");+ press("ArrowDown");+ press("Enter");+ assert.equal(activated.at(-1).textContent, "Create");+ press("ArrowDown");+ press("Enter");+ assert.equal(activated.at(-1).dataset.relationType, "candidate");+ keyboardList.querySelector('[data-relation-type="candidate"]').remove();+ press("Enter");+ assert.equal(activated.at(-1).dataset.relationType, "create");+ assert.ok(activated.every(item => item.dataset.relationType !== "selected"));+ const beforePending = activated.length;+ keyboardState.loading = true;+ keyboardState.page = 0;+ assert.equal(press("Enter").defaultPrevented, true);+ keyboardState.loading = false;+ press("Enter");+ keyboardState.page = 1;+ keyboardInput.value = "changed";+ press("Enter");+ keyboardInput.value = "query";+ press("Enter", keyboardInput, true);+ const pendingInput = document.createElement("input");+ pendingInput.value = "query";+ bindKeyboard(keyboardList, pendingInput, keyboardState, () => activated.push(null), 1);+ assert.equal(press("Enter", pendingInput).defaultPrevented, true);+ assert.equal(activated.length, beforePending);+ keyboardList.querySelector('[data-relation-type="create"]').setAttribute("disabled", "");+ press("Enter");+ assert.equal(activated.length, beforePending);+ keyboardInput.value = keyboardState.keyword = "";+ press("ArrowDown");+ press("Enter");+ assert.equal(activated.at(-1).textContent, "Selected one");+ assert.equal(keyboardList.querySelectorAll('[data-relation-type="selected"]').length, 2);const {deselect} = load("./relationSelection");const selectionMenu = document.createElement("div");selectionMenu.innerHTML = `<div data-relation-type="selectedRows"><div data-relation-type="selected" data-row-id="one" draggable="true">@@ -242,10 +296,19 @@ const runElectron = async () => {let exitCode = 0;try {const ts = require("typescript");- const sources = Object.fromEntries(["cell", "cellValue", "attributeValue", "blockIcon", "relationLayout", "capabilities", "capabilities.generated"].map(name => ["./" + name,+ const sources = Object.fromEntries(["cell", "cellValue", "attributeValue", "blockIcon", "relationLayout", "relationKeyboard", "capabilities", "capabilities.generated"].map(name => ["./" + name,ts.transpileModule(readFileSync(path.join(__dirname, `../src/protyle/render/av/${name}.ts`), "utf8"),{compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020}}).outputText]));const relationSource = readFileSync(path.join(__dirname, "../src/protyle/render/av/relation.ts"), "utf8");+ const keyboardStart = relationSource.indexOf(' inputElement.addEventListener("keydown", (event) => {');+ const keyboardEnd = relationSource.indexOf(' inputElement.addEventListener("input",', keyboardStart);+ assert.ok(keyboardStart > 0 && keyboardEnd > keyboardStart);+ sources["./relationKeyboardBinding"] = ts.transpileModule(`+const {getRelationKeyboardTarget} = require("./relationKeyboard");+export const bindKeyboard = (listElement, inputElement, state, setRelationCell, searchTimer) => {+const options = {menuElement: listElement, cellElements: []};+${relationSource.slice(keyboardStart, keyboardEnd)} };`,+ {compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020}}).outputText;const rowStart = relationSource.indexOf("const genRelationRowHTML =");const rowEnd = relationSource.indexOf("const genRelationRowsHTML =", rowStart);sources["./relationPreview"] = ts.transpileModule(`