Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/json-schema-completions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@inkcre/ui-web": patch
---

修复 JSON 编辑器的 Schema 补全,让接受建议时按语言服务给出的范围替换文本,并保留引号、默认值和可编辑占位符。
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
14 changes: 4 additions & 10 deletions packages/web/src/components/inkJsonEditor/inkJsonEditor.vue
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -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`,
Expand All @@ -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;
Expand Down
74 changes: 74 additions & 0 deletions packages/web/src/components/inkJsonEditor/jsonSchemaCompletion.ts
Original file line number Diff line number Diff line change
@@ -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)) };
}
2 changes: 2 additions & 0 deletions packages/web/stories/specialized/inkJsonEditor.story.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 管理。
12 changes: 12 additions & 0 deletions packages/web/stories/specialized/inkJsonEditor.story.vue
Original file line number Diff line number Diff line change
Expand Up @@ -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<JsonEditorValidation>();
Expand Down Expand Up @@ -85,5 +94,8 @@ function saveDraft() {
/>
<p>状态:{{ result?.status }};已保存:{{ saved }}</p>
</Variant>
<Variant title="Schema completion">
<InkJsonEditor v-model="completionDraft" label="补全配置" :schema="completionSchema" />
</Variant>
</Story>
</template>