diff --git a/.github/workflows/native-tests.yml b/.github/workflows/native-tests.yml index 4f10111c..ddd16746 100644 --- a/.github/workflows/native-tests.yml +++ b/.github/workflows/native-tests.yml @@ -8,6 +8,10 @@ on: tested_sha: description: Exact 40-character plugin commit approved for this run required: true + kplex_sha: + description: Exact K-Plex companion commit approved for ontology integration + required: true + default: 6c9c48cff3054c41b5aac9395ac06f65ddb7f8b4 profile: type: choice options: [regression, smoke, full, devices, soak, cold] @@ -28,11 +32,15 @@ jobs: EXCALIDRAW_TEST_REPORT_DIR: ${{ github.workspace }}/.test-work/reports/native-ci EXCALIDRAW_FORK_ROOT: ${{ github.workspace }}/.test-work/checkouts/fork EXCALIDRAW_EXTRAS_ROOT: ${{ github.workspace }}/.test-work/checkouts/extras + EXCALIDRAW_KPLEX_ROOT: ${{ github.workspace }}/.test-work/checkouts/kplex steps: - name: Require an exact approved commit env: TESTED_SHA: ${{ inputs.tested_sha }} - run: if ($env:TESTED_SHA -notmatch '^[a-f0-9]{40}$') { throw 'Supply an exact approved commit SHA' } + KPLEX_SHA: ${{ inputs.kplex_sha }} + run: | + if ($env:TESTED_SHA -notmatch '^[a-f0-9]{40}$') { throw 'Supply an exact approved plugin commit SHA' } + if ($env:KPLEX_SHA -notmatch '^[a-f0-9]{40}$') { throw 'Supply an exact approved K-Plex commit SHA' } - uses: actions/checkout@v4 with: ref: ${{ inputs.tested_sha }} @@ -46,24 +54,31 @@ jobs: - uses: actions/checkout@v4 with: repository: zsviczian/excalidraw - ref: 801c17c372cf3f9f18b3f253844348b8b9a67570 + ref: 278ed4937dde5fd9e77c83a4e25e5a9b3d8028f7 path: .test-work/checkouts/fork persist-credentials: false - uses: actions/checkout@v4 with: repository: zsviczian/obsidian-excalidraw-extras - ref: df1f2b5659259c43780c5ef07cd433fa6c3e14fa + ref: e247088e1222935a2bb006e94658b639916e0814 path: .test-work/checkouts/extras persist-credentials: false + - uses: actions/checkout@v4 + with: + repository: zsviczian/kplex + ref: ${{ inputs.kplex_sha }} + path: .test-work/checkouts/kplex + persist-credentials: false - uses: actions/setup-node@v4 with: - node-version: '22.22.3' + node-version: '22.22.2' - name: Prove session ownership before any native mutation run: node scripts/testing/host/requireIsolatedSession.mjs - run: npm ci - run: corepack enable - run: yarn --cwd .test-work/checkouts/fork install --frozen-lockfile - run: npm ci --prefix .test-work/checkouts/extras + - run: npm ci --prefix .test-work/checkouts/kplex - name: Run approved native profile env: TEST_PROFILE: ${{ inputs.profile }} diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 46761322..fa22a723 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -18,13 +18,13 @@ jobs: - uses: actions/checkout@v4 with: repository: zsviczian/excalidraw - ref: 801c17c372cf3f9f18b3f253844348b8b9a67570 + ref: 278ed4937dde5fd9e77c83a4e25e5a9b3d8028f7 path: .test-work/checkouts/fork persist-credentials: false - uses: actions/checkout@v4 with: repository: zsviczian/obsidian-excalidraw-extras - ref: df1f2b5659259c43780c5ef07cd433fa6c3e14fa + ref: e247088e1222935a2bb006e94658b639916e0814 path: .test-work/checkouts/extras persist-credentials: false - uses: actions/setup-node@v4 diff --git a/.gitignore b/.gitignore index b32897df..2277fe72 100644 --- a/.gitignore +++ b/.gitignore @@ -31,3 +31,4 @@ repository.zip .test-work/ !tests/vault/.obsidian/plugins/obsidian-excalidraw-plugin/data.json !tests/vault/.obsidian/plugins/excalidraw-extras/data.json +!tests/fixtures/kplex-ontology/data.json diff --git a/RefactorPlan.md b/RefactorPlan.md index f8559873..5277d1cd 100644 --- a/RefactorPlan.md +++ b/RefactorPlan.md @@ -3503,3 +3503,21 @@ remain strict pending maintainer classification; no production changes. - PR #3028 integration, 2026-11-01: resolved documentation conflicts with current master by retaining its newer release-note editorial rules in CODING_STANDARDS.md. The maintainer requested immediate merge without waiting for CI or additional checks. + +- PR #3033 optional ontology completion, 2026-11-03: keep the existing typed + attachment, input-owned InlineLinkSuggester popup/scope and fork unchanged. + K-Plex owns shared native/public matching and ordered physical candidates; + Excalidraw owns wrapper/caret mutation and rejects stale provider/configuration + selections. Balanced filename brackets retain their own closers. A linked + source worktree shares only its verified primary checkout's marker-owned test + vault, with both actual plugin builds frozen, hashed, enabled and restored. + Focused acceptance passes 20 Windows Obsidian 1.14.5 native cases across + main/popout and emulated phone/tablet, including input Undo/Redo, scripted IME, + provider lifecycle, saved links and native Markdown insertion. Strict error + gates/cleanup pass; earlier discovery, migration, seed-write and delayed-read + failures remain recorded. Source helpers have whole-module protocol/bounds + tests and the actual class covers subpaths, aliases and wrapper insertion. + Final combined portable/full-native source and artifact identities belong to + the coordinated PR handoff. Highest-risk manual follow-up: physical OS IME + composition/Undo, physical mobile text entry, and macOS popout save/reopen; + desktop emulation does not establish those platforms. diff --git a/docs/KPLEX_ONTOLOGY_COMPLETION.md b/docs/KPLEX_ONTOLOGY_COMPLETION.md new file mode 100644 index 00000000..093e1538 --- /dev/null +++ b/docs/KPLEX_ONTOLOGY_COMPLETION.md @@ -0,0 +1,69 @@ +# Optional K-Plex ontology completion + +Excalidraw's existing inline link suggester can use the optional +`window.kplexApi.v1.completeOntology` capability. K-Plex owns trigger matching, +role eligibility, inverse-aware filtering, ordering and field annotations. +Excalidraw reads no private K-Plex settings or editor instances and performs no +ontology matching of its own. No fork change or hard plugin dependency is needed. + +The element-link editor, text inputs and ExcalidrawAutomate's existing +`attachInlineLinkSuggester()` share one input-owned popup and keyboard scope. +File, alias, heading, block, frame, clipped-frame and tag contexts take precedence. +The integration keeps K-Plex's exact physical spelling; annotations are inert text. + +With `|` denoting the caret: + +```text +:::| → friend::| +::p| → parent::| +(:::| → (parent:: |) +(::p|) → (parent:: |) +[:::| → [friend:: |] +[:::|] → [friend:: |] +``` + +Adjacent wrappers retain their opener and existing matching closer. Missing +closers are inserted before unrelated suffix text. Type `[[` after selection to +continue ordinary note completion, including bracket-containing filenames. +K-Plex's `boldFields` and Markdown trailing-space policy remain specific to its +native Markdown suggester; HTML link inputs use plain field names. + +Every input update and selection reacquires the public provider. Selection checks +the provider/API/method identity, configuration revision, original text/caret, +replacement range and selected exact field. A stale row cannot edit the input. +Semantic/index revisions do not invalidate these configuration-only offers. +Missing, disabled, incompatible, retired or malformed providers leave ordinary +editing and existing completion available. Reload needs no plugin restart. + +The consumer accepts at most 65,536 UTF-16 input units and requests 20 candidates +within K-Plex's advertised completion limits. It validates bounded detached +results before displaying them. Wrapper mutation, caret placement, input/change +events and browser Undo belong to Excalidraw's owning input document. Composition +temporarily closes suggestions and fences Enter until composition ends. + +## Combined validation + +`npm run test:kplex-ontology` builds the selected fork, Extras, K-Plex and plugin, +freezes their artifacts, verifies hashes, then stages the actual plugins in +`.test-work/vaults/excalidraw-auto-test/`. Set `EXCALIDRAW_KPLEX_ROOT` when K-Plex +is not the sibling `../kplex`. Fork and Extras retain their existing root overrides. +The test vault's small K-Plex fixture uses on-demand indexing on every device. +Preparation acknowledges only K-Plex's owned theme migration dialog through its +normal action; it verifies all declared settings before exercising the UI. + +The focused command covers main/popout completion, exact carets, keyboard/mouse +selection, Undo/Redo, scripted composition, note continuation, physical drawing +save/reopen, native Markdown insertion, passive API reads, live configuration and +provider disable/re-enable/reload. Full native/regression profiles require these +cases and repeat them in responsive phone/tablet layouts. Desktop mobile +emulation does not establish physical touch, OS IME or native mobile WebView behavior. + +A linked Git worktree shares only its verified primary checkout's marker-owned +native vault. Build/source roots remain worktree-local. Git common-directory and +reverse ownership checks reject copied or redirected metadata; arbitrary vault +overrides remain forbidden. The shared application-user-data lock still serializes +all staging, native cases and cleanup across repositories. + +Release coordination: ship K-Plex's additive public capability before, or together +with, this plugin feature. Earlier K-Plex versions remain compatible but offer no +ontology completion. No release version or published package is changed here. diff --git a/docs/OBSIDIAN_RUNTIME_TESTING.md b/docs/OBSIDIAN_RUNTIME_TESTING.md index e585e7ca..322ff875 100644 --- a/docs/OBSIDIAN_RUNTIME_TESTING.md +++ b/docs/OBSIDIAN_RUNTIME_TESTING.md @@ -1,5 +1,16 @@ # Obsidian runtime testing on macOS and Windows +The optional [K-Plex ontology completion lane](KPLEX_ONTOLOGY_COMPLETION.md) +builds and stages the companion K-Plex alongside the selected plugin/fork/Extras +artifacts. Use `npm run test:kplex-ontology` for focused main/popout coverage; +add `-- --devices --device-profiles=phone-portrait-light,tablet-portrait-full-light` +for the two responsive integration layouts. Full/regression profiles require +both. `EXCALIDRAW_KPLEX_ROOT` selects a non-sibling source checkout. The guarded +runner supplies and verifies all three `KPLEX_TEST_*` vault identity variables. +Build manifests and baseline restoration include K-Plex; missing capability or +producer artifacts cannot satisfy these cases. Source worktrees share only their +verified primary checkout's marker-owned test vault, under the same host lock. + Current acceptance is **2/2 complete matching-build passes**, each with all **357 required native cases**, including 258 behavioral obligations and 40 device/layout profiles. Final portable validation passes **666 cases** and the diff --git a/docs/TESTING.md b/docs/TESTING.md index dd25e4cd..2e8959ba 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -1,5 +1,11 @@ # Maintaining the test lanes +Optional K-Plex ontology completion has a combined fresh-build native lane: +`npm run test:kplex-ontology`. Its source, API contract, fixture ownership and +release coordination are documented in [K-Plex ontology completion](KPLEX_ONTOLOGY_COMPLETION.md). +The full native/regression profiles require its main/popout cases and responsive +phone/tablet cases. The ordinary portable lane keeps K-Plex optional. + ## Current checkpoint (2026-10-30) [Accessible sanitized case summaries and artifact manifests](testing-evidence/3022/README.md) diff --git a/docs/agent-handoffs/kplex-ontology-suggester.md b/docs/agent-handoffs/kplex-ontology-suggester.md deleted file mode 100644 index 9fc57297..00000000 --- a/docs/agent-handoffs/kplex-ontology-suggester.md +++ /dev/null @@ -1,60 +0,0 @@ -# K-Plex ontology completion — temporary handoff - -**Status:** Plan-only draft PR; no runtime implementation or completed feature tests. - -Prepared by Zsolt's Codex Agent on 2026-11-02 at the maintainer's request. - -The implementation plan and acceptance criteria belong to the draft PR on -`2026-11-02-kplex-ontology-suggester`. Continue on that branch; remove this -placeholder before finalizing the implementation. - -## Starting references - -- Plugin baseline: `master@5b926e2957f290a25d963bc08a661356b845f4a2`. -- K-Plex reference: `main@e757239ce41a29934bc8a2b74d598146b2bd7e10`. -- Read `AGENTS.md`, `CONTRIBUTING.md`, `CODING_STANDARDS.md`, - `docs/TESTING.md`, and `docs/OBSIDIAN_RUNTIME_TESTING.md` before implementation. -- Follow `docs/agent-workflows/issue-resolution.md` for plan-only PR handoff. - -## Requested outcome - -Use K-Plex's live configured ontology and trigger combinations in Excalidraw's -existing inline suggestion inputs, especially the native element-link editor. -With `|` denoting the caret, representative results are: - -```text -:::| -> friend::| -(::p| -> (parent:: |) -(:::|) -> (parent:: |) -[:::|] -> [friend:: |] -``` - -Use the selected physical field's exact spelling. Preserve surrounding text, -reuse an existing matching closer, and allow subsequent `[[note]]` completion. -K-Plex must remain optional; honor its disabled-suggester setting and custom or -historical triggers without rewriting configuration. - -## Important integration constraint - -K-Plex's documented entry point is `window.kplexApi.v1`. Its current public API -exposes ontology definitions, but not the native suggester's configured triggers, -enabled flag, or completion matcher. The PR must resolve that supported API gap; -do not read private settings, hijack a registered `EditorSuggest` instance, or -copy the matcher into Excalidraw. A narrow companion K-Plex capability should -reuse its existing matching and ontology-presentation owners. This branch does -not modify K-Plex or establish that such a capability already exists. - -Prefer the existing `InlineLinkSuggester` and typed host attachment boundary. -Do not add a second competing popup, a hard dependency, a whole-vault scan, or -an unrelated fork refactor. Validate actual input state, caret, keyboard scope, -scene persistence, lifecycle, popout ownership, and existing link/tag completion. - -Historical regression references, not issues fixed by this placeholder: -- [Ontology-wrapped embeds, fixed in 2.23.8](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2782). -- [K-Plex trigger defaults and saved-trigger compatibility](https://github.com/zsviczian/kplex/issues/109). - -Run focused executable regressions during implementation and the required -portable/native acceptance profiles before readiness. Stage companion artifacts -only in the repository-owned disposable test vault, record exact revisions and -hashes, and distinguish desktop mobile emulation from physical-device evidence. -Keep the PR draft and unmerged until implementation and validation are complete. diff --git a/package.json b/package.json index ce49421f..24155736 100644 --- a/package.json +++ b/package.json @@ -40,6 +40,7 @@ "test:image-geometry": "node --experimental-strip-types --test tests/markdownImage*.test.mjs scripts/testing/textElementParsing.test.mjs", "test:drop-actions": "node --test scripts/testing/dropActions.test.mjs", "test:inline-link-suggester": "node --test scripts/testing/inlineLinkSuggester.test.mjs", + "test:kplex-ontology": "node scripts/testing/host/verify.mjs --kplex-ontology", "verify:obsidian": "node scripts/testing/host/verify.mjs", "verify:obsidian:plugin": "node scripts/testing/host/verify.mjs", "lib": "cross-env NODE_ENV=lib rollup --config rollup.config.mjs", @@ -150,4 +151,4 @@ "node": ">=22.0.0", "npm": ">=10.0.0" } -} \ No newline at end of file +} diff --git a/scripts/testing/contracts.mjs b/scripts/testing/contracts.mjs index 154ba18b..475b602e 100644 --- a/scripts/testing/contracts.mjs +++ b/scripts/testing/contracts.mjs @@ -10,6 +10,7 @@ export const REQUIRED_ROLES = { plugin: ["main", "manifest", "styles"], fork: ["production-js", "production-css", "development-js", "development-css", "declarations"], extras: ["main", "manifest", "styles", "declarations"], + kplex: ["main", "manifest", "styles"], }; export const sha256 = value => createHash("sha256").update(value).digest("hex"); export const fileHash = path => sha256(readFileSync(path)); diff --git a/scripts/testing/host/combination.mjs b/scripts/testing/host/combination.mjs index 5fcce394..09d56ba4 100644 --- a/scripts/testing/host/combination.mjs +++ b/scripts/testing/host/combination.mjs @@ -24,6 +24,7 @@ export function produceCombination({ pluginRoot, forkRoot, extrasRoot, + kplexRoot, output, }) { output = resolve(output); @@ -33,6 +34,7 @@ export function produceCombination({ plugin: resolve(pluginRoot), fork: resolve(forkRoot), extras: resolve(extrasRoot), + ...(kplexRoot ? {kplex: resolve(kplexRoot)} : {}), }, manifests = {}; const run = ({ manager, args, cwd }) => { @@ -65,6 +67,10 @@ export function produceCombination({ run, }); } + if (roots.kplex) { + assert.ok(existsSync(join(roots.kplex, "package.json")), "K-Plex workspace is required for ontology integration coverage"); + manifests.kplex = produceArtifacts({root: roots.kplex, kind: "kplex", snapshotRoot: join(output, "kplex"), run}); + } const installed = JSON.parse( readFileSync( join(roots.plugin, "node_modules/@zsviczian/excalidraw/package.json"), diff --git a/scripts/testing/host/devices.mjs b/scripts/testing/host/devices.mjs index 1be8520c..205ba768 100644 --- a/scripts/testing/host/devices.mjs +++ b/scripts/testing/host/devices.mjs @@ -14,6 +14,7 @@ import { writeReportFiles } from "../reportFiles.mjs"; import { waitForNativeReady } from "./hostReadiness.mjs"; import { mainWindowExpression, restoreDeviceState } from "./deviceRecovery.mjs"; import { runBehaviorMatrix } from "./behaviorMatrix.mjs"; +import { runKplexOntologyScenario } from "./kplexOntology.mjs"; import {acquireBrowserDiagnostics,classifyCLIErrorText,splitWindowErrors} from './browserDiagnostics.mjs'; import { constrainedViewportMetrics, viewportInput } from "./deviceViewport.mjs"; import { retryReadOnly } from "./readOnlyTransport.mjs"; @@ -29,6 +30,7 @@ export async function runDeviceMatrix({ profiles = deviceProfiles(), featureWorkflows = false, featureCases, + kplexOntology = false, }) { reportDir = resolve(reportDir); const target = validateTarget({ @@ -197,6 +199,11 @@ export async function runDeviceMatrix({ if(workflows.transportDiagnostics?.length)(report.transportDiagnostics||=[]).push(...workflows.transportDiagnostics); expectedConsoleErrors.push(...(workflows.expectedConsoleErrors || [])); } + let ontology; + if(kplexOntology && ["phone-portrait-light","tablet-portrait-full-light"].includes(profile.id)) { + ontology=await runKplexOntologyScenario({cli,drawingPath:path,contexts:[profile.id.startsWith("phone-")?"phone":"tablet"],inputMode:"touch",viewportScale:viewportMetrics?.scale??1}); + report.tests.push(...ontology.tests); + } // Clearing viewport emulation resizes the real host again. Include that // teardown in the quiet/error gate before starting the next profile. if (viewportMetrics) {cli("dev:cdp", "method=Emulation.clearDeviceMetricsOverride", "params={}");viewportMetrics=null;} @@ -204,13 +211,14 @@ export async function runDeviceMatrix({ const errors = [ ...debuggerSession.read(), ...(workflows?.consoleErrors || []), + ...(ontology?.consoleErrors || []), ]; const unexpected = unexpectedConsoleErrors(errors, expectedConsoleErrors), windowErrorText = cli("dev:errors").trim(); const windowEvents=browserSession.read(),classified=splitWindowErrors(windowEvents),cliErrors=classifyCLIErrorText(windowErrorText); const errorGatePassed = unexpected.length === 0 && - classified.unexpected.length===0 && cliErrors.unexpected.length===0 && browserIdle.status==='passed' && (!workflows||workflows.status==='passed'); + classified.unexpected.length===0 && cliErrors.unexpected.length===0 && browserIdle.status==='passed' && (!workflows||workflows.status==='passed') && (!ontology||ontology.status==='passed'); browserSession.dispose();browserSession=null; if(debuggerSession.transportDiagnostics?.length)report.transportDiagnostics.push(...debuggerSession.transportDiagnostics.map(item=>({profile:profile.id,...item}))); debuggerSession.dispose(); diff --git a/scripts/testing/host/kplexOntology.mjs b/scripts/testing/host/kplexOntology.mjs new file mode 100644 index 00000000..69358161 --- /dev/null +++ b/scripts/testing/host/kplexOntology.mjs @@ -0,0 +1,231 @@ +/** Combined fresh-build coverage through the real element-link and Markdown editors. */ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { runInAppTask } from "./inAppTask.mjs"; +import { behaviorEnvironment } from "./behaviorEnvironment.mjs"; +import { behaviorInputDriver } from "./behaviorMatrix.mjs"; +import { completeConsoleErrors } from "./debuggerSession.mjs"; +import { settleBrowserDiagnostics, splitWindowErrors } from "./browserDiagnostics.mjs"; + +const casesFor = ids => ids.flatMap(id => [ + "native:kplex-ontology-passive:" + id, + "native:kplex-ontology-links:" + id, + "native:kplex-ontology-configuration:" + id, + "native:kplex-ontology-provider:" + id, + "native:kplex-ontology-markdown:" + id, +]); +export const kplexOntologyCaseIds = casesFor(["main", "popout"]); +export const kplexOntologyDeviceCaseIds = casesFor(["phone", "tablet"]); + +/** The caller owns staging, hashes, the shared application lock and outer error capture. */ +export async function runKplexOntologyScenario({ cli, drawingPath, contexts=["main", "popout"], inputMode="mouse", viewportScale=1 }) { + const template = readFileSync(new URL("../../../tests/vault/Drawings/Uncompressed.excalidraw.md", import.meta.url), "utf8"); + const tests = [], consoleErrors = [], windowErrors = [], browserIdle = []; + for (const id of contexts) { + const execute = new Function(`return async function(c,path,context,template,modifier){ + const env=await (${behaviorEnvironment.toString()})(c,path,context,template,${completeConsoleErrors.toString()},${settleBrowserDiagnostics.toString()}); + const runCase=c.case.bind(c);c.case=async (...args)=>{c.phase=args[0];return runCase(...args);}; + try { await (${exerciseKplexOntology.toString()})(c,env,modifier); } + catch(error){c.observations={...c.observations,diagnostics:env.diagnostics()};throw error;} + return {tests:c.tests,consoleErrors:c.externalConsoleErrors||[],windowErrors:env.windowErrors,browserIdle:env.browserIdle}; + }`)(); + const result = await runInAppTask({cli, execute, + args: [drawingPath, {id, input:inputMode}, template, process.platform === "darwin" ? 4 : 2], + timeoutMs: 300000, cleanupMs: 60000, onRequest: request => { + if (request.method !== "kplex-lifecycle") return behaviorInputDriver(cli,viewportScale)(request); + assert.ok(["disable","enable"].includes(request.params.command),"Bounded companion lifecycle command required"); + cli("plugin:" + request.params.command,"id=k-plex");return {completed:true}; + }, + onProgress: phase => process.stdout.write("ontology " + id + ": " + phase + "\n"), + }).catch(error => {error.evidence = [...tests, ...(error.evidence || [])]; throw error;}); + tests.push(...result.tests); consoleErrors.push(...result.consoleErrors); + windowErrors.push(...result.windowErrors); browserIdle.push(...result.browserIdle); + } + assert.equal(consoleErrors.length, 0, "Ontology emitted console errors"); + assert.equal(splitWindowErrors(windowErrors).unexpected.length, 0, "Ontology emitted window errors"); + assert.ok(browserIdle.every(result => result.status === "passed"), "Ontology did not settle"); + return {id:"kplex-ontology", status:"passed", tests, consoleErrors, windowErrors, browserIdle}; +} + +/** Trusted input and actual React submission/persistence, with test-owned settings restoration. */ +async function exerciseKplexOntology(c, env, modifier) { + const {p,doc,win,check,openDrawing,saveReopen,key,input,click,geometry,create,leaf} = env; + let host = app.plugins.plugins["k-plex"]; + check(host && window.kplexApi?.v1?.completeOntology, "Combined K-Plex completion build unavailable"); + const settings = structuredClone(host.settings); + c.defer(async () => { + if (!app.plugins.plugins["k-plex"]) await app.plugins.enablePlugin("k-plex"); + const current=app.plugins.plugins["k-plex"];check(current,"Companion did not return during cleanup"); + Object.assign(current.settings, settings);await current.saveSettings(false,false); + }); + const type = text => input("Input.insertText", {text}); + let view, elementId; + const current = () => view.excalidrawAPI.getSceneElements().find(e => e.id === elementId); + const popup = () => doc.querySelector(".excalidraw-hyperlinkContainer-input"); + const rows = () => [...doc.querySelectorAll(".excalidraw-ontology-suggestion")]; + const open = async text => { + view.excalidrawAPI.updateScene({appState:{selectedElementIds:{[elementId]:true}}}); + view.containerEl.querySelector(".excalidraw").focus(); + await key("k","KeyK",75,modifier); + let field; + await c.waitFor(() => field = popup(), "actual element-link input"); + await click(popup); field = popup(); await key("a","KeyA",65,modifier); await type(text); + c.observations = {context:geometry().requested.id, value:field.value,caret:field.selectionStart}; + return field; + }; + const choose = async (field,name,method="click") => { + let row; + await c.waitFor(() => row = rows().find(row => row.querySelector(".suggestion-title")?.textContent === name || row.firstElementChild?.textContent === name), "ontology row " + name); + check(!row.querySelector("b"), "Ontology annotation became markup"); + if (method === "click") await click(row); + else { + for (let step=0;step {await key("Escape","Escape",27);await c.waitFor(() => !popup(), "link editor closes");}; + await c.case("native:kplex-ontology-passive:" + geometry().requested.id,["P04","P11"],async () => { + const restore=[],calls=[]; + const forbid=(owner,name)=>{ + if(typeof owner?.[name]!=="function")return; + const previous=Object.getOwnPropertyDescriptor(owner,name); + Object.defineProperty(owner,name,{configurable:true,writable:true,value:()=>{calls.push(name);throw Error("Completion acquired forbidden capability: "+name);}}); + restore.push(()=>{if(previous)Object.defineProperty(owner,name,previous);else Reflect.deleteProperty(owner,name);}); + }; + try { + for(const name of ["read","cachedRead","readBinary","getFiles","getMarkdownFiles","modify","create"])forbid(app.vault,name); + for(const name of ["read","readBinary","list","write","writeBinary"])forbid(app.vault.adapter,name); + for(const name of ["saveData","saveSettings"])forbid(host,name); + for(const owner of new Set([window,win]))for(const name of ["fetch","setTimeout","setInterval"])forbid(owner,name); + const index=host.index; + for(const name of new Set([...Object.getOwnPropertyNames(index),...Object.getOwnPropertyNames(Object.getPrototypeOf(index))])) { + if(name!=="constructor"&&name!=="getSemanticRevision")forbid(index,name); + } + for(const text of [":::friend","::ppar","::c","::f","::r","::s","::n","Prose (:::parent) suffix"]){ + const cursor=text.includes(")")?text.indexOf(")"):text.length,result=window.kplexApi.v1.completeOntology({text,cursor}); + check(result.ok && result.coverage.scope === "configuration" && result.coverage.complete,"Settings-only native completion acquired another owner"); + } + check(calls.length===0,"Completion performed forbidden work: "+calls.join(",")); + } finally {for(const reset of restore.reverse())reset();} + return {assertions:["real loaded API with all roles and inline prefix","no graph/index work, Markdown reads, vault enumeration, writes, timers or fetch during synchronous completion"]}; + }); + await c.case("native:kplex-ontology-links:" + geometry().requested.id,["P02","P04"],async () => { + view = await openDrawing("ontology-links"); + const ea = p.ea.getAPI(view); + try {ea.reset();elementId = ea.addRect(0,0,220,100);await ea.addElementsToView(false,true,true);} + finally {ea.destroy();} + view.excalidrawAPI.zoomToFit([current()],1,0.1); + const variants = [ + [":::","friend","friend::",8], + ["::p","parent","parent::",8], + ["(:::","parent","(parent:: )",10], + ["(::p)","parent","(parent:: )",10,4], + ["[:::","friend","[friend:: ]",10], + ["[:::]","friend","[friend:: ]",10,4], + [":::par","Parent Exact","Parent Exact::",14], + ]; + for (const [index,[source,name,expected,caret,cursor]] of variants.entries()) { + const field = await open(source); + if (cursor !== undefined) {field.setSelectionRange(cursor,cursor);field.dispatchEvent(new win.Event("input",{bubbles:true}));} + await choose(field,name,index === 1 ? "Enter" : index === 2 ? "Tab" : "click"); + check(field.value === expected && field.selectionStart === caret && field.selectionEnd === caret,"Ontology replacement/caret mismatch: " + JSON.stringify({source,value:field.value,caret:field.selectionStart,expected})); + if (index === 1) { + await key("z","KeyZ",90,modifier);await c.waitFor(() => field.value === source,"native input Undo restores the trigger"); + await key("z","KeyZ",90,modifier|8);await c.waitFor(() => field.value === expected,"native input Redo restores completion"); + } + await close(); + check(current().link === expected,"React element-link submission ignored completed value"); + } + const note = await create("Note [draft].md","Ontology completion target."); + for (const opener of ["(","["]) { + const field = await open(opener + ":::"), closer = opener === "(" ? ")" : "]"; + await choose(field,"parent"); + await type("[[Note [draft]"); + let row; + await c.waitFor(() => row = [...doc.querySelectorAll(".suggestion-item")].find(row => row.textContent.includes("Note [draft]")), "existing bracket-filename note completion"); + await click(row); + check(field.value.includes("[[" + note.basename + "]]"), "Existing note completion was not preserved"); + check(field.value.endsWith(closer),"Ontology wrapper closer was lost"); + const expected = field.value; + await close(); + check(current().link === expected,"Element link differs after note completion"); + view = await saveReopen(view); + check(current().link === expected,"Completed element link differs after physical save/reopen"); + } + return {assertions:["seven actual link replacements and collapsed carets","click, Enter, Tab and keyboard navigation","native input Undo/Redo","bracket-filename note continuation in both wrappers","actual React submission and physical save/reopen"]}; + }); + await c.case("native:kplex-ontology-configuration:" + geometry().requested.id,["P04","P06","P11"],async () => { + const field = await open("::p"); + await c.waitFor(() => rows().length, "initial live ontology rows"); + host.settings.ontologySuggesterParentTrigger = "@@"; + await host.saveSettings(false,false); + const stale = rows().find(row => row.textContent.includes("parent")); + check(stale,"Missing captured stale row"); + await click(stale); + check(field.value === "::p","Stale configuration selection mutated input"); + await key("a","KeyA",65,modifier);await type("@@"); + await choose(field,"parent");check(field.value === "parent::","Custom live trigger was ignored"); + await close(); + host.settings.allowOntologySuggester = false;await host.saveSettings(false,false); + const disabled = await open(":::"); + check(rows().length === 0,"Disabled K-Plex retained ontology rows"); + await close(); + host.settings.allowOntologySuggester = true;Object.assign(host.settings,settings);await host.saveSettings(false,false); + const enabled = await open("::p");await choose(enabled,"parent");check(enabled.value === "parent::","Re-enabled K-Plex not reacquired");await close(); + const composing = await open("::p"); + composing.dispatchEvent(new win.CompositionEvent("compositionstart",{bubbles:true})); + await key("Enter","Enter",13);check(popup() === composing,"IME Enter submitted the link editor"); + check(rows().length === 0,"IME retained an ontology popup"); + composing.dispatchEvent(new win.CompositionEvent("compositionend",{bubbles:true})); + await choose(composing,"parent");await close(); + return {assertions:["live custom trigger","stale configuration row rejected","disable/re-enable reacquires public completion","scripted composition fences Enter without submitting"]}; + }); + await c.case("native:kplex-ontology-provider:" + geometry().requested.id,["P03","P04","P11"],async () => { + const field=await open("::p");await c.waitFor(()=>rows().length,"provider lifecycle rows"); + const old=window.kplexApi; + await c.requestHost("kplex-lifecycle",{command:"disable"}); + await c.waitFor(()=>!app.plugins.plugins["k-plex"]&&!window.kplexApi&&!win.kplexApi,"public aliases retire on disable"); + check(old.v1.completeOntology({text:"::p",cursor:3}).error?.code==="API_UNAVAILABLE","Retired public API remained available"); + const stale=rows().find(row=>row.querySelector(".suggestion-title")?.textContent==="parent"); + check(stale,"Provider retirement unexpectedly consumed its offered UI row");await click(stale); + check(field.value==="::p","Retired provider selection mutated the link"); + await key("a","KeyA",65,modifier);await type("[[Note"); + let noteRow; + await c.waitFor(()=>noteRow=[...doc.querySelectorAll(".suggestion-item")].find(row=>row.textContent.includes("Note [draft]")),"note completion without K-Plex"); + await click(noteRow);check(field.value.includes("[[Note [draft]]]"),"Missing K-Plex broke ordinary note selection");await close(); + await c.requestHost("kplex-lifecycle",{command:"enable"}); + await c.waitFor(()=>window.kplexApi&&window.kplexApi!==old&&win.kplexApi===window.kplexApi,"reloaded public API in the owning window"); + host=app.plugins.plugins["k-plex"]; + const reloaded=await open("::p");await choose(reloaded,"parent");check(reloaded.value==="parent::","Reloaded provider was not reacquired");await close(); + const incompatible=await open("::p");await c.waitFor(()=>rows().length,"missing-capability baseline"); + const aliases=[...new Set([window,win])].map(owner=>[owner,Object.getOwnPropertyDescriptor(owner,"kplexApi")]); + try { + for(const [owner]of aliases)Object.defineProperty(owner,"kplexApi",{configurable:true,value:{version:1,v1:{version:1,capabilities:()=>({ok:true,value:{operations:[]}})}}}); + const row=rows().find(row=>row.querySelector(".suggestion-title")?.textContent==="parent");await click(row); + check(incompatible.value==="::p","Missing capability accepted a stale selection"); + await key("a","KeyA",65,modifier);await type(":::");check(rows().length===0,"Missing capability retained ontology completion");await close(); + } finally {for(const [owner,descriptor]of aliases){if(descriptor)Object.defineProperty(owner,"kplexApi",descriptor);else Reflect.deleteProperty(owner,"kplexApi");}} + return {assertions:["actual plugin disable/enable and retired API refusal","stale provider row rejected","ordinary bracket-filename completion without K-Plex","new provider reacquired in the input realm","missing capability degrades without changing text"]}; + }); + await c.case("native:kplex-ontology-markdown:" + geometry().requested.id,["P04"],async () => { + const file = await create("Native-ontology.md",""); + await leaf.openFile(file);app.workspace.setActiveLeaf(leaf,{focus:true}); + const editor = leaf.view.editor;check(editor,"Actual Markdown editor unavailable");editor.focus(); + const expected="**parent**:: ";let metadataComplete=false; + const changed=app.metadataCache.on("changed",(changedFile,data)=>{if(changedFile===file&&data===expected)metadataComplete=true;}); + c.defer(()=>app.metadataCache.offref(changed)); + await type("::p"); + let row; + await c.waitFor(() => row = [...doc.querySelectorAll(".suggestion-item")].find(row => row.querySelector("b")?.textContent === "parent"),"native Markdown ontology row"); + await click(row); + check(editor.getValue() === expected,"Native Markdown bold/trailing-space insertion changed: " + editor.getValue()); + await leaf.view.save(); + await c.waitFor(()=>metadataComplete,"native Markdown save and metadata completion"); + check(await app.vault.read(file)===expected,"Native Markdown insertion was not physically persisted"); + await leaf.setViewState({type:"empty",state:{}}); + return {assertions:["real Markdown editor and native OntologySuggester","exact physical field with native bold and trailing space","physical Markdown save and completed metadata read before cleanup"]}; + }); +} diff --git a/scripts/testing/host/pluginDiscovery.mjs b/scripts/testing/host/pluginDiscovery.mjs index 6d400f95..aa8ddbf5 100644 --- a/scripts/testing/host/pluginDiscovery.mjs +++ b/scripts/testing/host/pluginDiscovery.mjs @@ -3,7 +3,7 @@ import assert from "node:assert/strict"; import { runInAppTask } from "./inAppTask.mjs"; export async function discoverStagedPlugin(cli, id) { assert.ok( - ["obsidian-excalidraw-plugin", "excalidraw-extras"].includes(id), + ["obsidian-excalidraw-plugin", "excalidraw-extras", "k-plex"].includes(id), "Unowned plugin discovery target", ); return runInAppTask({ diff --git a/scripts/testing/host/pluginDiscovery.test.mjs b/scripts/testing/host/pluginDiscovery.test.mjs index 2894d720..b66482d2 100644 --- a/scripts/testing/host/pluginDiscovery.test.mjs +++ b/scripts/testing/host/pluginDiscovery.test.mjs @@ -42,3 +42,8 @@ test("missing discovery capability fails with an explicit first-open prerequisit false, ); }); +test("combined coverage discovers only the explicitly supported companion", async () => { + const h = host({manifests:{"k-plex":{id:"k-plex"}}}); + assert.equal((await discoverStagedPlugin(h.cli,"k-plex")).discovery,"existing"); + await assert.rejects(discoverStagedPlugin(h.cli,"personal-plugin"),/Unowned plugin/); +}); diff --git a/scripts/testing/host/verify.mjs b/scripts/testing/host/verify.mjs index 11c3b867..17fe9cd4 100644 --- a/scripts/testing/host/verify.mjs +++ b/scripts/testing/host/verify.mjs @@ -26,6 +26,8 @@ import { runWorkflowFixesScenario } from "./workflowFixes.mjs"; import { runWorkflowBundleScenario } from "./workflowBundle.mjs"; import { runTextSaveShortcutScenario } from "./textSaveShortcut.mjs"; import { runCodeCardScenario } from "./codeCards.mjs"; +import { runKplexOntologyScenario } from "./kplexOntology.mjs"; +import { nativeRepositoryRoot } from "../nativeRepositoryRoot.mjs"; import { acquireHostLock } from "./hostLock.mjs"; import { runDataIntegrityScenario } from "./dataIntegrity.mjs"; import { runLifecycleScenario } from "./lifecycle.mjs"; @@ -106,6 +108,7 @@ const workflowFixes = coreScenarios || process.argv.includes("--workflow-fixes") const workflowBundle = coreScenarios || process.argv.includes("--workflow-bundle"); const textSaveShortcut = workflowBundle || process.argv.includes("--text-save-shortcut"); const codeCards = workflowBundle || process.argv.includes("--code-cards"); +const kplexOntology = coreScenarios || profile === "devices" || process.argv.includes("--kplex-ontology"); const behaviorMatrix = fullProfile || process.argv.includes("--behavior-matrix"); const dataIntegrity = coreScenarios || process.argv.includes("--data-integrity"); @@ -151,6 +154,7 @@ const flags = [ "--workflow-bundle", "--text-save-shortcut", "--code-cards", + "--kplex-ontology", "--lucide", "--text-undo", "--stability", @@ -191,6 +195,14 @@ const extrasRoot = resolve( const forkRoot = resolve( process.env.EXCALIDRAW_FORK_ROOT || join(pluginRoot, "../excalidraw"), ); +const kplexRoot = kplexOntology ? resolve(process.env.EXCALIDRAW_KPLEX_ROOT || join(nativeRepositoryRoot(pluginRoot), "../kplex")) : undefined; +if (kplexOntology) { + for (const [key,value] of Object.entries({KPLEX_TEST_VAULT_NAME:target.vaultName,KPLEX_TEST_VAULT_PATH:target.vaultPath,KPLEX_TEST_CONFIG_DIR:target.configDir})) { + const supplied=process.env[key]; + if(supplied && (key.endsWith("NAME")?supplied!==value:resolve(supplied)!==resolve(value)))throw Error("Combined K-Plex target differs from the owned vault: "+key); + process.env[key]=value; + } +} const reportDir = process.env.EXCALIDRAW_TEST_REPORT_DIR || join(pluginRoot, ".test-work/reports/native-" + randomUUID()); @@ -244,6 +256,7 @@ try { pluginRoot, forkRoot, extrasRoot, + kplexRoot, output: join(pluginRoot, ".test-work/frozen/combination-" + randomUUID()), }); const invokeCLI=(name,args,timeout)=>command(obsidianCliExecutable(),[`vault=${target.vaultName}`,name,...args],pluginRoot,timeout); @@ -360,6 +373,7 @@ try { ...(workflowBundle ? [runWorkflowBundleScenario] : []), ...(textSaveShortcut ? [runTextSaveShortcutScenario] : []), ...(codeCards ? [runCodeCardScenario] : []), + ...(kplexOntology ? [runKplexOntologyScenario] : []), // The catalogue/picker workflow runs after independent core scenarios. ...(lucide ? [runLucideScenario] : []), ], @@ -398,6 +412,7 @@ try { profiles: selectedDeviceIds ? allDeviceProfiles.filter(profile=>selectedDeviceIds.includes(profile.id)) : allDeviceProfiles, featureWorkflows: fullProfile || profile === "devices", featureCases:focusedCases, + kplexOntology, }); deviceReport.source = combination?.manifests.plugin || source; deviceReport.artifacts = report.artifacts.installedHashes; diff --git a/scripts/testing/inlineLinkSuggester.test.mjs b/scripts/testing/inlineLinkSuggester.test.mjs index 3fbb42b2..4726fa06 100644 --- a/scripts/testing/inlineLinkSuggester.test.mjs +++ b/scripts/testing/inlineLinkSuggester.test.mjs @@ -6,17 +6,29 @@ import test from "node:test"; import vm from "node:vm"; import ts from "typescript"; -function fixture({ connected, nested = false, deferTimers = false }) { +function fixture({ connected, nested = false, deferTimers = false, provider }) { const source = readFileSync(resolve(import.meta.dirname, "../../src/shared/Suggesters/InlineLinkSuggester.ts"), "utf8"); const javascript = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS } }).outputText; const exports = {}; const timers = []; + const ownerWindow = { kplexApi: provider, setTimeout: callback => deferTimers ? timers.push(callback) : callback() }; + ownerWindow.Event = class { constructor(type) { this.type = type; } }; + const helpers = new Map(); + function helper(name) { + if (helpers.has(name)) return helpers.get(name); + const source = readFileSync(resolve(import.meta.dirname, "../../src/shared/Suggesters", name.slice(2) + ".ts"), "utf8"); + const exports = {}; + vm.runInNewContext(ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS } }).outputText, + { exports, window: ownerWindow }); + helpers.set(name, exports); + return exports; + } vm.runInNewContext(javascript, { exports, require: name => name === "./SuggestionModal" ? { SuggestionModal: class { onInputChanged() { this.openedCount = (this.openedCount ?? 0) + 1; } - } } : {}, - window: { setTimeout: callback => deferTimers ? timers.push(callback) : callback() }, + } } : ["./kplexOntologyProvider", "./ontologyLinkCompletion"].includes(name) ? helper(name) : {}, + window: ownerWindow, }); const root = {}, scope = {}, modal = {}; const stack = nested ? [root, scope, modal] : [root, scope]; @@ -34,8 +46,9 @@ function fixture({ connected, nested = false, deferTimers = false }) { shouldNotOpen: true, block: true, suggestionGeneration: 0, + limit: 20, }); - return { instance, scope, root, modal, stack, released, timers }; + return { instance, scope, root, modal, stack, released, timers, ownerWindow, helper }; } test("closing a detached dropdown releases its keyboard scope", () => { @@ -97,3 +110,178 @@ test("a previous close timer does not unblock a newly opened suggestion session" h.timers.forEach(callback => callback()); assert.equal(h.instance.block, true); }); + +test("configured public ontology completion uses the existing inline popup owner", () => { + const revision = { semantic: 1, source: 1, configuration: 1 }; + const provider = { version: 1, v1: { version: 1, + capabilities: () => ({ ok: true, value: { version: 1, operations: ["completeOntology"] } }), + completeOntology: () => ({ ok: true, revision, value: { state: "matched", context: { + range: { start: 0, end: 3 }, query: "", role: "all", trigger: ":::", prefix: "", + }, items: [{ name: "friend", role: "left", roles: ["left"] }], truncated: false } }), + } }; + const h = fixture({ connected: false, provider }); + h.instance.inputEl = { value: ":::", selectionStart: 3, selectionEnd: 3, ownerDocument: { defaultView: h.ownerWindow } }; + h.instance.onInputChanged(); + assert.equal(h.instance.mode, "ontology"); + assert.equal(h.instance.getSuggestions()[0].item.name, "friend"); + assert.equal(h.instance.openedCount, 1); +}); + +/** Supply public detached data, not a second trigger matcher, to the real input owner. */ +function ontologyFixture(marked, name = "friend", trigger = ":::") { + const cursor = marked.indexOf("|"), text = marked.replace("|", ""), start = text.indexOf(trigger); + assert(cursor >= 0 && start >= 0); + const revision = { semantic: 1, source: 1, configuration: 1 }; + const result = { ok: true, revision, value: { state: "matched", context: { + range: { start, end: cursor }, query: text.slice(start + trigger.length, cursor), trigger, role: "all", prefix: "", + }, items: [{ name, role: "left", roles: ["left"], partner: "Partner", description: "Literal description" }], truncated: false } }; + let calls = 0; + const provider = { version: 1, v1: { version: 1, + capabilities: () => ({ ok: true, value: { operations: ["completeOntology"] } }), + completeOntology: request => { calls++; return request.text === text && request.cursor === cursor ? result : + { ok: true, revision, value: { state: "no-match", context: null, items: [], truncated: false } }; }, + } }; + const h = fixture({ connected: false, provider }); + const doc = { defaultView: h.ownerWindow, activeElement: null }; + const events = []; + const input = { value: text, selectionStart: cursor, selectionEnd: cursor, isConnected: true, ownerDocument: doc, + setSelectionRange(start, end) { this.selectionStart = start; this.selectionEnd = end; }, + focus() { doc.activeElement = this; }, + dispatchEvent(event) { events.push(event.type); if (event.type === "input") h.instance.onInputChanged(); return true; }, + }; + h.instance.inputEl = input; + h.instance.app.metadataCache = { getFirstLinkpathDest: () => null }; + h.instance.getSourcePath = () => "Drawing.excalidraw.md"; + h.instance.ensureLinkItemsLoaded = () => { h.instance.linkItemsLoaded = true; }; + return { ...h, input, doc, result, provider, events, calls: () => calls, + marked: () => input.value.slice(0, input.selectionStart) + "|" + input.value.slice(input.selectionEnd), + offer() { h.instance.onInputChanged(); return h.instance.getSuggestions()[0]?.item; }, + }; +} + +test("ontology insertion preserves exact names, wrappers, closers, suffixes and caret", () => { + for (const [input, field, trigger, expected] of [ + [":::|", "friend", ":::", "friend::|"], + ["::p|", "parent", "::p", "parent::|"], + ["(:::|", "parent", ":::", "(parent:: |)"], + ["(::pPar|)", "Parent", "::p", "(Parent:: |)"], + ["[:::|", "friend", ":::", "[friend:: |]"], + ["[:::|]", "friend", ":::", "[friend:: |]"], + ["Before (:::|) after", "Parent With Space", ":::", "Before (Parent With Space:: |) after"], + ["Before (:::| trailing)", "PaRéNT", ":::", "Before (PaRéNT:: | trailing)"], + ["(:::| unrelated", "Parent", ":::", "(Parent:: |) unrelated"], + ["[:::| (unrelated)] suffix", "Friend", ":::", "[Friend:: | (unrelated)] suffix"], + ]) { + const h = ontologyFixture(input, field, trigger), item = h.offer(); + h.instance.onChooseItem(item); + assert.equal(h.marked(), expected, input); + assert.equal(h.doc.activeElement, h.input); + assert.deepEqual(h.events, ["input", "change"]); + assert.deepEqual(h.stack, [h.root]); + } +}); + +test("ontology completion continues into the existing wikilink mode and bracket-containing names", () => { + for (const wrapper of ["(", "["]) { + const h = ontologyFixture(wrapper + ":::|", "Parent"), item = h.offer(); + h.instance.onChooseItem(item); + for (let count = 0; count < 2; count++) h.instance.onBracketKeyDown({ key: "[", preventDefault() {} }); + assert.equal(h.instance.mode, "file"); + h.instance.onChooseItem({ path: "Note [draft]" }); + assert.equal(h.input.value, wrapper + "Parent:: [[Note [draft]]]" + (wrapper === "(" ? ")" : "]")); + assert.equal(h.input.selectionStart, h.input.value.length - 1); + } +}); + +test("a bracket in a queried filename cannot consume the square ontology wrapper", () => { + for (const [text, expected] of [ + ["[Parent:: [[Note [draft]|]", "[Parent:: [[Note [draft]]]]"], + ["[Parent:: [[Note [draft]|]]] suffix", "[Parent:: [[Note [draft]]]] suffix"], + ["(Parent:: [[Note [draft]|]]) suffix", "(Parent:: [[Note [draft]]]) suffix"], + ]) { + const h = ontologyFixture(":::|"), cursor = text.indexOf("|"), value = text.replace("|", ""); + h.input.value = value; h.input.setSelectionRange(cursor,cursor); + const active = h.instance.findActiveLink(value, cursor); + assert(active, text); + h.instance.activeOpen = active.open; h.instance.activeClose = active.close; + h.instance.insertLink("[[Note [draft]]]"); + assert.equal(h.input.value, expected); + } +}); + +test("wrapped bracket filenames retain real alias, heading, block, frame and clipped-frame parsing", () => { + const h=ontologyFixture(":::|"),note={basename:"Note [draft]",path:"Note [draft].md",extension:"md"},drawing={basename:"Drawing [draft]",path:"Drawing [draft].excalidraw.md",extension:"md"}; + h.instance.getSourcePath=()=>"Source.md"; + h.instance.app.metadataCache={getFirstLinkpathDest:path=>path===note.basename?note:path===drawing.basename?drawing:null}; + h.instance.plugin={isExcalidrawFile:file=>file===drawing}; + for(const [marked,mode,searchTerm,inAlias]of [ + ["[Parent:: [[Note [draft]§]]]","file","Note [draft]",false], + ["[Parent:: [[Note [draft]|alias§]]]","file","Note [draft]",true], + ["(Parent:: [[Note [draft]#Heading§]])","heading","Heading",false], + ["[Parent:: [[Note [draft]#^block-id§]]]","block","block-id",false], + ["[Parent:: [[Drawing [draft]#^frame=Frame§]]]","frame","Frame",false], + ["(Parent:: [[Drawing [draft]#^clippedframe=Frame§]])","clippedframe","Frame",false], + ]){ + const cursor=marked.indexOf("§"),value=marked.replace("§",""),active=h.instance.findActiveLink(value,cursor);assert(active,marked); + const context=h.instance.parseLinkContext(value,cursor,active.open,active.close); + assert.equal(context.mode,mode,marked);assert.equal(context.searchTerm,searchTerm,marked);assert.equal(context.inAlias,inAlias,marked); + } +}); + +test("provider/configuration/input changes retire captured ontology rows without mutation", () => { + for (const change of [ + h => { h.result.revision.configuration++; }, + h => { h.ownerWindow.kplexApi = { ...h.provider }; }, + h => { h.result.value.state = "disabled"; }, + h => { delete h.ownerWindow.kplexApi; }, + h => { h.provider.v1.completeOntology = () => { throw Error("retired"); }; }, + h => { h.provider.v1.capabilities = () => ({ ok: true, value: { operations: [] } }); }, + h => { h.input.value += "changed"; }, + h => { h.input.selectionStart--; }, + ]) { + const h = ontologyFixture("(:::|)", "Parent"), item = h.offer(); + change(h); const before = h.input.value; + h.instance.onChooseItem(item); + assert.equal(h.input.value, before); + assert.deepEqual(h.events, []); + assert.deepEqual(h.stack, [h.root]); + } + const h = ontologyFixture(":::|", "Friend"), item = h.offer(); + h.result.revision.semantic++; h.result.revision.source++; + h.instance.onChooseItem(item); + assert.equal(h.input.value, "Friend::", "Unrelated graph publication cannot stale configuration-only completion"); +}); + +test("missing or incompatible providers leave normal editing and existing suggestion precedence intact", () => { + const h = ontologyFixture(":::|"); + for (const provider of [undefined, {}, { version: 9, v1: h.provider.v1 }, { version: 1, v1: {} }]) { + h.ownerWindow.kplexApi = provider; h.instance.onInputChanged(); + assert.equal(h.instance.mode, null); assert.equal(h.instance.block, false); + } + h.ownerWindow.kplexApi = h.provider; + for (const value of ["[[Note]]", "[[Note#Heading]]", "[[Note#^block]]", "[[Note#^frame=Frame]]", "[[Note#^clippedframe=Frame]]", "[[Note|Alias]]"]) { + const before = h.calls(); h.input.value = value; h.input.setSelectionRange(value.length - 2, value.length - 2); + h.instance.parseLinkContext = () => ({ mode: "file", file: null, searchTerm: "", alias: null }); + h.instance.onInputChanged(); assert.equal(h.calls(), before); + } + h.input.value = "#tag"; h.input.setSelectionRange(4, 4); h.instance.getTagSuggestions = () => []; + const before = h.calls(); h.instance.onInputChanged(); assert.equal(h.instance.mode, "tag"); assert.equal(h.calls(), before); +}); + +test("composition and selections do not call the provider or submit link-editor Enter", () => { + const h = ontologyFixture(":::|"), before = h.calls(); + h.instance.composing = true; h.instance.onInputChanged(); assert.equal(h.calls(), before); + let stopped = false, prevented = false; + h.instance.onBracketKeyDown({ key: "Enter", isComposing: true, stopPropagation() { stopped = true; }, preventDefault() { prevented = true; } }); + assert(stopped); assert.equal(prevented, false); + h.instance.composing = false; h.input.selectionStart = 0; h.instance.onInputChanged(); assert.equal(h.calls(), before); +}); + +test("ontology annotations render as inert text and two inputs cannot choose each other's rows", () => { + const first = ontologyFixture(":::|", "Friend"), second = ontologyFixture(":::|", "Friend"), item = first.offer(); second.offer(); + second.instance.onChooseItem(item); assert.equal(second.input.value, ":::"); assert.equal(first.instance.block, true); + const rendered = []; + first.instance.renderSuggestion({ item }, { addClass() {}, createDiv(value) { rendered.push(value.text); } }); + assert.deepEqual(rendered, ["Friend", "↔ Partner", "Literal description"]); + first.instance.onChooseItem(item); assert.equal(first.input.value, "Friend::"); +}); diff --git a/scripts/testing/kplexOntology.source.test.mjs b/scripts/testing/kplexOntology.source.test.mjs new file mode 100644 index 00000000..5074f938 --- /dev/null +++ b/scripts/testing/kplexOntology.source.test.mjs @@ -0,0 +1,77 @@ +/** Whole production helpers: optional protocol refusal and HTML-only edits, without a matcher double. */ +import assert from "node:assert/strict"; +import test from "node:test"; +import {sourceHarness} from "./sourceHarness.mjs"; + +async function fixture(t) { + const prior=Object.getOwnPropertyDescriptor(globalThis,"window"),main={}; + globalThis.window=main; + const graph=sourceHarness(); + t.after(()=>{graph.close();if(prior)Object.defineProperty(globalThis,"window",prior);else Reflect.deleteProperty(globalThis,"window");}); + const provider=await graph.importModule("src/shared/Suggesters/kplexOntologyProvider.ts"); + const edits=await graph.importModule("src/shared/Suggesters/ontologyLinkCompletion.ts"); + let calls=0; + const result={ok:true,revision:{semantic:1,source:1,configuration:1},value:{state:"matched",context:{range:{start:1,end:4},trigger:":::",query:""},items:[{name:"Friend",partner:"Ally",description:"literal"}]}}; + const api={version:1,capabilities:()=>({ok:true,value:{operations:["completeOntology"]}}),completeOntology(request){calls++;assert.deepEqual(request,{text:"[:::]",cursor:4,limit:20});return result;}}; + const root={version:1,v1:api},owner={kplexApi:root}; + const input={value:"[:::]",selectionStart:4,selectionEnd:4,isConnected:true,ownerDocument:{defaultView:owner}}; + return {...provider,...edits,root,api,result,input,owner,main,calls:()=>calls}; +} + +test("optional completion reads only the public owning-window API and returns detached inert fields",async t=>{ + const h=await fixture(t),offer=h.readKplexOntologyCompletion(h.input); + assert.equal(h.calls(),1);assert.equal(offer.provider,h.root); + assert.deepEqual(offer.items,[{name:"Friend",partner:"Ally",description:"literal"}]); + h.result.value.items[0].name="Changed";assert.equal(offer.items[0].name,"Friend"); + delete h.owner.kplexApi;h.main.kplexApi=h.root;assert(h.readKplexOntologyCompletion(h.input)); +}); + +test("missing, incompatible and throwing optional providers never escape into editing",async t=>{ + const h=await fixture(t); + for(const root of [undefined,{},[],{version:2,v1:h.api},{version:1,v1:{...h.api,version:2}},{version:1,v1:{version:1}},{version:1,v1:{...h.api,capabilities:()=>{throw Error("gone");}}},{version:1,v1:{...h.api,completeOntology:()=>{throw Error("gone");}}}]){ + h.owner.kplexApi=root;assert.equal(h.readKplexOntologyCompletion(h.input),null); + } +}); + +test("bad ranges, oversized results and disabled/unavailable envelopes cannot become offers",async t=>{ + const h=await fixture(t),baseline=structuredClone(h.result); + const changes=[ + result=>{result.ok=false;},result=>{result.revision.configuration=NaN;},result=>{result.value.state="disabled";}, + result=>{result.value.context.range.start=-1;},result=>{result.value.context.range.end=3;}, + result=>{result.value.context.trigger="@@";},result=>{result.value.context=null;}, + result=>{result.value.items=Array.from({length:21},()=>({name:"x"}));}, + result=>{result.value.items[0].name="";},result=>{result.value.items[0].partner={};}, + result=>{result.value.items[0].description="x".repeat(1048577);}, + ]; + for(const change of changes){Object.assign(h.result,structuredClone(baseline));change(h.result);assert.equal(h.readKplexOntologyCompletion(h.input),null);} +}); + +test("input bounds and noncollapsed or detached selections refuse before the optional call",async t=>{ + const h=await fixture(t); + for(const change of [()=>{h.input.selectionEnd=3;},()=>{h.input.isConnected=false;},()=>{h.input.value="x".repeat(65537);}]){ + change();assert.equal(h.readKplexOntologyCompletion(h.input),null);h.input.selectionEnd=4;h.input.isConnected=true;h.input.value="[:::]"; + } + for(const limit of [0,101,1.5])assert.equal(h.readKplexOntologyCompletion(h.input,limit),null); + assert.equal(h.calls(),0); +}); + +test("selection fences provider, method, configuration and input while ignoring unrelated graph revisions",async t=>{ + const h=await fixture(t),offer=h.readKplexOntologyCompletion(h.input); + h.result.revision.semantic++;h.result.revision.source++;assert(h.isKplexOntologyOfferCurrent(h.input,offer,"Friend")); + h.result.revision.configuration++;assert.equal(h.isKplexOntologyOfferCurrent(h.input,offer,"Friend"),false); + h.result.revision.configuration--;h.owner.kplexApi={...h.root};assert.equal(h.isKplexOntologyOfferCurrent(h.input,offer,"Friend"),false); + h.owner.kplexApi=h.root;const method=h.api.completeOntology;h.api.completeOntology=function(request){return method.call(this,request);};assert.equal(h.isKplexOntologyOfferCurrent(h.input,offer,"Friend"),false); + h.api.completeOntology=method;h.input.selectionStart=3;assert.equal(h.isKplexOntologyOfferCurrent(h.input,offer,"Friend"),false); +}); + +test("wrapper edits preserve suffixes and balanced closers with exact UTF-16 carets",async t=>{ + const h=await fixture(t); + for(const [text,start,end,name,expected,caret]of [ + ["::: tail",0,3,"friend","friend:: tail",8], + ["😀 (::: suffix",4,7,"PaRéNT","😀 (PaRéNT:: ) suffix",13], + ["[::: [kept]] suffix",1,4,"Friend","[Friend:: [kept]] suffix",10], + ["(::: (nested)) suffix",1,4,"Parent","(Parent:: (nested)) suffix",10], + ]){const edit=h.ontologyLinkEdit(text,{start,end},name);assert.equal(edit.value,expected);assert.equal(edit.caret,caret);} + for(const range of [{start:-1,end:3},{start:0,end:99},{start:2,end:1},{start:0.1,end:3}])assert.equal(h.ontologyLinkEdit(":::x",range,"Field"),null); + assert.equal(h.ontologyLinkEdit(":::x",{start:0,end:3},""),null); +}); diff --git a/scripts/testing/localVault.mjs b/scripts/testing/localVault.mjs index e84e7379..ae7b0212 100644 --- a/scripts/testing/localVault.mjs +++ b/scripts/testing/localVault.mjs @@ -10,6 +10,7 @@ import { } from "node:fs"; import { dirname, join, resolve } from "node:path"; import { fileHash, ownedPath, validateArtifactManifest } from "./contracts.mjs"; +import { nativeRepositoryRoot } from "./nativeRepositoryRoot.mjs"; import { provisionVault, validateOwnedVault, @@ -24,8 +25,9 @@ import { } from "./host/debuggerSession.mjs"; export const LOCAL_VAULT_NAME = "excalidraw-auto-test"; +const KPLEX_FIXTURE = "tests/fixtures/kplex-ontology/data.json"; export function localVaultTarget(projectRoot) { - const automationRoot = resolve(projectRoot, ".test-work/vaults"); + const automationRoot = resolve(nativeRepositoryRoot(projectRoot), ".test-work/vaults"); const vaultPath = join(automationRoot, LOCAL_VAULT_NAME); return { vaultName: LOCAL_VAULT_NAME, @@ -171,6 +173,7 @@ export function installLocalVault({ for (const [kind, id] of [ ["plugin", "obsidian-excalidraw-plugin"], ["extras", "excalidraw-extras"], + ...(combination.manifests.kplex ? [["kplex", "k-plex"]] : []), ]) { if (!combination.manifests[kind]) { assert.equal(kind, "extras", "Plugin producer is required"); @@ -212,6 +215,11 @@ export function installLocalVault({ ); assert.equal(installed.id, id); const data = join(target.configDir, "plugins", id, "data.json"); + if (kind === "kplex") { + const fixture = ownedPath(projectRoot, KPLEX_FIXTURE); + copyFileSync(fixture, data); + assert.equal(fileHash(data), fileHash(fixture), "Installed K-Plex fixture changed"); + } assert.ok(existsSync(data), "Missing declared plugin settings: " + id); installations[kind] = { status: "installed", @@ -249,6 +257,15 @@ export function installLocalVault({ } /** The caller holds the shared application-session lock throughout preparation and scenarios. */ +/** Await Obsidian's pending native layout writer before copying the immutable working seed. + * Closing leaves and unloading companions schedule a debounced write; it must not race the + * seed's workspace hash check. The public Debouncer.run() drains and awaits that exact write. */ +export async function flushNativeWorkspaceSave() { + if(typeof app.workspace.requestSaveLayout?.run!=="function")throw Error("Native workspace-save flush unavailable"); + await app.workspace.requestSaveLayout.run(); + return {workspaceSaveCompleted:true}; +} + export async function prepareLocalVault({ projectRoot, combination, @@ -326,7 +343,7 @@ export async function prepareLocalVault({ return { quiescent: true, mobile: app.isMobile === true,closedPopouts:popouts.length }; }, }); - for (const id of ["obsidian-excalidraw-plugin", "excalidraw-extras"]) { + for (const id of ["obsidian-excalidraw-plugin", "excalidraw-extras", "k-plex"]) { const loaded = parseCLIJSON( cli( "eval", @@ -338,6 +355,7 @@ export async function prepareLocalVault({ if (loaded) cli("plugin:disable", "id=" + id); } } + if(opened)await runInAppTask({cli,execute:flushNativeWorkspaceSave}); const evidence = installLocalVault({ projectRoot, combination, target }); if (!opened) return { @@ -353,7 +371,7 @@ export async function prepareLocalVault({ execute: applyDeclaredHostConfiguration, args: declaredHostConfiguration(projectRoot), }); - for (const id of ["excalidraw-extras", "obsidian-excalidraw-plugin"]) { + for (const id of ["excalidraw-extras", "k-plex", "obsidian-excalidraw-plugin"]) { if (!Object.values(evidence.installations).some((i) => i.id === id)) continue; await discoverStagedPlugin(cli, id); @@ -410,6 +428,24 @@ export async function prepareLocalVault({ [true, true, true], "Workspace Extras services must be active automatically", ); + if (evidence.installations.kplex?.status === "installed") { + await runInAppTask({cli, args: [JSON.parse(readFileSync(ownedPath(projectRoot, KPLEX_FIXTURE), "utf8"))], + execute: async (c, fixture) => { + await c.waitFor(() => !!app.plugins.plugins["k-plex"] && window.kplexApi?.version === 1, "K-Plex public API after settings load"); + const plugin = app.plugins.plugins["k-plex"], capabilities = window.kplexApi.v1.capabilities(); + if (!capabilities.ok || !capabilities.value.operations.includes("completeOntology")) throw Error("Selected K-Plex build lacks ontology completion"); + // The deliberately small fixture exercises K-Plex's real upgrade path. Acknowledge + // only its owned migration dialog through the canonical settings action before UI input. + const migrationAcknowledged = !!plugin.appearanceMigrationDialog; + if (migrationAcknowledged) { + plugin.appearanceMigrationDialog.close(); + await c.waitFor(() => !plugin.appearanceMigrationDialog && plugin.settings.appearanceThemes?.migrationNotice === false, "K-Plex migration acknowledgment"); + } + for (const [key, value] of Object.entries(fixture)) if (JSON.stringify(plugin.settings[key]) !== JSON.stringify(value)) + throw Error("K-Plex declared setting not applied: " + key); + return {enabled: true, completion: true, migrationAcknowledged}; + }}); + } return { ...evidence, hostConfiguration, ready: true }; } finally { if (session) { @@ -453,6 +489,9 @@ export async function restoreLocalVaultBaseline({ projectRoot, cli }) { ); const corpus = verifySeed(), target = localVaultTarget(projectRoot); + const installed = JSON.parse(readFileSync(join(target.vaultPath, ".excalidraw-installed-build.json"), "utf8")); + const kplex = installed.installations.kplex?.status === "installed" + ? JSON.parse(readFileSync(ownedPath(projectRoot, KPLEX_FIXTURE), "utf8")) : null; const content = corpus.manifest.fixtures.filter( (f) => !f.path.startsWith(".obsidian/"), ); @@ -468,8 +507,8 @@ export async function restoreLocalVaultBaseline({ projectRoot, cli }) { })); const result = await runInAppTask({ cli, - args: [plugin, extras, changed], - execute: async (_c, plugin, extras, changed) => { + args: [plugin, extras, changed, kplex], + execute: async (_c, plugin, extras, changed, kplex) => { const pending = Object.keys(globalThis).filter((k) => k.startsWith("__excalidrawTestTask_"), ); @@ -486,6 +525,15 @@ export async function restoreLocalVaultBaseline({ projectRoot, cli }) { Object.assign(e.settings, extras); await e.saveSettings(); } + if (kplex) { + const owner = app.plugins.plugins["k-plex"]; + if (!owner || !window.kplexApi) throw Error("K-Plex was not restored after lifecycle testing"); + Object.assign(owner.settings, kplex); + await owner.saveSettings(false, false); + const saved = await owner.loadData(); + for (const [key, value] of Object.entries(kplex)) if (JSON.stringify(saved[key]) !== JSON.stringify(value)) + throw Error("K-Plex baseline not persisted: " + key); + } app.changeTheme("moonstone"); for (const [key, value] of Object.entries(plugin)) if (JSON.stringify(p.settings[key]) !== JSON.stringify(value)) @@ -526,6 +574,7 @@ export async function restoreLocalVaultBaseline({ projectRoot, cli }) { restored: true, pluginEnabled: true, extrasEnabled: !!e, + kplexEnabled: !!kplex, theme: app.vault.getConfig("theme"), restoredFixturePaths: changed.map((f) => f.path), }; diff --git a/scripts/testing/localVault.test.mjs b/scripts/testing/localVault.test.mjs index 10507b01..36375e11 100644 --- a/scripts/testing/localVault.test.mjs +++ b/scripts/testing/localVault.test.mjs @@ -19,8 +19,18 @@ import { registeredLocalVault, configureLocalVaultEnvironment, applyDeclaredHostConfiguration, + flushNativeWorkspaceSave, } from "./localVault.mjs"; +test("live preparation awaits the actual pending workspace write before seed copying", async () => { + let release,calls=0,completed=false; + const pending=new Promise(resolve=>{release=resolve;}); + const result=runInNewContext("("+flushNativeWorkspaceSave.toString()+")()",{app:{workspace:{requestSaveLayout:{run(){calls++;return pending;}}}}}); + void result.then(()=>{completed=true;});await Promise.resolve();assert.equal(calls,1);assert.equal(completed,false); + release();assert.equal((await result).workspaceSaveCompleted,true); + await assert.rejects(runInNewContext("("+flushNativeWorkspaceSave.toString()+")()",{app:{workspace:{requestSaveLayout(){}}}}),/flush unavailable/); +}); + test("live preparation restores core activation and accepts Obsidian's persisted boolean map", async () => { const configuration = { livePreview: true, promptDelete: false, zero: 0 }; const live = { livePreview: false, promptDelete: true, zero: 10 }; @@ -91,7 +101,7 @@ test("live preparation restores core activation and accepts Obsidian's persisted } }); -function fixture(t, extras = true) { +function fixture(t, extras = true, kplex = false) { const projectRoot = mkdtempSync(join(tmpdir(), "excalidraw-local-vault-")); t.after(() => rmSync(projectRoot, { recursive: true, force: true })); const output = join(projectRoot, "frozen"), @@ -99,6 +109,7 @@ function fixture(t, extras = true) { for (const [kind, id] of [ ["plugin", "obsidian-excalidraw-plugin"], ...(extras ? [["extras", "excalidraw-extras"]] : []), + ...(kplex ? [["kplex", "k-plex"]] : []), ]) { const root = join(output, kind); mkdirSync(join(root, "dist"), { recursive: true }); @@ -130,6 +141,11 @@ function fixture(t, extras = true) { })), }); } + if (kplex) { + const directory = join(projectRoot, "tests/fixtures/kplex-ontology"); + mkdirSync(directory, {recursive: true}); + writeFileSync(join(directory, "data.json"), readFileSync(new URL("../../tests/fixtures/kplex-ontology/data.json", import.meta.url))); + } return { projectRoot, combination: { output, manifests } }; } @@ -196,6 +212,21 @@ test("missing Extras is explicit and cannot masquerade as installed coverage", ( ); }); +test("the explicit K-Plex fixture stages only the selected frozen build and declared settings", (t) => { + const result = installLocalVault(fixture(t, true, true)); + const installation = result.installations.kplex; + assert.equal(installation.status, "installed"); + assert.equal(installation.id, "k-plex"); + const directory = join(result.target.configDir, "plugins/k-plex"); + for (const name of ["main.js", "manifest.json", "styles.css"]) assert.equal(fileHash(join(directory, name)), installation.hashes[name]); + const settings = JSON.parse(readFileSync(join(directory, "data.json"), "utf8")); + assert.equal(settings.indexingModeDesktop, "on-demand"); + assert.equal(settings.boldFields, true); + assert.equal(settings.allowOntologySuggester, true); + assert.deepEqual(settings.__ontologyCompletionUnknown, {preserve: true}); + assert(JSON.parse(readFileSync(join(result.target.configDir, "community-plugins.json"), "utf8")).includes("k-plex")); +}); + test("corrupt producer bytes and redirected destinations cannot become a prepared installation", (t) => { const input = fixture(t); installLocalVault(input); diff --git a/scripts/testing/nativeRepositoryRoot.mjs b/scripts/testing/nativeRepositoryRoot.mjs new file mode 100644 index 00000000..5807c778 --- /dev/null +++ b/scripts/testing/nativeRepositoryRoot.mjs @@ -0,0 +1,34 @@ +/** Resolve one Git repository's persistent native-test owner across isolated source worktrees. + * Source/seed/build provenance remains worktree-local; only the existing marker-owned vault is + * shared. No caller-supplied vault path, redirected metadata or unrelated repository is accepted. */ +import assert from 'node:assert/strict'; +import {spawnSync} from 'node:child_process'; +import {existsSync,lstatSync,readFileSync,realpathSync} from 'node:fs'; +import {dirname,join,relative,resolve,isAbsolute,sep} from 'node:path'; +import {ownedPath} from './contracts.mjs'; + +/** Read Git's own canonical metadata location without a shell or mutation. */ +function metadataPath(root,args){ + const result=spawnSync('git',args,{cwd:root,encoding:'utf8',windowsHide:true,timeout:10000}); + assert.ok(!result.error&&result.status===0,'Cannot verify native worktree ownership: '+(result.error?.message||result.stderr)); + return realpathSync(result.stdout.trim()); +} + +/** Ordinary repositories and synthetic fixtures own their local vault. A linked worktree may + * share only its primary checkout's vault, after both common metadata and the reverse worktree + * pointer agree. Existing canonical path/marker guards continue to validate that destination. */ +export function nativeRepositoryRoot(projectRoot){ + const root=resolve(projectRoot),dotGit=join(root,'.git'); + if(!existsSync(dotGit)||lstatSync(dotGit).isDirectory())return root; + ownedPath(root,'.git'); + assert.ok(lstatSync(dotGit).isFile(),'Native source metadata must be a regular Git worktree file'); + const common=metadataPath(root,['rev-parse','--path-format=absolute','--git-common-dir']); + const gitDir=metadataPath(root,['rev-parse','--absolute-git-dir']); + const primary=dirname(common),worktrees=join(common,'worktrees'),entry=relative(worktrees,gitDir); + assert.ok(entry&&entry!=='..'&&!entry.startsWith('..'+sep)&&!isAbsolute(entry),'Native source is not a linked repository worktree'); + assert.equal(common,realpathSync(join(primary,'.git')),'Native common metadata must belong to its primary repository'); + ownedPath(primary,'.git/config'); + const backPointer=readFileSync(ownedPath(common,'worktrees/'+entry.split(sep).join('/')+'/gitdir'),'utf8').trim(); + assert.equal(realpathSync(resolve(gitDir,backPointer)),realpathSync(dotGit),'Native worktree reverse ownership differs'); + return primary; +} diff --git a/scripts/testing/nativeRepositoryRoot.test.mjs b/scripts/testing/nativeRepositoryRoot.test.mjs new file mode 100644 index 00000000..e1b6b835 --- /dev/null +++ b/scripts/testing/nativeRepositoryRoot.test.mjs @@ -0,0 +1,46 @@ +/** Worktree native targets retain the existing repository vault and all canonical path guards. */ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import {spawnSync} from 'node:child_process'; +import {mkdtempSync,mkdirSync,readFileSync,writeFileSync,rmSync,symlinkSync} from 'node:fs'; +import {join,resolve} from 'node:path'; +import {tmpdir} from 'node:os'; +import {nativeRepositoryRoot} from './nativeRepositoryRoot.mjs'; +import {localVaultTarget,configureLocalVaultEnvironment} from './localVault.mjs'; + +/** Use real Git metadata so ownership is established by both ends of an actual linked worktree. */ +function fixture(t){ + const root=mkdtempSync(join(tmpdir(),'excalidraw-native-owner-')),primary=join(root,'primary'),worktree=join(root,'source');mkdirSync(primary); + t.after(()=>rmSync(root,{recursive:true,force:true})); + const git=(cwd,...args)=>{const r=spawnSync('git',args,{cwd,encoding:'utf8',windowsHide:true});assert.equal(r.status,0,r.stderr);}; + git(primary,'init');writeFileSync(join(primary,'fixture.txt'),'owned fixture');git(primary,'add','fixture.txt'); + git(primary,'-c','user.name=Native test','-c','user.email=native@example.invalid','commit','-m','fixture'); + git(primary,'worktree','add','--detach',worktree,'HEAD');return{root,primary,worktree,git}; +} + +test('linked source worktree shares only its verified primary repository native target',t=>{ + const f=fixture(t);assert.equal(nativeRepositoryRoot(f.worktree),f.primary); + assert.deepEqual(localVaultTarget(f.worktree),localVaultTarget(f.primary)); + const env={};configureLocalVaultEnvironment(f.worktree,env); + assert.equal(env.EXCALIDRAW_TEST_VAULT_PATH,join(f.primary,'.test-work/vaults/excalidraw-auto-test')); + const wrong={...env,EXCALIDRAW_TEST_VAULT_PATH:join(f.root,'personal')}; + assert.throws(()=>configureLocalVaultEnvironment(f.worktree,wrong),/repository-local/); +}); + +test('another repository cannot substitute worktree metadata or redirect its ownership pointer',t=>{ + const f=fixture(t),other=join(f.root,'other');mkdirSync(other); + writeFileSync(join(other,'.git'),readFileSync(join(f.worktree,'.git'),'utf8')); + assert.throws(()=>nativeRepositoryRoot(other),/reverse ownership differs/); +}); + +test('a redirected source metadata file is rejected before target selection',t=>{ + const f=fixture(t),redirect=join(f.root,'redirect');mkdirSync(redirect); + symlinkSync(f.worktree,join(redirect,'source'),process.platform==='win32'?'junction':'dir'); + assert.throws(()=>nativeRepositoryRoot(join(redirect,'source')),/Redirected/); +}); + +test('nonrepository synthetic fixtures retain the ordinary fixed target',t=>{ + const root=mkdtempSync(join(tmpdir(),'excalidraw-native-synthetic-'));t.after(()=>rmSync(root,{recursive:true,force:true})); + assert.equal(nativeRepositoryRoot(root),resolve(root)); + assert.equal(localVaultTarget(root).vaultPath,join(root,'.test-work/vaults/excalidraw-auto-test')); +}); diff --git a/scripts/testing/produceArtifacts.mjs b/scripts/testing/produceArtifacts.mjs index ce126459..ec3a3568 100644 --- a/scripts/testing/produceArtifacts.mjs +++ b/scripts/testing/produceArtifacts.mjs @@ -9,7 +9,7 @@ import { packageManagerInvocation } from "./host/processTools.mjs"; export function producerFiles(root, kind) { const plugin = ["main.js", "manifest.json", "styles.css"].map((file, i) => ({ role: ["main", "manifest", "styles"][i], relativePath: `dist/${file}` })); - if (kind === "plugin") return plugin; + if (kind === "plugin" || kind === "kplex") return plugin; if (kind === "extras") return [...plugin, ...declarations("api", "api/api/index.d.ts")]; if (kind === "fork") return [ ...["production.min.js", "production.min.css", "development.js", "development.css"].map((file, i) => ({ role: ["production-js", "production-css", "development-js", "development-css"][i], relativePath: `packages/excalidraw/dist/obsidian/excalidraw.${file}` })), @@ -25,14 +25,14 @@ export function producerFiles(root, kind) { } export function produceArtifacts({ root, kind, snapshotRoot, run = runBuild }) { - assert.ok(["plugin", "fork", "extras"].includes(kind), "Unknown producer kind"); + assert.ok(["plugin", "fork", "extras", "kplex"].includes(kind), "Unknown producer kind"); assert.ok(!existsSync(snapshotRoot), "Snapshot already exists"); const before = sourceIdentity(root); const steps = kind === "fork" ? ["build:esm", "build:obsidian"].map(script => ({ manager: "yarn", args: [script], cwd: join(root, "packages/excalidraw") })) : [{ manager: "npm", args: ["run", "build"], cwd: root }, ...(kind === "extras" ? [{ manager: "npm", args: ["run", "build:api"], cwd: root }] : [])]; for (const step of steps) run(step); assert.deepEqual(sourceIdentity(root), before, "Producer source changed while building; discard output and rebuild"); - const repository = `zsviczian/${kind === "fork" ? "excalidraw" : kind === "extras" ? "obsidian-excalidraw-extras" : "obsidian-excalidraw-plugin"}`; + const repository = `zsviczian/${kind === "fork" ? "excalidraw" : kind === "extras" ? "obsidian-excalidraw-extras" : kind === "kplex" ? "kplex" : "obsidian-excalidraw-plugin"}`; const manifest = createArtifactManifest({ root, kind, repository, identity: before, buildCommand: steps.map(step => `${step.manager} ${step.args.join(" ")}`).join(" && "), artifacts: producerFiles(root, kind) }); freezeArtifacts(manifest, root, snapshotRoot); writeFileSync(join(snapshotRoot, "producer.json"), JSON.stringify({ ...manifest, sourceRoot: resolve(root) }, null, 2) + "\n"); @@ -46,7 +46,7 @@ function runBuild({ manager, args, cwd }) { } if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { - const args = Object.fromEntries(process.argv.slice(2).map(arg => { const match = arg.match(/^--(kind|root|snapshot)=(.+)$/); if (!match) throw Error("Use --kind=plugin|fork|extras --root=PATH --snapshot=NEW_PATH"); return match.slice(1); })); + const args = Object.fromEntries(process.argv.slice(2).map(arg => { const match = arg.match(/^--(kind|root|snapshot)=(.+)$/); if (!match) throw Error("Use --kind=plugin|fork|extras|kplex --root=PATH --snapshot=NEW_PATH"); return match.slice(1); })); if (!args.kind || !args.root || !args.snapshot) throw Error("Producer kind, root and new snapshot are required"); const manifest = produceArtifacts({ kind: args.kind, root: resolve(args.root), snapshotRoot: resolve(args.snapshot) }); process.stdout.write(`${manifest.kind}: ${manifest.artifacts.length} frozen artifacts, commit ${manifest.commit}, dirty=${manifest.dirty}\n`); diff --git a/scripts/testing/regression.mjs b/scripts/testing/regression.mjs index b90df4cc..d5b08b5b 100644 --- a/scripts/testing/regression.mjs +++ b/scripts/testing/regression.mjs @@ -21,16 +21,18 @@ import { coverageChanges } from "./coverageChanges.mjs"; import { workflowBundleCaseIds } from "./host/workflowBundle.mjs"; import { textSaveShortcutCaseIds } from "./host/textSaveShortcut.mjs"; import { codeCardCaseIds } from "./host/codeCards.mjs"; +import { kplexOntologyCaseIds, kplexOntologyDeviceCaseIds } from "./host/kplexOntology.mjs"; export const requiredDeviceCases = [ ...deviceProfiles(), ...breakpointProfiles(), -].map((profile) => "native:device:" + profile.id); +].map((profile) => "native:device:" + profile.id).concat(kplexOntologyDeviceCaseIds); export const requiredNativeCases = [ ...workflowBundleCaseIds, ...textSaveShortcutCaseIds, ...codeCardCaseIds, + ...kplexOntologyCaseIds, ...behavioralCases().map((row) => row.testId), ...["image-url", "image-import"].flatMap((action) => ["uri", "linked-image", "extensionless", "blob"].map( diff --git a/src/core/main.ts b/src/core/main.ts index 95ebbfde..b8e645d9 100644 --- a/src/core/main.ts +++ b/src/core/main.ts @@ -1496,7 +1496,7 @@ export default class ExcalidrawPlugin extends Plugin { } /** - * Attaches an inline link suggester to the specified input element. + * Attaches one shared link/tag/optional public K-Plex ontology suggester to the input element. * @param inputEl The text input element to attach the suggester to. * @param widthWrapper Optional HTML element to wrap the width of suggester element. * @param containerEl Optional container element used as collision boundary. diff --git a/src/shared/Dialogs/Messages.ts b/src/shared/Dialogs/Messages.ts index a77f3f28..12bdfd07 100644 --- a/src/shared/Dialogs/Messages.ts +++ b/src/shared/Dialogs/Messages.ts @@ -19,6 +19,7 @@ I build this plugin as a labor of love. Curious about the philosophy behind it? `, "2.29.2": ` ## New and improved +- With a compatible K-Plex enabled, complete its ontology fields in link inputs using your configured triggers, then continue with \`[[note]]\` completion inside parentheses or square brackets. - Paste code blocks as interactive embeddables or editable Markdown images, and optionally remember your choice. Code images adapt to their content up to 800 px wide and wrap long lines without scrollbars. ## Fixed diff --git a/src/shared/Dialogs/SuggesterInfo.ts b/src/shared/Dialogs/SuggesterInfo.ts index ca832c3c..ff783936 100644 --- a/src/shared/Dialogs/SuggesterInfo.ts +++ b/src/shared/Dialogs/SuggesterInfo.ts @@ -1147,7 +1147,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [ { field: "attachInlineLinkSuggester", code: "attachInlineLinkSuggester(inputEl: HTMLInputElement, widthWrapper?: HTMLElement): KeyBlocker;", - desc: "Attaches an inline [[link]] suggester to an input. Optionally align width to a wrapper element. Returns a KeyBlocker so host scripts can skip their own keydown handlers while the suggester is active via isBlockingKeys(); call close() on the returned suggester to detach.", + desc: "Attaches the shared inline link/tag suggester to an input, including optional ontology completion from a compatible enabled K-Plex. Ontology selection keeps exact field spelling and surrounding parentheses/square brackets, with the caret ready for [[note]] completion. Optionally align width to a wrapper element. Returns a KeyBlocker so host scripts can skip their own keydown handlers while the suggester is active via isBlockingKeys(); call close() on the returned suggester to detach.", after: "", }, { diff --git a/src/shared/ExcalidrawAutomate.ts b/src/shared/ExcalidrawAutomate.ts index 868c17e1..3c5011bf 100644 --- a/src/shared/ExcalidrawAutomate.ts +++ b/src/shared/ExcalidrawAutomate.ts @@ -1104,9 +1104,9 @@ export class ExcalidrawAutomate { } /** - * Attaches an inline link suggester to the provided input element. The suggester reacts to - * "[[" typing, offers vault link choices (including aliases and unresolved links), and inserts - * the selected link using relative linktext when the active Excalidraw view is known. + * Attaches one popup for [[links]], tags and compatible K-Plex public ontology completion. + * Vault choices include aliases/unresolved links and use relative linktext when the target view is known. + * Ontology fields preserve exact spelling/wrappers and leave the caret ready for [[note]] completion. * @param {HTMLInputElement} inputEl - The input element to enhance. * @param {HTMLElement} [widthWrapper] - Optional element to determine suggester width. * @returns {KeyBlocker} The suggester instance; call close() to detach; call .isBlockingKeys() to check if suggester dropdown is open. diff --git a/src/shared/Suggesters/InlineLinkSuggester.ts b/src/shared/Suggesters/InlineLinkSuggester.ts index 2ed7554c..ac3b0f1c 100644 --- a/src/shared/Suggesters/InlineLinkSuggester.ts +++ b/src/shared/Suggesters/InlineLinkSuggester.ts @@ -16,6 +16,8 @@ import { t } from "src/lang/helpers"; import { nanoid } from "src/constants/constants"; import { getEA } from "src/core"; import { setStyle } from "src/utils/styleUtils"; +import { readKplexOntologyCompletion, isKplexOntologyOfferCurrent, type OntologyCompletionOffer, type OntologyFieldSuggestion } from "./kplexOntologyProvider"; +import { ontologyLinkEdit } from "./ontologyLinkCompletion"; type HeadingSuggestion = { kind: "heading"; @@ -53,10 +55,14 @@ type InlineSuggestion = | HeadingSuggestion | ParagraphSuggestion | TagSuggestion - | FrameSuggestion; + | FrameSuggestion + | OntologySuggestion; + +type OntologySuggestion = OntologyFieldSuggestion & {kind: "ontology"; offer: OntologyCompletionOffer}; /** - * Inline link suggester that attaches to a specific input element. + * One input-owned popup for links, metadata, tags and optional public K-Plex ontology fields. + * The provider owns matching; this class owns editing, keyboard scope and lookup generations. */ export class InlineLinkSuggester extends SuggestionModal @@ -83,6 +89,7 @@ export class InlineLinkSuggester | "frame" | "clippedframe" | "tag" + | "ontology" | null = null; private headingItems: HeadingSuggestion[] = []; private paragraphItems: ParagraphSuggestion[] = []; @@ -90,7 +97,13 @@ export class InlineLinkSuggester private tagItems: TagSuggestion[] = []; private linkItemsLoaded = false; private suggestionGeneration = 0; + private ontologyOffer: OntologyCompletionOffer | null = null; + private ontologyItems: OntologySuggestion[] = []; + private composing = false; + private readonly handleCompositionStart: () => void; + private readonly handleCompositionEnd: () => void; + /** Attach to the input's event lifetime; closing a dropdown keeps a connected input reusable. */ constructor( app: App, plugin: ExcalidrawPlugin, @@ -114,6 +127,10 @@ export class InlineLinkSuggester this.emptyStateText = "No match"; this.syncWidth(); this.inputEl.addEventListener("keydown", this.handleBracketKeyDown); + this.handleCompositionStart = () => { this.composing = true; this.resetSuggestions(); }; + this.handleCompositionEnd = () => { this.composing = false; this.onInputChanged(); }; + this.inputEl.addEventListener("compositionstart", this.handleCompositionStart); + this.inputEl.addEventListener("compositionend", this.handleCompositionEnd); } public isBlockingKeys() { @@ -121,6 +138,11 @@ export class InlineLinkSuggester } private onBracketKeyDown(event: KeyboardEvent) { + if (event.isComposing || this.composing) { + // Leave native IME defaults intact while keeping Enter/Escape out of the link editor. + event.stopPropagation(); + return; + } if ( event.key !== "[" || event.metaKey || @@ -185,7 +207,7 @@ export class InlineLinkSuggester const anchorRect = hostRect ?? this.inputEl.getBoundingClientRect(); let availableWidth = this.collisionBoundary ? this.collisionBoundary.innerWidth - 16 //SuggestionModal padding - : Math.max(0, window.innerWidth - anchorRect.left - 16); + : Math.max(0, (this.inputEl.ownerDocument.defaultView?.innerWidth ?? window.innerWidth) - anchorRect.left - 16); if (!this.hasCustomWidthHost) { availableWidth = @@ -229,6 +251,12 @@ export class InlineLinkSuggester onInputChanged(): void { const generation = ++this.suggestionGeneration; + this.ontologyOffer = null; + this.ontologyItems = []; + if (this.composing) { + this.resetSuggestions(); + return; + } const inputStr = this.modifyInput(this.inputEl.value); this.caretPos = this.inputEl.selectionStart ?? inputStr.length; @@ -293,6 +321,21 @@ export class InlineLinkSuggester const activeTag = this.findActiveTag(inputStr, this.caretPos); if (!activeTag) { + const offer = readKplexOntologyCompletion(this.inputEl, this.limit); + if (offer && offer.items.length) { + this.activeOpen = -1; + this.activeClose = -1; + this.activeTagStart = -1; + this.activeTagEnd = -1; + this.activeAlias = null; + this.activeFile = null; + this.mode = "ontology"; + this.ontologyOffer = offer; + this.ontologyItems = offer.items.map(field => ({...field, kind: "ontology", offer})); + this.block = true; + super.onInputChanged(); + return; + } this.resetSuggestions(); return; } @@ -339,6 +382,10 @@ export class InlineLinkSuggester } getSuggestions(): FuzzyMatch[] { + if (this.mode === "ontology") { + // K-Plex already owns inverse-aware filtering and ordering; never rank the rows again. + return this.ontologyItems.map>(item => ({item, match: {score: 0, matches: []}})); + } if (this.mode === "tag") { return fuzzyMatchTextItems( this.activeSearchTerm ?? "", @@ -395,6 +442,7 @@ export class InlineLinkSuggester } getItemText(item: InlineSuggestion): string { + if (this.isOntology(item)) return item.name; if (this.isHeading(item)) { return item.heading; } @@ -415,6 +463,11 @@ export class InlineLinkSuggester return; } + if (this.isOntology(item)) { + this.insertOntology(item); + return; + } + if (this.isTag(item)) { this.insertTag(item.tag); return; @@ -487,6 +540,14 @@ export class InlineLinkSuggester renderSuggestion(result: FuzzyMatch, itemEl: HTMLElement) { const { item } = result || {}; + if (this.isOntology(item)) { + itemEl.addClass("excalidraw-ontology-suggestion"); + itemEl.createDiv({cls: "suggestion-title", text: item.name}); + if (item.partner) itemEl.createDiv({cls: "suggestion-note", text: `↔ ${item.partner}`}); + if (item.description) itemEl.createDiv({cls: "suggestion-note", text: item.description}); + return; + } + if (this.isTag(item)) { const tagItem = item; itemEl.createDiv({ text: tagItem.tag }); @@ -581,7 +642,7 @@ export class InlineLinkSuggester } const nextOpen = this.inputEl.value.indexOf("[[", start + 2); - const fallbackClose = this.inputEl.value.indexOf("]]", start + 2); + const fallbackClose = this.findLinkClose(this.inputEl.value, start); const closeBelongsToLink = this.activeClose >= 0 ? true @@ -624,6 +685,47 @@ export class InlineLinkSuggester this.close(); } + /** Distinguish provider fields from file/tag/metadata options without interpreting their names. */ + private isOntology(item: InlineSuggestion | undefined): item is OntologySuggestion { + return Boolean(item && "kind" in item && item.kind === "ontology"); + } + + /** Validate the offered provider/configuration before applying one exact range through the + * host-observed input path. Native insertText preserves the browser input undo group; older + * hosts retain the existing value/input-event fallback. This never submits the element link. */ + private insertOntology(item: OntologySuggestion): void { + const offer = item.offer, input = this.inputEl; + if (offer !== this.ontologyOffer || this.composing || input.disabled || input.readOnly || + !isKplexOntologyOfferCurrent(input, offer, item.name)) { + this.close(); + return; + } + const edit = ontologyLinkEdit(input.value, offer.range, item.name); + if (!edit) { this.close(); return; } + this.close(); + input.focus(); + input.setSelectionRange(offer.range.start, offer.range.end); + let applied = false; + try { + // Feature-detect the legacy browser editing command: assigning value/setRangeText cannot + // retain the input's native undo stack, and some hosts do not expose editing commands. + const nativeCommand: unknown = Reflect.get(input.ownerDocument, "execCommand"); + if (typeof nativeCommand === "function") { + applied = Reflect.apply(nativeCommand, input.ownerDocument, ["insertText", false, edit.insertion]) === true; + } + } catch { + // The documented value/event path also supports hosts without native insertText. + applied = false; + } + if (!applied) { + if (input.value !== offer.text && input.value !== edit.value) return; + input.value = edit.value; + } + if (input.value !== edit.value) return; + this.dispatchInputChange(); + input.setSelectionRange(edit.caret, edit.caret); + } + private resetSuggestions() { this.close(); this.activeOpen = -1; @@ -898,6 +1000,13 @@ export class InlineLinkSuggester close(): void { // A pending heading/block/frame lookup must not reopen a retired input's scope. const generation = ++this.suggestionGeneration; + this.ontologyOffer = null; + this.ontologyItems = []; + if (this.inputEl?.isConnected === false) { + this.inputEl.removeEventListener("keydown", this.handleBracketKeyDown); + this.inputEl.removeEventListener("compositionstart", this.handleCompositionStart); + this.inputEl.removeEventListener("compositionend", this.handleCompositionEnd); + } // Docking/closing a host can detach the dropdown before its scope is released. // popScope is idempotent and uses the scope's acquisition window, not DOM visibility. this.app.keymap.popScope(this.scope); @@ -919,6 +1028,24 @@ export class InlineLinkSuggester this.shouldNotOpen = false; } + /** Find this wikilink's delimiter while retaining balanced literal filename brackets. + * A filename's final ] next to an outer ontology ] is not a wikilink closer. An independent + * subsequent [[ still ends this incomplete context instead of being swallowed on selection. */ + private findLinkClose(value: string, open: number): number { + let depth = 0; + for (let index = open + 2; index < value.length; index++) { + const char = value[index]; + if (char === "[") { + if (value[index + 1] === "[") return -1; + depth++; + } else if (char === "]") { + if (depth > 0) depth--; + else if (value[index + 1] === "]") return index; + } + } + return -1; + } + private findActiveLink( value: string, pos: number, @@ -931,7 +1058,7 @@ export class InlineLinkSuggester break; } const nextOpen = value.indexOf("[[", open + 2); - const closeCandidate = value.indexOf("]]", open + 2); + const closeCandidate = this.findLinkClose(value, open); const closeBelongsToLink = closeCandidate !== -1 && (nextOpen === -1 || closeCandidate < nextOpen); const close = closeBelongsToLink ? closeCandidate : -1; @@ -1008,12 +1135,13 @@ export class InlineLinkSuggester private dispatchInputChange() { const eventInit = { bubbles: true, composed: true, cancelable: true }; + const ownerWindow = this.inputEl.ownerDocument.defaultView ?? window; const inputEvt = - typeof InputEvent !== "undefined" - ? new InputEvent("input", eventInit) - : new Event("input", eventInit); + typeof ownerWindow.InputEvent !== "undefined" + ? new ownerWindow.InputEvent("input", eventInit) + : new ownerWindow.Event("input", eventInit); this.inputEl.dispatchEvent(inputEvt); - const changeEvt = new Event("change", eventInit); + const changeEvt = new ownerWindow.Event("change", eventInit); this.inputEl.dispatchEvent(changeEvt); } } diff --git a/src/shared/Suggesters/kplexOntologyProvider.ts b/src/shared/Suggesters/kplexOntologyProvider.ts new file mode 100644 index 00000000..c4d9de4f --- /dev/null +++ b/src/shared/Suggesters/kplexOntologyProvider.ts @@ -0,0 +1,104 @@ +/** Optional public K-Plex completion boundary. Matching and ontology policy stay in K-Plex; + * this consumer validates bounded detached data and retains only the offered API incarnation. + * Every read reacquires the public window entry point, including after reload or in a popout. */ + +type DataRecord = Record; +type PublicRead = (this: DataRecord, ...args: unknown[]) => unknown; +export type OntologyFieldSuggestion = Readonly<{name: string; partner?: string; description?: string}>; +export type OntologyCompletionOffer = Readonly<{ + provider: DataRecord; + api: DataRecord; + read: PublicRead; + configuration: number; + text: string; + cursor: number; + range: Readonly<{start: number; end: number}>; + items: readonly OntologyFieldSuggestion[]; +}>; + +const MAX_TEXT = 65_536; +const MAX_ITEMS = 100; +const MAX_OUTPUT = 1_048_576; + +/** Narrow only plain object-shaped protocol values; arrays are never envelopes or API roots. */ +function record(value: unknown): value is DataRecord { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +/** A public method is invoked with its captured API as receiver, preserving service ownership. */ +function callable(value: unknown): value is PublicRead { + return typeof value === "function"; +} + +/** Read the documented public root, preferring the input's realm and its supported popout alias. */ +function providerFor(input: HTMLInputElement | HTMLTextAreaElement): DataRecord | null { + const owner = input.ownerDocument.defaultView ?? window; + const local: unknown = Reflect.get(owner, "kplexApi"); + if (record(local)) return local; + const main: unknown = Reflect.get(window, "kplexApi"); + return record(main) ? main : null; +} + +/** Request current public completion without loading K-Plex, reading private settings or issuing + * graph work. Missing, old, disabled, retired, malformed and throwing providers are silent fallbacks. + * Replacement integrity is checked against the original input, never a normalized display label. */ +export function readKplexOntologyCompletion( + input: HTMLInputElement | HTMLTextAreaElement, + limit = 20, +): OntologyCompletionOffer | null { + const text = input.value, cursor = input.selectionStart; + if (input.isConnected === false || cursor === null || cursor !== input.selectionEnd || + text.length > MAX_TEXT || !Number.isInteger(limit) || limit < 1 || limit > MAX_ITEMS) return null; + try { + const provider = providerFor(input); + if (!provider || provider.version !== 1 || !record(provider.v1)) return null; + const api = provider.v1; + if (api.version !== 1 || !callable(api.capabilities) || !callable(api.completeOntology)) return null; + const capabilities: unknown = api.capabilities.call(api); + if (!record(capabilities) || capabilities.ok !== true || !record(capabilities.value) || + !Array.isArray(capabilities.value.operations) || capabilities.value.operations.length > 64 || + !capabilities.value.operations.includes("completeOntology")) return null; + const read = api.completeOntology; + const result: unknown = read.call(api, {text, cursor, limit}); + if (!record(result) || result.ok !== true || !record(result.revision) || + !Number.isSafeInteger(result.revision.configuration) || Number(result.revision.configuration) < 0 || + !record(result.value) || result.value.state !== "matched") return null; + const value = result.value, context = value.context; + if (!record(context) || !record(context.range) || !Array.isArray(value.items) || value.items.length > limit) return null; + const start = context.range.start, end = context.range.end; + if (typeof start !== "number" || !Number.isInteger(start) || start < 0 || start > cursor || end !== cursor || + typeof context.trigger !== "string" || typeof context.query !== "string" || + text.slice(start, cursor) !== context.trigger + context.query) return null; + const items: OntologyFieldSuggestion[] = []; + let budget = text.length + context.trigger.length + context.query.length; + for (const field of value.items) { + if (!record(field) || typeof field.name !== "string" || !field.name || field.name.length > MAX_TEXT || + (field.partner !== undefined && typeof field.partner !== "string") || + (field.description !== undefined && typeof field.description !== "string")) return null; + const partner = typeof field.partner === "string" ? field.partner : undefined; + const description = typeof field.description === "string" ? field.description : undefined; + budget += field.name.length + (partner?.length ?? 0) + (description?.length ?? 0); + if (budget > MAX_OUTPUT) return null; + items.push({name: field.name, partner, description}); + } + return {provider, api, read, configuration: Number(result.revision.configuration), text, cursor, + range: {start, end: cursor}, items}; + } catch { + // Another optional plugin's failure must not interrupt ordinary input or existing suggestions. + return null; + } +} + +/** Recheck identity, configuration and the exact input/range before a captured row may mutate it. + * Semantic/source revisions are deliberately irrelevant to this configuration-only completion. */ +export function isKplexOntologyOfferCurrent( + input: HTMLInputElement | HTMLTextAreaElement, + offer: OntologyCompletionOffer, + name: string, +): boolean { + if (input.value !== offer.text || input.selectionStart !== offer.cursor || input.selectionEnd !== offer.cursor) return false; + const current = readKplexOntologyCompletion(input, Math.max(20, offer.items.length)); + return current !== null && current.provider === offer.provider && current.api === offer.api && current.read === offer.read && + current.configuration === offer.configuration && current.range.start === offer.range.start && current.range.end === offer.range.end && + current.items.some(field => field.name === name); +} diff --git a/src/shared/Suggesters/ontologyLinkCompletion.ts b/src/shared/Suggesters/ontologyLinkCompletion.ts new file mode 100644 index 00000000..d9379020 --- /dev/null +++ b/src/shared/Suggesters/ontologyLinkCompletion.ts @@ -0,0 +1,34 @@ +/** HTML-input insertion policy over a provider-owned exact range. This helper neither matches + * triggers nor interprets ontology. It preserves suffix text and owns only an adjacent wrapper. */ + +export type OntologyLinkEdit = Readonly<{value: string; insertion: string; caret: number}>; + +/** Locate a matching wrapper closer on the same logical line without consuming any suffix. + * Nested suffix delimiters retain their own closers; trigger/query characters are being replaced. */ +function hasWrapperCloser(text: string, start: number, opener: string, closer: string): boolean { + let depth = 1; + for (let index = start; index < text.length; index++) { + const char = text[index]; + if (/[\n\r\u2028\u2029]/.test(char)) return false; + if (char === opener) depth++; + else if (char === closer && --depth === 0) return true; + } + return false; +} + +/** Construct plain physical-field insertion, reusing a matching closer or adding one before + * unrelated suffix text. Bare fields have no trailing space; wrappers leave one value-entry space. + * The collapsed caret follows that space, immediately before an adjacent existing/new closer. */ +export function ontologyLinkEdit( + text: string, + range: Readonly<{start: number; end: number}>, + name: string, +): OntologyLinkEdit | null { + const {start, end} = range; + if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || end < start || end > text.length || !name) return null; + const before = text.slice(0, start), after = text.slice(end), opener = before.charAt(before.length - 1); + const closer = opener === "(" ? ")" : opener === "[" && !before.endsWith("[[") ? "]" : null; + const field = name + "::" + (closer ? " " : ""); + const insertion = field + (closer && !hasWrapperCloser(text, end, opener, closer) ? closer : ""); + return {value: before + insertion + after, insertion, caret: start + field.length}; +} diff --git a/tests/features.json b/tests/features.json index 0970ada3..4cf876c9 100644 --- a/tests/features.json +++ b/tests/features.json @@ -232,12 +232,69 @@ "priority": "P0", "name": "Text, links and history", "anchors": [ + { + "path": "src/shared/Suggesters/InlineLinkSuggester.ts", + "symbol": "class InlineLinkSuggester" + }, { "path": "src/view/ExcalidrawView.ts", "symbol": "ExcalidrawView" } ], "tests": [ + { + "layer": "native", + "path": "scripts/testing/host/kplexOntology.mjs", + "cases": [ + "native:kplex-ontology-passive:main", + "native:kplex-ontology-links:main", + "native:kplex-ontology-configuration:main", + "native:kplex-ontology-provider:main", + "native:kplex-ontology-markdown:main", + "native:kplex-ontology-passive:popout", + "native:kplex-ontology-links:popout", + "native:kplex-ontology-configuration:popout", + "native:kplex-ontology-provider:popout", + "native:kplex-ontology-markdown:popout", + "native:kplex-ontology-passive:phone", + "native:kplex-ontology-links:phone", + "native:kplex-ontology-configuration:phone", + "native:kplex-ontology-provider:phone", + "native:kplex-ontology-markdown:phone", + "native:kplex-ontology-passive:tablet", + "native:kplex-ontology-links:tablet", + "native:kplex-ontology-configuration:tablet", + "native:kplex-ontology-provider:tablet", + "native:kplex-ontology-markdown:tablet" + ] + }, + { + "layer": "source", + "path": "scripts/testing/inlineLinkSuggester.test.mjs", + "cases": [ + "node:scripts/testing/inlineLinkSuggester.test.mjs::configured public ontology completion uses the existing inline popup owner", + "node:scripts/testing/inlineLinkSuggester.test.mjs::ontology insertion preserves exact names, wrappers, closers, suffixes and caret", + "node:scripts/testing/inlineLinkSuggester.test.mjs::ontology completion continues into the existing wikilink mode and bracket-containing names", + "node:scripts/testing/inlineLinkSuggester.test.mjs::a bracket in a queried filename cannot consume the square ontology wrapper", + "node:scripts/testing/inlineLinkSuggester.test.mjs::wrapped bracket filenames retain real alias, heading, block, frame and clipped-frame parsing", + "node:scripts/testing/inlineLinkSuggester.test.mjs::provider/configuration/input changes retire captured ontology rows without mutation", + "node:scripts/testing/inlineLinkSuggester.test.mjs::missing or incompatible providers leave normal editing and existing suggestion precedence intact", + "node:scripts/testing/inlineLinkSuggester.test.mjs::composition and selections do not call the provider or submit link-editor Enter", + "node:scripts/testing/inlineLinkSuggester.test.mjs::ontology annotations render as inert text and two inputs cannot choose each other's rows" + ] + }, + { + "layer": "source", + "path": "scripts/testing/kplexOntology.source.test.mjs", + "cases": [ + "node:scripts/testing/kplexOntology.source.test.mjs::optional completion reads only the public owning-window API and returns detached inert fields", + "node:scripts/testing/kplexOntology.source.test.mjs::missing, incompatible and throwing optional providers never escape into editing", + "node:scripts/testing/kplexOntology.source.test.mjs::bad ranges, oversized results and disabled/unavailable envelopes cannot become offers", + "node:scripts/testing/kplexOntology.source.test.mjs::input bounds and noncollapsed or detached selections refuse before the optional call", + "node:scripts/testing/kplexOntology.source.test.mjs::selection fences provider, method, configuration and input while ignoring unrelated graph revisions", + "node:scripts/testing/kplexOntology.source.test.mjs::wrapper edits preserve suffixes and balanced closers with exact UTF-16 carets" + ] + }, { "layer": "native", "path": "scripts/testing/host/textUndo.mjs", diff --git a/tests/fixtures/kplex-ontology/data.json b/tests/fixtures/kplex-ontology/data.json new file mode 100644 index 00000000..8a36916c --- /dev/null +++ b/tests/fixtures/kplex-ontology/data.json @@ -0,0 +1,34 @@ +{ + "kplexInitialized": true, + "indexingMode": "on-demand", + "indexingModeDesktop": "on-demand", + "indexingModeTablet": "on-demand", + "indexingModeMobile": "on-demand", + "allowOntologySuggester": true, + "ontologySuggesterTrigger": ":::", + "ontologySuggesterParentTrigger": "::p", + "ontologySuggesterChildTrigger": "::c", + "ontologySuggesterLeftFriendTrigger": "::f", + "ontologySuggesterRightFriendTrigger": "::r", + "ontologySuggesterPreviousTrigger": "::s", + "ontologySuggesterNextTrigger": "::n", + "ontologySuggesterMidSentenceTrigger": "(", + "ontologyPairingVersion": 1, + "boldFields": true, + "primaryTagField": "Tags", + "hierarchy": { + "exclusions": [], + "parents": ["parent/child", "Parent Exact"], + "children": [], + "leftFriends": ["friend/ally"], + "rightFriends": ["Challenger", "challenge"], + "previous": ["before/after"], + "next": [], + "hidden": ["Hidden"] + }, + "ontologyDescriptions": { + "parent": "Literal parent description.", + "friend": "Friend description: árvíz 漢字." + }, + "__ontologyCompletionUnknown": {"preserve": true} +} diff --git a/tests/inventory.json b/tests/inventory.json index 7ccb9fff..b20e3497 100644 --- a/tests/inventory.json +++ b/tests/inventory.json @@ -2568,6 +2568,10 @@ "path": "scripts/testing/inlineLinkSuggester.test.mjs", "mode": "isolated-or-extracted" }, + { + "path": "scripts/testing/kplexOntology.source.test.mjs", + "mode": "direct-module-or-tooling" + }, { "path": "scripts/testing/localVault.test.mjs", "mode": "isolated-or-extracted" @@ -2584,6 +2588,10 @@ "path": "scripts/testing/markdownImageInsertion.source.test.mjs", "mode": "direct-module-or-tooling" }, + { + "path": "scripts/testing/nativeRepositoryRoot.test.mjs", + "mode": "direct-module-or-tooling" + }, { "path": "scripts/testing/package.source.test.mjs", "mode": "direct-module-or-tooling"