An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:white_check_mark: Fit inline math selection fixtures to the actual viewport
Daniel3a6df5ff9660
diff --git a/app/tests/inlineMathSelection.test.js b/app/tests/inlineMathSelection.test.jsindex 12c6c6fd99..4728904feb 100644--- a/app/tests/inlineMathSelection.test.js+++ b/app/tests/inlineMathSelection.test.js@@ -52,15 +52,31 @@ const setupEdge = async (mode, direction) => {await window.mathSelectionAPI.mathRender(editable);await document.fonts.ready;const range = document.createRange();- range.selectNodeContents(prefix);// 先测量整段文字,不能把已换行文本的外接矩形当作单行宽度。editable.style.width = "max-content";editable.style.whiteSpace = "nowrap";- const measuredLines = Array.from(range.getClientRects());- if (measuredLines.length !== 1) throw new Error("Prefix measurement must occupy one line");- const width = measuredLines[0].width;+ const measurePrefix = () => {+ range.selectNodeContents(prefix);+ const measuredLines = Array.from(range.getClientRects());+ if (measuredLines.length !== 1 || !Number.isFinite(measuredLines[0].width) || measuredLines[0].width <= 0) {+ throw new Error("Prefix measurement must occupy one nonempty line");+ }+ return measuredLines[0].width;+ };+ const mathWidth = math.getBoundingClientRect().width;+ const availableWidth = innerWidth - editable.getBoundingClientRect().left - 32;+ let width = measurePrefix();+ // 窗口实际视口可能小于请求尺寸,按字体实测宽度保留能完整显示的最长数字前缀。+ while (width + mathWidth + 2 > availableWidth && prefix.textContent.length > 3) {+ prefix.textContent = prefix.textContent.slice(0, -1);+ width = measurePrefix();+ }+ if (!Number.isFinite(mathWidth) || mathWidth <= 0 || width + mathWidth + 2 > availableWidth) {+ throw new Error("Viewport cannot contain the inline math edge fixture: " ++ JSON.stringify({viewport: innerWidth, availableWidth, width, mathWidth}));+ }editable.style.removeProperty("white-space");- editable.style.width = (width + math.getBoundingClientRect().width * (mode === "left" ? 0.5 : 1) + 2) + "px";+ editable.style.width = (width + mathWidth * (mode === "left" ? 0.5 : 1) + 2) + "px";const point = (node, offset) => {range.setStart(node, offset);range.setEnd(node, offset + 1);@@ -73,9 +89,19 @@ const setupEdge = async (mode, direction) => {const diagnosticAbort = new AbortController();window.mathSelectionDiagnosticAbort = diagnosticAbort;const geometry = {mode, requestedWidth: editable.style.width, measuredPrefixWidth: width,+ prefixLength: prefix.textContent.length, viewport: [innerWidth, innerHeight],editable: editable.getBoundingClientRect().toJSON(), math: rect.toJSON(),prefixLines: Array.from(prefix.getClientRects(), item => item.toJSON()),fontsStatus: document.fonts.status, devicePixelRatio: window.devicePixelRatio};+ const prefixLine = geometry.prefixLines[0];+ if (geometry.prefixLines.length !== 1 || geometry.editable.right > innerWidth - 32 ||+ !(after.y > before.y) || (mode === "left" ?+ Math.abs(rect.left - prefixLine.left) >= 1 || rect.top < prefixLine.bottom ||+ after.y < rect.top || after.y >= rect.bottom :+ rect.top >= prefixLine.bottom || rect.bottom <= prefixLine.top ||+ after.y <= Math.max(rect.bottom, prefixLine.bottom))) {+ throw new Error("Invalid inline math edge layout: " + JSON.stringify(geometry));+ }window.mathSelectionDiagnostics = {mode, direction, geometry, events: []};const recordSelection = (phase, event) => {const selection = getSelection();@@ -109,6 +135,22 @@ const setupEdge = async (mode, direction) => {geometry};};+const validateDragPoints = (from, to) => {+ const editable = document.querySelector('[contenteditable="true"]');+ for (const [name, point] of Object.entries({from, to})) {+ const inViewport = Number.isFinite(point.x) && Number.isFinite(point.y) &&+ point.x >= 0 && point.x < innerWidth && point.y >= 0 && point.y < innerHeight;+ const hit = inViewport ? document.elementFromPoint(point.x, point.y) : null;+ const caret = inViewport ? document.caretRangeFromPoint(point.x, point.y) : null;+ if (!inViewport || !hit || !editable?.contains(hit) || !caret || !editable.contains(caret.startContainer)) {+ throw new Error("Invalid native selection drag " + name + ": " + JSON.stringify({point,+ viewport: [innerWidth, innerHeight], hit: hit?.outerHTML?.slice(0, 512),+ caretText: caret?.startContainer.textContent?.slice(0, 180), caretOffset: caret?.startOffset}));+ }+ }+ return true;+};+const runElectron = async () => {const {app, BrowserWindow} = require("electron");const ts = require("typescript");@@ -166,6 +208,11 @@ const runElectron = async () => {win.webContents.debugger.attach("1.3");const send = params => win.webContents.debugger.sendCommand("Input.dispatchMouseEvent", params);const drag = async (from, to, edge = false) => {+ // 校验与派发使用相同的整数坐标,避免边缘点取整后落到编辑器之外。+ from = {x: Math.floor(from.x), y: Math.floor(from.y)};+ to = {x: Math.floor(to.x), y: Math.floor(to.y)};+ await win.webContents.executeJavaScript(+ `(${validateDragPoints.toString()})(${JSON.stringify(from)}, ${JSON.stringify(to)})`);await win.webContents.executeJavaScript(`getSelection().removeAllRanges();if (window.mathSelectionDiagnostics) window.mathSelectionDiagnostics.events = []; true;`);await send({type: "mouseMoved", ...from});diff --git a/app/tests/inlineMathSelectionDiagnostics.test.js b/app/tests/inlineMathSelectionDiagnostics.test.jsindex 0ae3308fe6..f62a18ee12 100644--- a/app/tests/inlineMathSelectionDiagnostics.test.js+++ b/app/tests/inlineMathSelectionDiagnostics.test.js@@ -9,16 +9,23 @@ const selectionFailure = (diagnosticFailure = false) => {const file = path.join(__dirname, "inlineMathSelection.test.js");const source = ts.createSourceFile(file, readFileSync(file, "utf8"), ts.ScriptTarget.Latest, true);let drag;+ let validateDragPoints;const visit = node => {if (ts.isVariableDeclaration(node) && node.name.getText(source) === "drag") {drag = node.initializer.getText(source);}+ if (ts.isVariableDeclaration(node) && node.name.getText(source) === "validateDragPoints") {+ validateDragPoints = node.initializer.getText(source);+ }ts.forEachChild(node, visit);};visit(source);assert.ok(drag);+ assert.ok(validateDragPoints);const script = `const assert = require("node:assert/strict");+const validateDragPoints = ${validateDragPoints};const win = {webContents: {executeJavaScript: async source => {+ if (source.includes("Invalid native selection drag")) return true;if (source === "getSelection().toString()") return "";if (${diagnosticFailure} && source.includes("const describePoint")) throw new Error("Renderer disposed");return {mode: "left", direction: "forward", events: [{phase: "mouseup", text: "", collapsed: true}]};diff --git a/app/tests/inlineMathSelectionGeometry.test.js b/app/tests/inlineMathSelectionGeometry.test.jsnew file mode 100644index 0000000000..6efe82ddc2--- /dev/null+++ b/app/tests/inlineMathSelectionGeometry.test.js@@ -0,0 +1,206 @@+const assert = require("node:assert/strict");+const {readFileSync} = require("node:fs");+const path = require("node:path");+const test = require("node:test");+const ts = require("typescript");++const file = path.join(__dirname, "inlineMathSelection.test.js");+const source = ts.createSourceFile(file, readFileSync(file, "utf8"), ts.ScriptTarget.Latest, true);+const extract = name => {+ let implementation;+ const visit = node => {+ if (ts.isVariableDeclaration(node) && node.name.getText(source) === name) {+ implementation = node.initializer.getText(source);+ }+ ts.forEachChild(node, visit);+ };+ visit(source);+ assert.ok(implementation, name);+ return implementation;+};++const rect = (x, y, width, height = 17) => ({x, y, width, height,+ left: x, right: x + width, top: y, bottom: y + height,+ toJSON() { return {x, y, width, height, left: x, right: x + width, top: y, bottom: y + height}; }});++// 只模拟字体度量和换行条件,驱动真实夹具;原生选区仍由 Electron 测试验证。+const fixture = ({viewportWidth, characterWidth = 1044.875 / 141, mathWidth = 17.671875}) => {+ const left = 36;+ const lineTop = 42;+ const lineHeight = 26;+ const suffix = {textContent: "哒哒哒哒哒哒"};+ const prefix = {textContent: ""};+ const prefixText = {get textContent() { return prefix.textContent; }};+ prefix.firstChild = prefixText;+ const prefixWidth = () => prefix.textContent.length * characterWidth;+ const style = {removeProperty(name) { if (name === "white-space") delete this.whiteSpace; }};+ const containerWidth = () => style.width === "max-content" ? prefixWidth() + mathWidth + 96 : parseFloat(style.width);+ const mathRect = () => {+ const wrapped = style.whiteSpace !== "nowrap" && prefixWidth() + mathWidth > containerWidth();+ return rect(wrapped ? left : left + prefixWidth(), lineTop + (wrapped ? lineHeight : 0), mathWidth);+ };+ const suffixRect = offset => {+ const formula = mathRect();+ const firstLineCapacity = Math.floor((containerWidth() - (formula.right - left)) / 16);+ if (offset < firstLineCapacity) return rect(formula.right + offset * 16, formula.top, 16);+ const lineCapacity = Math.max(1, Math.floor(containerWidth() / 16));+ const remainingOffset = offset - firstLineCapacity;+ return rect(left + remainingOffset % lineCapacity * 16,+ formula.top + (1 + Math.floor(remainingOffset / lineCapacity)) * lineHeight, 16);+ };+ const math = {dataset: {}, nextSibling: suffix, getBoundingClientRect: mathRect};+ const prefixRect = () => rect(left, lineTop, prefixWidth());+ prefix.getClientRects = () => [prefixRect()];+ prefix.getBoundingClientRect = prefixRect;+ const editable = {firstChild: prefix, style,+ get clientWidth() { return Math.round(containerWidth()); },+ getBoundingClientRect: () => rect(left, 38, containerWidth(), 52),+ querySelector: () => math,+ contains: node => [editable, prefix, prefixText, math, suffix].includes(node)};+ let selected;+ let offset = 0;+ const range = {+ selectNodeContents(node) { selected = node; },+ setStart(node, value) { selected = node; offset = value; },+ setEnd() {},+ getClientRects: () => [prefixRect()],+ getBoundingClientRect: () => selected === suffix ? suffixRect(offset) :+ rect(left + offset * characterWidth, lineTop, characterWidth),+ };+ const document = {body: {}, fonts: {ready: Promise.resolve(), status: "loaded"},+ querySelector: () => editable, createRange: () => range, addEventListener() {}};+ const window = {mathSelectionAPI: {mathRender: async () => {}}, devicePixelRatio: 1};+ const setupEdge = new Function("document", "window", "innerWidth", "innerHeight",+ `return (${extract("setupEdge")});`)(document, window, viewportWidth, 600);+ return {setupEdge, editable, prefix, math, prefixText, suffix, document, window};+};++for (const viewportWidth of [640, 1024, 1600]) {+ for (const characterWidth of [5, 1044.875 / 141, 11]) {+ for (const mode of ["left", "right"]) {+ test(`inline math edge geometry fits ${viewportWidth}px at glyph width ${characterWidth} (${mode})`, async () => {+ const item = fixture({viewportWidth, characterWidth});+ const points = await item.setupEdge(mode, "cross-line");+ assert.ok(points.geometry.editable.right <= viewportWidth - 32, JSON.stringify(points.geometry));+ assert.equal(item.prefix.textContent, "1".repeat(Math.min(141,+ Math.floor((viewportWidth - 36 - 32 - 17.671875 - 2) / characterWidth))));+ assert.equal(points.geometry.prefixLines.length, 1);+ assert.ok(points.after.y > points.before.y, "cross-line endpoints must occupy different lines");+ if (mode === "left") {+ assert.equal(points.mathLeft, points.prefixLeft);+ assert.ok(points.geometry.math.top > points.geometry.prefixLines[0].bottom);+ } else {+ assert.equal(points.geometry.math.top, points.geometry.prefixLines[0].top);+ assert.ok(points.mathLeft > points.prefixLeft + points.width - 30);+ }+ for (const point of [points.before, points.after, points.left, points.right, points.mathEnd]) {+ assert.ok(point.x >= 0 && point.x < viewportWidth, JSON.stringify(point));+ assert.ok(point.y >= 0 && point.y < 600, JSON.stringify(point));+ }+ });+ }+ }+}++test("inline math edge geometry rejects a viewport too narrow for the fixture", async () => {+ await assert.rejects(fixture({viewportWidth: 80}).setupEdge("left", "cross-line"), /viewport|Prefix/i);+});++test("inline math edge geometry preserves both suffix hit characters at its narrow boundary", async () => {+ const item = fixture({viewportWidth: 133});+ const points = await item.setupEdge("left", "cross-line");+ assert.equal(item.prefix.textContent.length, 6);+ assert.ok(points.after.y >= points.geometry.math.top && points.after.y < points.geometry.math.bottom);+ await assert.rejects(fixture({viewportWidth: 132}).setupEdge("left", "cross-line"), /Invalid inline math edge layout/);+});++test("inline math edge geometry rejects a prefix that wraps after measurement", async () => {+ const item = fixture({viewportWidth: 1024});+ item.prefix.getClientRects = () => [rect(36, 42, 900), rect(36, 68, 30)];+ await assert.rejects(item.setupEdge("left", "cross-line"), /Invalid inline math edge layout/);+});++test("inline math edge geometry waits for fonts before measuring", async () => {+ const item = fixture({viewportWidth: 1024});+ let finishFonts;+ item.document.fonts.ready = new Promise(resolve => { finishFonts = resolve; });+ const pending = item.setupEdge("left", "cross-line");+ await Promise.resolve();+ assert.equal(item.editable.style.width, undefined);+ finishFonts();+ await pending;+ assert.ok(item.editable.style.width.endsWith("px"));+});++const pointFixture = () => {+ const item = fixture({viewportWidth: 1024});+ item.document.elementFromPoint = () => item.prefix;+ item.document.caretRangeFromPoint = () => ({startContainer: item.prefixText, startOffset: 1});+ const validateDragPoints = new Function("document", "innerWidth", "innerHeight",+ `return (${extract("validateDragPoints")});`)(item.document, 1024, 600);+ return {...item, validateDragPoints};+};++test("inline math drag preflight accepts hit and caret within the intended editor", () => {+ const item = pointFixture();+ assert.equal(item.validateDragPoints({x: 36, y: 50}, {x: 70, y: 76}), true);+});++for (const point of [{x: 1066, y: 50}, {x: 1024, y: 50}, {x: -1, y: 50},+ {x: 36, y: 600}, {x: 36, y: -1}, {x: NaN, y: 50}, {x: 36, y: Infinity}]) {+ for (const endpoint of ["from", "to"]) {+ test(`inline math drag preflight rejects ${endpoint} outside the viewport: ${JSON.stringify(point)}`, () => {+ const item = pointFixture();+ const points = {from: {x: 36, y: 50}, to: {x: 70, y: 76}, [endpoint]: point};+ assert.throws(() => item.validateDragPoints(points.from, points.to), new RegExp("Invalid native selection drag " + endpoint));+ });+ }+}++for (const failure of ["missing-hit", "foreign-hit", "missing-caret", "foreign-caret"]) {+ test(`inline math drag preflight rejects ${failure}`, () => {+ const item = pointFixture();+ if (failure.endsWith("hit")) {+ item.document.elementFromPoint = () => failure === "missing-hit" ? null : item.document.body;+ } else {+ item.document.caretRangeFromPoint = () => failure === "missing-caret" ? null :+ {startContainer: item.document.body, startOffset: 0};+ }+ assert.throws(() => item.validateDragPoints({x: 36, y: 50}, {x: 70, y: 76}), /Invalid native selection drag from/);+ });+}++const dragFixture = () => {+ const item = pointFixture();+ const sent = [];+ const win = {webContents: {executeJavaScript: async script => {+ if (script.includes("Invalid native selection drag")) {+ return new Function("document", "innerWidth", "innerHeight", `return ${script};`)(item.document, 1024, 600);+ }+ if (script === "getSelection().toString()") return "IE";+ if (script.includes("cloneContents")) return String.raw`$I_{\mathrm{E}}$`;+ }}};+ const drag = new Function("win", "send", "assert", "validateDragPoints", `return (${extract("drag")});`)(+ win, async event => sent.push(event), assert, item.validateDragPoints);+ return {...item, drag, sent};+};++test("inline math drag validates the same integer endpoints that it dispatches", async () => {+ const item = dragFixture();+ const hits = [];+ item.document.elementFromPoint = (x, y) => { hits.push({x, y}); return item.prefix; };+ await item.drag({x: 36.7, y: 50.5}, {x: 70.671875, y: 76.5}, true);+ assert.deepEqual(hits, [{x: 36, y: 50}, {x: 70, y: 76}]);+ for (const [type, point] of [["mousePressed", hits[0]], ["mouseReleased", hits[1]]]) {+ const event = item.sent.find(value => value.type === type);+ assert.equal(event.x, point.x);+ assert.equal(event.y, point.y);+ }+});++test("inline math drag fails before dispatch when integer rounding misses the editor", async () => {+ const item = dragFixture();+ item.document.elementFromPoint = x => x >= 36.2 ? item.prefix : item.document.body;+ await assert.rejects(item.drag({x: 36.7, y: 50.5}, {x: 70.671875, y: 76.5}, true), /Invalid native selection drag from/);+ assert.deepEqual(item.sent, []);+});