diff --git a/.changeset/json-schema-completions.md b/.changeset/json-schema-completions.md new file mode 100644 index 0000000..025c175 --- /dev/null +++ b/.changeset/json-schema-completions.md @@ -0,0 +1,5 @@ +--- +"@inkcre/ui-web": patch +--- + +修复 JSON 编辑器的 Schema 补全,让接受建议时按语言服务给出的范围替换文本,并保留引号、默认值和可编辑占位符。 diff --git a/packages/web/skills/ui-web/references/components/InkJsonEditor.md b/packages/web/skills/ui-web/references/components/InkJsonEditor.md index d15f0ac..2c00f48 100644 --- a/packages/web/skills/ui-web/references/components/InkJsonEditor.md +++ b/packages/web/skills/ui-web/references/components/InkJsonEditor.md @@ -62,7 +62,7 @@ - None. - Types exported from the package root: `JsonEditorValidation` -- Story variants: `Basic`, `JSON Schema`, `In popup`, `Validated save and isolated editors` +- Story variants: `Basic`, `JSON Schema`, `In popup`, `Validated save and isolated editors`, `Schema completion` ### API type definitions diff --git a/packages/web/src/components/inkJsonEditor/inkJsonEditor.vue b/packages/web/src/components/inkJsonEditor/inkJsonEditor.vue index c82c392..b454a1e 100644 --- a/packages/web/src/components/inkJsonEditor/inkJsonEditor.vue +++ b/packages/web/src/components/inkJsonEditor/inkJsonEditor.vue @@ -13,6 +13,7 @@ import { SCHEMA_RESOLVE_ERROR, type JsonEditorValidation, } from "./jsonSchemaService"; +import { jsonSchemaCompletion } from "./jsonSchemaCompletion"; import { setDiagnostics, type Diagnostic } from "@codemirror/lint"; import { TextDocument } from "vscode-languageserver-textdocument"; @@ -121,6 +122,7 @@ const completion = autocompletion({ override: [ async (context) => { if (!props.schema) return null; + context.addEventListener("abort", () => {}, { onDocChange: true }); const currentService = service; const doc = TextDocument.create( `inkcre://document/${controlId.value}.json`, @@ -134,16 +136,8 @@ const completion = autocompletion({ doc.positionAt(context.pos), currentService.parseJSONDocument(doc), ); - if (currentService !== service || context.aborted) return null; - return { - from: context.pos, - options: - result?.items.map((item) => ({ - label: item.label, - detail: item.detail, - type: item.kind === 10 ? "property" : "value", - })) ?? [], - }; + if (!result || currentService !== service || context.aborted) return null; + return jsonSchemaCompletion(doc, context.pos, result.items); } catch (error) { emit("error", error); return null; diff --git a/packages/web/src/components/inkJsonEditor/jsonSchemaCompletion.ts b/packages/web/src/components/inkJsonEditor/jsonSchemaCompletion.ts new file mode 100644 index 0000000..6762b0c --- /dev/null +++ b/packages/web/src/components/inkJsonEditor/jsonSchemaCompletion.ts @@ -0,0 +1,74 @@ +import { + insertCompletionText, + pickedCompletion, + snippet, + type Completion, + type CompletionResult, +} from "@codemirror/autocomplete"; +import type { + CompletionItem, + CompletionItemKind, + InsertTextFormat, +} from "vscode-json-languageservice"; +import type { TextDocument } from "vscode-languageserver-textdocument"; + +const PROPERTY: typeof CompletionItemKind.Property = 10; +const SNIPPET: typeof InsertTextFormat.Snippet = 2; + +function snippetInsertion(text: string) { + let hasFields = false; + // VS Code escapes literal JSON before adding numeric fields. CodeMirror escapes braces. + const template = text.replace( + /\\([\\$}])|\$(\d+)|\$\{(\d+)(?::((?:\\.|[^\\}])*))?\}|[{}]/g, + (token, escaped, shortField, longField, defaultText = "") => { + const field = shortField ?? longField; + if (field === undefined) return (escaped ?? token).replace(/[{}]/g, "\\$&"); + + const value = defaultText.replace(/\\([\\$}])/g, "$1"); + // CodeMirror's numbered fields only support single-line defaults without braces. + if (/[{}\r\n]/.test(value)) return value.replace(/[{}]/g, "\\$&"); + hasFields = true; + if (field === "0") return "${}" + value; + return "${" + field + (value ? ":" + value : "") + "}"; + }, + ); + return hasFields ? snippet(template) : template.replace(/\\([{}])/g, "$1"); +} + +function completionOption(item: CompletionItem, suffixLength: number): Completion { + const label = item.filterText ?? item.label; + const text = item.textEdit?.newText ?? item.insertText ?? item.label; + const insertion = item.insertTextFormat === SNIPPET ? snippetInsertion(text) : text; + return { + label, + displayLabel: label === item.label ? undefined : item.label, + detail: item.detail, + type: item.kind === PROPERTY ? "property" : "value", + apply(view, completion, from, to) { + const end = to + suffixLength; + if (typeof insertion === "function") { + insertion(view, completion, from, end); + } else { + view.dispatch({ + ...insertCompletionText(view.state, insertion, from, end), + annotations: pickedCompletion.of(completion), + }); + } + }, + }; +} + +export function jsonSchemaCompletion( + document: TextDocument, + position: number, + items: CompletionItem[], +): CompletionResult | null { + if (!items.length) return null; + // The JSON language service gives every option the same replacement range. + const edit = items[0].textEdit; + const range = edit && "range" in edit ? edit.range : undefined; + const from = range ? document.offsetAt(range.start) : position; + const end = range ? document.offsetAt(range.end) : position; + // CodeMirror filters by the text before the cursor. Applying also replaces the token's suffix. + return { from, options: items.map((item) => completionOption(item, end - position)) }; +} diff --git a/packages/web/stories/specialized/inkJsonEditor.story.md b/packages/web/stories/specialized/inkJsonEditor.story.md index e667b71..8c58f8b 100644 --- a/packages/web/stories/specialized/inkJsonEditor.story.md +++ b/packages/web/stories/specialized/inkJsonEditor.story.md @@ -8,4 +8,6 @@ validation 事件传出 JsonEditorValidation,包含对应 text、status、vali Story 的“Validated save and isolated editors”演示两个 schema 并存,以及如何在无效输入期间禁用保存。label 为编辑区提供名称,error 和诊断关联到 aria-describedby。JSON Schema 编辑需要包声明的 CodeMirror 和语言服务依赖。 +Story 的“Schema completion”可用 Ctrl+Space 打开建议,再按 Enter 接受。在空对象中接受 `count` 会插入 `"count": 0` 并选中默认值。将内容改为 `{"cou"}` 后,在 `cou` 末尾接受同一建议,编辑器会替换整个属性名。字符串枚举和数组元素也按 schema 插入,例如将 `{"mode":"fa","flags":["de"]}` 中的值补全为 `"fast"` 和 `"debug"`。 + 编辑器文本读取 label-lg 角色和系统 mono 家族,避免入口不同导致字体被覆盖。第三方编辑器内部布局与语法主题仍由 CodeMirror 管理。 diff --git a/packages/web/stories/specialized/inkJsonEditor.story.vue b/packages/web/stories/specialized/inkJsonEditor.story.vue index 73deefc..00a8b13 100644 --- a/packages/web/stories/specialized/inkJsonEditor.story.vue +++ b/packages/web/stories/specialized/inkJsonEditor.story.vue @@ -41,6 +41,15 @@ const secondSchema = { properties: { name: { type: "string" } }, required: ["name"], }; +const completionDraft = ref("{}"); +const completionSchema = { + type: "object", + properties: { + count: { type: "integer" }, + mode: { type: "string", enum: ["fast", "safe"] }, + flags: { type: "array", items: { type: "string", enum: ["debug", "trace"] } }, + }, +}; const firstDraft = ref('{"count":0}'); const secondDraft = ref('{"name":"existing"}'); const result = ref(); @@ -85,5 +94,8 @@ function saveDraft() { />

状态:{{ result?.status }};已保存:{{ saved }}

+ + +