@norio-office/rich-text 0.7.1 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +895 -824
- package/dist/ai/bridge.d.ts +335 -0
- package/dist/ai/consume-stream.d.ts +8 -0
- package/dist/ai/executor.d.ts +19 -0
- package/dist/ai/index.d.ts +8 -0
- package/dist/ai/index.js +4106 -0
- package/dist/ai/tools.d.ts +158 -0
- package/dist/ai-protocol/index.d.ts +12 -0
- package/dist/ai-protocol/index.js +2372 -0
- package/dist/ai-protocol/json-schema.d.ts +5 -0
- package/dist/ai-protocol/patch.d.ts +77 -0
- package/dist/ai-protocol/references.d.ts +11 -0
- package/dist/ai-protocol/stream.d.ts +94 -0
- package/dist/ai-protocol/tools.d.ts +8 -0
- package/dist/ai-protocol/validation.d.ts +20 -0
- package/dist/components/RichTextEditor.vue.d.ts +11 -4
- package/dist/document/ai-identity.d.ts +4 -0
- package/dist/document/nodes/columns-block.d.ts +2 -0
- package/dist/document/nodes/countdown-block.d.ts +2 -0
- package/dist/document/nodes/formula-block.d.ts +2 -0
- package/dist/document/nodes/highlight-block.d.ts +2 -0
- package/dist/document/nodes/image-block.d.ts +8 -0
- package/dist/document/nodes/link-block.d.ts +2 -0
- package/dist/document/nodes/local-file-block.d.ts +2 -0
- package/dist/document/nodes/mention.d.ts +2 -0
- package/dist/document/nodes/office-code-block.d.ts +1 -0
- package/dist/document/nodes/table-cells.d.ts +2 -0
- package/dist/document/nodes/themed-table.d.ts +1 -0
- package/dist/document/nodes/video-block.d.ts +8 -0
- package/dist/document/schema.d.ts +17 -0
- package/dist/extensions/ai-identity.d.ts +1 -0
- package/dist/extensions/columns-block.d.ts +1 -2
- package/dist/extensions/countdown-block.d.ts +1 -2
- package/dist/extensions/formula-block.d.ts +1 -2
- package/dist/extensions/highlight-block.d.ts +1 -2
- package/dist/extensions/image-block.d.ts +4 -8
- package/dist/extensions/link-block.d.ts +1 -2
- package/dist/extensions/local-file-block.d.ts +1 -2
- package/dist/extensions/mention.d.ts +1 -2
- package/dist/extensions/video-block.d.ts +4 -8
- package/dist/{html2canvas-4hiP1s1t.js → html2canvas-BnDzIoab.js} +112 -126
- package/dist/index.js +8343 -7407
- package/dist/index.umd.cjs +2196 -1995
- package/dist/nordox/index.d.ts +95 -0
- package/dist/nordox/index.js +2094 -0
- package/dist/{chunk-C_CI6nMA.js → rolldown-runtime-VHNaYcLd.js} +3 -3
- package/dist/style.css +1 -1
- package/dist/types.d.ts +9 -1
- package/docs/ai/README.md +108 -0
- package/docs/ai/acceptance-report.md +88 -0
- package/docs/ai/capability-matrix.md +43 -0
- package/docs/ai/compatibility.md +9 -0
- package/docs/icons.md +21 -0
- package/examples/ai/browser/App.vue +151 -0
- package/examples/ai/browser/index.html +12 -0
- package/examples/ai/browser/main.ts +5 -0
- package/examples/ai/browser/tsconfig.json +7 -0
- package/examples/ai/browser/vite.config.ts +14 -0
- package/examples/ai/node.mjs +28 -0
- package/package.json +15 -1
package/dist/types.d.ts
CHANGED
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
import { JSONContent } from '@tiptap/core';
|
|
2
|
+
import { RichTextAiEditorAdapter } from './ai/bridge';
|
|
3
|
+
import { NordoxResourceResolver, PackNordoxOptions, RichTextAssetPackaging, UnpackedNordox } from './nordox';
|
|
2
4
|
import { RichTextEditorExportItemKey, RichTextEditorCode, RichTextEditorFeatureItemKey, RichTextEditorInsertMenuItemKey, RichTextEditorOutlinePlacement, RichTextEditorToolbarActionKey } from './feature-codes';
|
|
3
5
|
export type { RichTextEditorExportItemKey, RichTextEditorCode, RichTextEditorFeatureCode, RichTextEditorFeatureItemKey, RichTextEditorInsertMenuItemKey, RichTextEditorOutlinePlacement, RichTextEditorToolbarActionKey, } from './feature-codes';
|
|
4
6
|
export type RichTextEditorProps = {
|
|
5
7
|
modelValue?: JSONContent | null;
|
|
6
8
|
documentName?: string;
|
|
7
|
-
editable?: boolean;
|
|
8
9
|
mode?: 'edit' | 'preview';
|
|
10
|
+
assetPackaging?: RichTextAssetPackaging | null;
|
|
9
11
|
showToolbar?: boolean;
|
|
12
|
+
showAiTargetButton?: boolean;
|
|
10
13
|
watermark?: RichTextEditorWatermarkOptions | null;
|
|
11
14
|
showOutline?: boolean;
|
|
12
15
|
outlinePlacement?: RichTextEditorOutlinePlacement;
|
|
@@ -250,6 +253,11 @@ export type RichTextEditorInstance = {
|
|
|
250
253
|
exportPdf: () => Promise<Blob | null>;
|
|
251
254
|
exportImage: (options?: RichTextEditorImageExportOptions) => Promise<Blob | null>;
|
|
252
255
|
exportHtml: () => string | null;
|
|
256
|
+
exportNordox: (options?: Omit<PackNordoxOptions, 'existingResources' | 'title'>) => Promise<Blob>;
|
|
257
|
+
openNordox: (input: Blob | Uint8Array | ArrayBuffer, options?: {
|
|
258
|
+
resourceResolver?: NordoxResourceResolver;
|
|
259
|
+
}) => Promise<UnpackedNordox>;
|
|
260
|
+
getAiAdapter: () => RichTextAiEditorAdapter;
|
|
253
261
|
insertImage: (payload: RichTextEditorImagePayload | RichTextEditorImagePayload[]) => boolean;
|
|
254
262
|
insertVideo: (payload: RichTextEditorVideoPayload) => boolean;
|
|
255
263
|
insertFile: (payload: RichTextEditorFilePayload) => boolean;
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
# AI and native files
|
|
2
|
+
|
|
3
|
+
This package exposes three additional entry points and one opt-in AI target button on `<RichTextEditor>`:
|
|
4
|
+
|
|
5
|
+
| Import | Environment | Purpose |
|
|
6
|
+
| --- | --- | --- |
|
|
7
|
+
| `@norio-office/rich-text/ai-protocol` | Node 20+ or browser | Schema, validation, tool definitions, NDJSON stream decoder/builder |
|
|
8
|
+
| `@norio-office/rich-text/nordox` | Node 20+ or browser | ZIP-based `.nordox` pack/unpack and resources |
|
|
9
|
+
| `@norio-office/rich-text/ai` | Browser editor | Bound Bridge, local transactions, stream preview and tool handlers |
|
|
10
|
+
|
|
11
|
+
The component adds `assetPackaging?: { images?, videos?, files? }` (each value `embed` or `reference`) and `showAiTargetButton?: boolean` (default `false`). Its instance exposes `getAiAdapter()`, `openNordox(input)` and `exportNordox(options)`. Existing JSON `v-model`, ordinary editing, HTML/PDF/image exports, and Yjs collaboration remain separate. Neither the Bridge nor the Skill calls a model by itself.
|
|
12
|
+
|
|
13
|
+
## Fixed AI target
|
|
14
|
+
|
|
15
|
+
Render `<RichTextEditor ref="editorRef" :show-ai-target-button="true" />`, then create one Bridge for that mounted editor and a stable `documentId`. The toolbar button is disabled until the Bridge is bound. It captures the editor's latest text, node, block, table-cell, or cursor selection without changing the document. The returned target contains `targetId`, document/session IDs, revision, native positions and selection details, a bounded preview, and selected JSON content. The editor owns the blue view-only marker and badge; neither is saved, copied, broadcast through Yjs, or added to Undo.
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
const bridge = createRichTextAiBridge(editorRef.value!, { documentId: hostDocumentId })
|
|
19
|
+
const stop = bridge.onEvent(event => {
|
|
20
|
+
if (event.type === 'ai-target-change') {
|
|
21
|
+
rangeCard.value = event.target // null means cleared; cancel the matching host request.
|
|
22
|
+
}
|
|
23
|
+
if (event.type === 'ai-target-invalidated') {
|
|
24
|
+
// The selected content changed or was deleted; ask the user to select again.
|
|
25
|
+
}
|
|
26
|
+
})
|
|
27
|
+
|
|
28
|
+
// When the user sends an AI instruction from the host panel:
|
|
29
|
+
const target = bridge.getAiTarget()
|
|
30
|
+
if (!target) throw new Error('Select an AI editing range first')
|
|
31
|
+
const context = bridge.createEditContext({
|
|
32
|
+
requestId: crypto.randomUUID(), instruction: userInstruction,
|
|
33
|
+
scope: 'selection', targetId: target.targetId,
|
|
34
|
+
})
|
|
35
|
+
// Use context.targetRefs with readContent, a patch, or a stream.
|
|
36
|
+
|
|
37
|
+
// The host's range-card close button:
|
|
38
|
+
bridge.clearAiTarget({ targetId: target.targetId, reason: 'host-close' })
|
|
39
|
+
stop()
|
|
40
|
+
bridge.dispose()
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Clicking the editor body or the badge close button also clears the target and emits `ai-target-change` with `target: null`. Re-clicking the toolbar button does **not** clear it: an unchanged selection keeps the same target; a new selection replaces it. `clearAiTarget` is idempotent, cancels its uncommitted contexts/streams, and blocks late commits. The host must separately cancel its model/IPC request when it receives a clear event. A successful commit also clears the marker without undoing the committed edit. The toolbar is hidden in preview mode and disabled while a target-bound request is active. See the runnable [browser example](../../examples/ai/browser/App.vue).
|
|
44
|
+
|
|
45
|
+
## Local edit example
|
|
46
|
+
|
|
47
|
+
```ts
|
|
48
|
+
import { createRichTextAiBridge, createRichTextToolHandlers } from '@norio-office/rich-text/ai'
|
|
49
|
+
|
|
50
|
+
const bridge = createRichTextAiBridge(editorRef.value!, {
|
|
51
|
+
documentId: hostDocumentId,
|
|
52
|
+
policy: { allowWholeDocument: false },
|
|
53
|
+
resourceResolver: hostResourceResolver,
|
|
54
|
+
authorizeExternalReference: ref => hostCanUseReference(hostDocumentId, ref),
|
|
55
|
+
})
|
|
56
|
+
const handlers = createRichTextToolHandlers(bridge, {
|
|
57
|
+
createDocument: async ({ title, bytes }) => hostSaveNewDocument(title, bytes),
|
|
58
|
+
resourceResolver: hostResourceResolver,
|
|
59
|
+
authorizeExternalReference: ref => hostCanUseReference(hostDocumentId, ref),
|
|
60
|
+
})
|
|
61
|
+
const context = bridge.createEditContext({
|
|
62
|
+
requestId: crypto.randomUUID(), instruction: 'Change only text color',
|
|
63
|
+
writePolicy: {
|
|
64
|
+
allowedOperations: ['setMarks'],
|
|
65
|
+
allowedMarkAttributes: { textStyle: ['color'] },
|
|
66
|
+
},
|
|
67
|
+
})
|
|
68
|
+
const input = {
|
|
69
|
+
protocolVersion: 1, documentId: hostDocumentId, requestId: context.requestId,
|
|
70
|
+
contextId: context.contextId, baseRevision: context.baseRevision,
|
|
71
|
+
operations: [{ type: 'setMarks', targetRef: context.targetRefs[0], marks: [
|
|
72
|
+
{ type: 'textStyle', attrs: { color: '#ff0000' } },
|
|
73
|
+
] }],
|
|
74
|
+
}
|
|
75
|
+
const result = await handlers.richtext_apply_patch(input)
|
|
76
|
+
// Dispose when the editor/document session is closed.
|
|
77
|
+
bridge.dispose()
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
The direct `createEditContext` call above remains supported for older hosts, which must capture the context before focusing the AI chat input. With the opt-in button, capture `targetId` first and pass it when creating the context, even after the chat input takes focus. `targetRef` is issued by this Bridge, not invented by the model. The Bridge applies a local ProseMirror transaction; never write a local AI patch by replacing `v-model` or calling `setContent`. A host may persist `update:modelValue` once and use the Bridge `applied` event only to label its provenance, avoiding double saves. In preview mode write methods reject requests. For Yjs, the same Bridge maps target positions through the active collaboration binding, checks target content, and dispatches the final edit through the collaborative document. A stream preview is local only.
|
|
81
|
+
|
|
82
|
+
`writePolicy` is set by the host when it creates the context, not by a model tool call. It can restrict operation names, Mark attributes, node attributes and table actions for that request. A selection snapshot includes native positions, direction, intersecting text blocks and Mark ranges; a table selection includes cell coordinates. The Bridge keeps the last selection after focus moves to the chat input.
|
|
83
|
+
|
|
84
|
+
`hostCanUseReference` in the example is a host-owned lookup against already authorized resources and object IDs; it must return a synchronous boolean for the Bridge. The create-document tool also accepts an asynchronous authorizer. New AI media, links, mentions and existing comment-thread references are rejected when no authorizer is configured or it denies the reference. The callback does not create comment threads, upload media, or grant a whole-document scope. Existing document references remain readable and are not deleted just because AI authorization is absent. `getCapabilities()` exposes attribute constraints, node content rules, read-only state and the missing external dependencies.
|
|
85
|
+
|
|
86
|
+
`richtext_read_document` returns a bounded outline plus scoped content; `richtext_read_target` also returns short neighboring block summaries. Both require a live context. A truncated read includes `nextCursor`, which the host can pass back to either read tool without expanding write permission.
|
|
87
|
+
|
|
88
|
+
Tool errors return `{ ok: false, error: { code, message, retryable, requiresContextRefresh } }`. If `requiresContextRefresh` is true, capture a new context and read the selection/target again; do not retry against a stale `targetRef` or replace the whole document. A text-only model can return complete JSON validated against a public tool `inputSchema`, then use the same handler; [the Skill integration example](https://github.com/cgq001/norio-office-rich-text-skill/blob/main/norio-rich-text/references/integration.md) shows this path. Complete JSON is not a substitute for incremental NDJSON when live preview is required.
|
|
89
|
+
|
|
90
|
+
## Native file and resources
|
|
91
|
+
|
|
92
|
+
```ts
|
|
93
|
+
const file = await editorRef.value!.exportNordox({
|
|
94
|
+
assetPackaging: { images: 'embed', videos: 'reference', files: 'reference' },
|
|
95
|
+
resourceResolver: hostResourceResolver,
|
|
96
|
+
})
|
|
97
|
+
await editorRef.value!.openNordox(file)
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
`exportNordox` returns a Blob. The host performs atomic file replacement or download and reports save success only after that operation succeeds. `embed` needs `readBytes(ref, { signal, maxBytes })`; failure aborts without changing the editor. `reference` requires a durable URL/reference, never a blob/data/file URL. Existing embedded bytes remain embedded unless a field is explicitly switched. Normal JSON autosave does not pack a ZIP. See [Nordox format](https://github.com/cgq001/norio-office-rich-text-skill/blob/main/norio-rich-text/references/nordox-format.md).
|
|
101
|
+
|
|
102
|
+
`openNordox(file, { resourceResolver })` may resolve external references to temporary display URLs. If one external resource is unavailable, the original persistent source is retained and the rest of the document still opens. Re-export restores persistent references rather than storing display-only blob URLs.
|
|
103
|
+
|
|
104
|
+
## Streaming
|
|
105
|
+
|
|
106
|
+
Use `bridge.beginStream(...)`, then forward real incremental NDJSON chunks with `consumeRichTextAiStream(bridge, asyncIterable, { streamId, signal })`. It decodes arbitrary UTF-8 chunk boundaries, shows draft content in the editor before `stream.end`, and commits only after the transport ends normally. Cancellation/error discards the draft. See [streaming protocol](https://github.com/cgq001/norio-office-rich-text-skill/blob/main/norio-rich-text/references/streaming.md) and the runnable [browser example](../../examples/ai/browser/App.vue). For offline creation, run [the Node example](../../examples/ai/node.mjs) or `node packages/skills/norio-rich-text/scripts/rich-text.mjs create --stream --input - --output result.nordox` from the workspace root.
|
|
107
|
+
|
|
108
|
+
Copying the Skill gives an AI system format instructions and fixtures, not editor permissions or automatically registered tools. The host must register the definitions, authorize the session, provide model transport, resources and persistent storage. See [capabilities](capability-matrix.md), [compatibility](compatibility.md) and [acceptance](acceptance-report.md).
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# AI delivery acceptance record
|
|
2
|
+
|
|
3
|
+
Date: 2026-10-13. Scope: this editor repository only. No real model, NorioWork runtime, storage service or production collaboration provider was connected. "Local" below means deterministic tests/fixtures or the mock browser example, **not** an end-to-end AI product pass. The source checklist is `docs/富文本编辑器公共AI接口与Skill交付任务书.md` in the repository root.
|
|
4
|
+
|
|
5
|
+
## Verified commands and evidence
|
|
6
|
+
|
|
7
|
+
| Check | Result |
|
|
8
|
+
| --- | --- |
|
|
9
|
+
| `npm run typecheck` | Passed: editor and playground |
|
|
10
|
+
| `npm run build:all` | Passed: editor, three subpath bundles and playground |
|
|
11
|
+
| `npm run test:protocol -w packages/office-word` | Passed: 73 tests covering protocol, ZIP, CLI, executor, mounted Vue component, browser DOM mock and two-Y.Doc collaboration fixture |
|
|
12
|
+
| `npm run skill:verify -w packages/office-word` | Passed: five generated Schemas and 26 Skill files; media reference fixture packs and reopens with three external resources |
|
|
13
|
+
| `npm run example:ai:build -w packages/office-word` | Browser example builds |
|
|
14
|
+
| JSON Schema compile smoke check | Document, AI-created document, patch and stream schemas compile under JSON Schema 2020-12; all six tool output schemas compile with Ajv and validate real success/error handler results; AI-created document rejects an injected `aiId` |
|
|
15
|
+
| `npm pack -w packages/office-word`, install tgz to empty temp project | Passed: direct Node imports for `ai-protocol`, `nordox`, `ai`; pack/unpack; packaged Skill CLI created ZIP; installed browser example built and ran |
|
|
16
|
+
|
|
17
|
+
The mock stream test checks that two text deltas are visible before `stream.end`, while `editor.getText()` stays unchanged until `commitStream`. The collaboration fixture uses two separate Y.Doc instances with update relay: a remote insertion remaps an unchanged target, a remote target edit rejects the AI stream, and Undo preserves the remote edit. These are **local transaction tests**, not a real provider deployment. The ZIP tests check signatures, embedded image bytes, unsafe paths, temporary URL rejection and source-change behavior.
|
|
18
|
+
|
|
19
|
+
The local browser example was opened on the dev server. A mock stream visibly inserted text, then the page exported `AI 示例.nordox`; the same page reopened that downloaded file. Independent `unpackNordox` inspection confirmed a version-1 ZIP and its committed text. The example bundled inside the clean-installed tgz was also built, served, and used to stream, export and reopen a second ZIP. Neither run is a desktop-host or real-model test. The release candidate is `packages/office-word/norio-office-rich-text-0.7.1.tgz` and has not been published.
|
|
20
|
+
|
|
21
|
+
The browser example also invokes the public `richtext_apply_patch` handler. Selecting `Select this text` and pressing its mock local-edit command returned `局部编辑已应用`; only that selection changed, while `and run the mock AI stream.` remained. This is a real handler/Bridge transaction with a deterministic mock request, not a model call.
|
|
22
|
+
|
|
23
|
+
A fresh browser check at `http://127.0.0.1:4179/` selected the demo paragraph and started the mock stream. The accessibility tree first showed status `生成中` and only the first arriving text chunk next to the still-present original paragraph; a later observation showed the complete replacement and status `已应用`. This is direct browser evidence that visible increments precede normal completion, not a post-hoc typing animation.
|
|
24
|
+
|
|
25
|
+
The styled browser example also opened reference-only fixtures with unreachable image and video URLs. In both cases the body remained visible and the corresponding node displayed an unavailable/retry state. An embedded-image ZIP opened to a one-pixel blob-backed image with no false unavailable state. This verifies browser media handling, not cross-host transfer or host-managed file download failures.
|
|
26
|
+
|
|
27
|
+
The refreshed tgz was installed again in an empty temp project. Direct imports of `ai-protocol`, `nordox` and `ai` worked without workspace aliases; a native ZIP round-trip succeeded; the installed Skill verifier found all 26 files. A deliberately failing host save callback returned `DOCUMENT_SAVE_FAILED` without its secret-bearing exception text. This is a packaged-consumer check, not merely a source-tree test.
|
|
28
|
+
|
|
29
|
+
Tool output definitions now describe each tool's success data and a shared, strict error result. Context/target errors set `requiresContextRefresh: true`; host save errors do not. Tests compile these schemas with Ajv and validate actual handler results, including both kinds of failure.
|
|
30
|
+
|
|
31
|
+
## Scenario status
|
|
32
|
+
|
|
33
|
+
Legend: **Local** = this repository has deterministic evidence; **Partial** = implemented path exists but the whole scenario is not yet tested; **Host** = requires application/real-provider integration; **Open** = not established by current tests/implementation. A mixed `Local + Host` entry separates the two responsibilities.
|
|
34
|
+
|
|
35
|
+
| ID | Status | Evidence / remaining check |
|
|
36
|
+
| --- | --- | --- |
|
|
37
|
+
| A01 | Partial | Basic native fixture, CLI ZIP creation and browser example edit/export/reopen pass; full Skill-to-model flow is Host. |
|
|
38
|
+
| A02 | Local | Nested stream generates native table, columns and highlight nodes; a mounted editor shows their in-progress preview, opens the generated ZIP and manually edits text inside a column without flattening custom nodes. A separate mounted-editor ZIP round-trip preserves formula LaTeX and code language/display attributes, and code text remains editable. |
|
|
39
|
+
| A03 | Local | Browser mock selection replacement and DOM stream test; external chat focus integration is Host. |
|
|
40
|
+
| A04 | Local | Browser mock cursor insertion and adjacent-text-preserving paragraph insertion test pass. |
|
|
41
|
+
| A05 | Local | TextStyle color and background update retains font, size, bold and adjacent text. |
|
|
42
|
+
| A06 | Local | Highlight block background, table cell background and table theme use their distinct node attributes. |
|
|
43
|
+
| A07 | Local | Discontiguous first/third block transaction leaves middle block unchanged. |
|
|
44
|
+
| A08 | Local | Multi-cell merge/split, column/row insertion, cell background and table theme transaction tests pass; visual table UX remains Host/UI review. |
|
|
45
|
+
| A09 | Local | Two-Y.Doc remote insertion remaps target; solo strict revision policy documented. |
|
|
46
|
+
| A10 | Local | Remote text change, deletion and Mark-only change each reject the captured target before commit. |
|
|
47
|
+
| A11 | Local | Later invalid operation leaves original state unchanged. |
|
|
48
|
+
| A12 | Local | Solo user-AI-user Undo units and collaborative remote-preserving Undo pass. |
|
|
49
|
+
| A13 | Local | Same request replay does not duplicate edit; changed replay conflicts; cancelled/disposed contexts reject late work. |
|
|
50
|
+
| A14 | Local | Context-issued refs, wrong document/context/target rejection and separate-editor spoof test pass; host-side session authorization remains Host. |
|
|
51
|
+
| A15 | Local + Host | Preview-mode write denial, per-context operation/field policy, missing external-reference authorization and an embed request without a byte resolver all reject without saving. Actual host upload/service policy remains Host. |
|
|
52
|
+
| A16 | Partial | Unknown node/attrs, malformed nested image and nullable attributes, invalid hex/RGB colors, malformed patch/stream, ZIP missing asset/version/path/limits tested; exhaustive value rules remain. |
|
|
53
|
+
| A17 | Local | Bytewise Chinese/emoji stream, text selection Mark ranges, table coordinates and cross-style replacement retain surrounding text and start style. |
|
|
54
|
+
| A18 | Local | Move keeps ID; mounted component regenerates IDs on copied and split blocks, then preserves them through ZIP export. Legacy/duplicate IDs normalize before packaging; table split/merge retains unique IDs. AI-supplied identities are rejected in patch, stream and create paths. |
|
|
55
|
+
| A19 | Local + Host | Bridge and create tool reject newly introduced media/link/mention/comment references without explicit host authorization. Positive mock-host cases persist an authorized image, mention and existing comment-thread reference in the native ZIP. Actual host identity/resource callbacks and side effects remain for integration. |
|
|
56
|
+
| A20 | Local + Host | Local two-Y.Doc sync, preview isolation, conflict and Undo pass; real clients/provider/concurrent UX await host. |
|
|
57
|
+
| A21 | Local | Installed tgz Node imported pure entries without DOM and CLI emitted ZIP. |
|
|
58
|
+
| A22 | Local + Host | A complete text-only model JSON response validates against the public tool input Schema and uses the same patch handler; invalid or truncated JSON makes no change. Actual model prompting and transport remain Host. |
|
|
59
|
+
| A23 | Local | Packaged Skill paths/CLI and clean tgz install tested; actual model Skill import is Host. |
|
|
60
|
+
| A24 | Local | Authorized budget reader, cursor continuation, outline and neighboring block summaries tested; long-document performance remains a separate concern. |
|
|
61
|
+
| A25 | Local | Mock replacement and new-document streams show multiple text deltas before end/commit in editor DOM. |
|
|
62
|
+
| A26 | Partial | Selection replace stream DOM test and browser cursor mock; full format-preservation matrix remains. |
|
|
63
|
+
| A27 | Local | Mounted editor displays a table, two columns and a highlight block in the DOM before `stream.end` while committed text stays unchanged. The generated ZIP opens with all three native nodes, and column text remains manually editable. |
|
|
64
|
+
| A28 | Local | Single-byte and deterministic random-chunk UTF-8 Chinese/emoji reconstruction, escaped text, CRLF and truncation tests pass. |
|
|
65
|
+
| A29 | Local | Identical retransmission is idempotent; conflicting duplicate, reorder/gap, invalid UTF-8, event and total-byte limits, and incomplete framing reject without commit. |
|
|
66
|
+
| A30 | Partial | Remote conflict, malformed event, premature commit, stalled-transport abort, async resource-preparation cancel and mounted-component Bridge disposal discard local preview; actual network/lifecycle matrix remains for integration. |
|
|
67
|
+
| A31 | Local | During preview, formal snapshot, contextual read, mounted-component clipboard copy and packaged ZIP use committed content. The component `exportNordox()` excludes draft text until commit, and preview transactions do not emit formal content updates. Host save bookkeeping remains an integration concern. |
|
|
68
|
+
| A32 | Partial | Target conflict and remote unrelated edit tested. DOM fixture confirms preview does not take focus from an external input, and solo-mode unrelated user edits survive strict-revision draft discard; browser scroll interaction remains. |
|
|
69
|
+
| A33 | Local | Single transaction, Undo/Redo, repeated commit and committed-stream discard rejection tested. |
|
|
70
|
+
| A34 | Partial | Animation-frame preview coalescing and under-200ms mock visibility pass. A 1,500-delta single-chunk fixture exercises the incremental decoder/builder path without per-event full-draft copies; long-stream browser scrolling remains unverified. |
|
|
71
|
+
| A35 | Partial | Concurrent drafts stay isolated within one editor and across two editor instances; committing one and discarding the other do not cross documents. Separate-editor context/target spoofing rejects, and resource failure/cancel discards preview. Full browser/media concurrency remains. |
|
|
72
|
+
| A36 | Local + Host | CLI stdin stream and browser AsyncIterable mock run; real model stream adapter is Host. |
|
|
73
|
+
| A37 | Local + Host | True ZIP and browser example open/export/reopen tested without external unzip; independent desktop-host flow is Host. |
|
|
74
|
+
| A38 | Local | Independent image/video/file embed/reference policy tested. Identical embedded bytes under separate resource IDs share one ZIP entry, resolver buffers are captured before later reads, and a mounted component single-export override does not alter its packaging prop. |
|
|
75
|
+
| A39 | Host | One browser opened an embedded-image ZIP and rendered its packaged bytes; cross-host offline image/video/file transfer still requires two host environments. |
|
|
76
|
+
| A40 | Local + Host | External references survive ZIP; browser fixtures show unavailable/retry states for unreachable image and video while retaining body text. Host-managed file download failure remains for integration. |
|
|
77
|
+
| A41 | Local | Changed source and blob-display-URL re-pack both retain correct bytes; mounted component opens an embedded image ZIP and re-exports stable resource ID plus original bytes. |
|
|
78
|
+
| A42 | Local | Embedded-to-reference conversion without durable address rejects in regression test. |
|
|
79
|
+
| A43 | Partial | Embed resolver errors/cancellation reject before ZIP; resolver error detail is sanitized and pack/unpack cancellation is tested. A mock host create callback failure or missing saved document ID returns `DOCUMENT_SAVE_FAILED` without exposing the exception text or reporting success. Atomic existing-file replacement remains Host. |
|
|
80
|
+
| A44 | Local | Unsafe path, duplicate ZIP name, missing asset, unknown version, archive/entry limits and high expansion ratio reject in fixtures. A mounted component also preserves its open document when import rejects a damaged ZIP. |
|
|
81
|
+
| A45 | Partial | Export captures JSON snapshot before async resource reads; mutation-during-pack test retains the captured text, while saved-revision host bookkeeping remains. |
|
|
82
|
+
| A46 | Local | Clean tgz Node import, pack/unpack, packaged CLI and installed-package browser build/stream/export/reopen pass. |
|
|
83
|
+
|
|
84
|
+
## Integration handoff
|
|
85
|
+
|
|
86
|
+
NorioWork or another host must supply `documentId`, session authorization, model/NDJSON transport with an explicit normal-finish signal, resource byte/reference resolver, `authorizeExternalReference` checks for newly AI-introduced media/links/mentions/comment references, durable document creation/save and lifecycle disposal. Register only authorized tool definitions from `getRichTextToolDefinitions()`, bind them through `createRichTextToolHandlers`, and create a context before the user focuses the chat input. The host must still run real-model, actual collaboration-provider, storage-failure, cross-host resource and UI acceptance cases. Do not report these local mocks as those results.
|
|
87
|
+
|
|
88
|
+
**Known gaps before claiming complete task-book acceptance:** A19, A30, A32, A34–A35 and the media/host file scenarios need the additional local checks or host integration described above. In particular, the Skill's online tools are not registered by copying its folder alone. No real model, NorioWork callback, production collaboration provider or cross-host file transfer was tested here.
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# Capability matrix
|
|
2
|
+
|
|
3
|
+
This table describes editor content support separately from AI mutation. The source of truth for legal node/Mark names is `src/document/schema.ts`; `getCapabilities()` exposes their defaults, JSON-Schema-derived value constraints, content rules, modes and host dependencies. The generated JSON Schemas use the same registry. `featureCodes` hides UI affordances; it is **not** an AI write permission.
|
|
4
|
+
|
|
5
|
+
| Capability | Native mapping | AI mutation path | Dependency or limit |
|
|
6
|
+
| --- | --- | --- | --- |
|
|
7
|
+
| Plain text, bold/italic/underline/strike/code | `paragraph`, text Marks | `replaceText`, `setMarks`, `unsetMarks` | Selected text or scoped cursor |
|
|
8
|
+
| Font, size, foreground/background | `textStyle` Mark attrs | `setMarks` | Registered attrs only; not arbitrary CSS |
|
|
9
|
+
| Heading, alignment, indentation | `heading`, `paragraph` attrs | `transformBlocks`, `setNodeAttributes` | Single block transformation; no arbitrary multi-block wrap |
|
|
10
|
+
| Bullet/ordered/task lists | `bulletList`, `orderedList`, `taskList`, item nodes | `insertContent`, `transformBlocks` | Single-block wrap/unwrap; existing structured fragments accepted |
|
|
11
|
+
| Quote | `blockquote` | `insertContent`, `transformBlocks` | Single-block wrap/unwrap |
|
|
12
|
+
| Links | `link` Mark, `linkBlock` | `setMarks`, `insertContent`, node attrs | New AI URL requires `authorizeExternalReference` |
|
|
13
|
+
| Tables, themes, cells | `table`, row/cell/header attrs | `insertContent`, `tableOperation` | Row/column changes, merge/split, cell content/background, table theme; multi-cell merge uses group target |
|
|
14
|
+
| Columns | `columnsBlock`, `columnsColumn`, `widths` | `insertContent`, `setNodeAttributes` | Width count validated against columns |
|
|
15
|
+
| Highlight/code/formula/countdown | Native custom nodes | `insertContent`, `setNodeAttributes` | Countdown reminder side effect not automatic |
|
|
16
|
+
| Divider | `horizontalRule` | `insertContent`, node attrs | Native style attrs |
|
|
17
|
+
| Image/video/file | `imageBlock`, `videoBlock`, `localFileBlock` | `insertContent`, node attrs, Nordox pack | New AI references require host authorization; byte resolver required to embed new external media |
|
|
18
|
+
| Mention | `mention` | `insertContent` | Host must resolve and authorize identity before AI insertion |
|
|
19
|
+
| Comment | `commentMark` references a thread | Preserve/read Mark; insert only an authorized existing thread reference | Thread data is host-owned; AI does not create a thread |
|
|
20
|
+
| Watermark | Component visual config | None | Not document content |
|
|
21
|
+
| Selection types | cursor, textRange, node, blockSet, tableCells, none | Bridge context capture | `none` cannot become whole-document authority |
|
|
22
|
+
| Streaming | create, insert, replace text/fragment, operations | NDJSON decoder, builder, local preview, atomic commit | Model transport and normal-finish signal owned by host |
|
|
23
|
+
| Native file | ZIP `.nordox` version 1 | pack/unpack/open/export | Browser object URLs are temporary, never persisted |
|
|
24
|
+
|
|
25
|
+
The shared node and Mark registry is `src/document/schema.ts`; `src/ai-protocol/validation.ts` applies its semantic rules, and `src/ai/executor.ts` maps authorized operations into one transaction. The table below gives the concrete source and test location for each capability above. A test named here proves the local protocol/component behavior, not a real host service or online permission decision.
|
|
26
|
+
|
|
27
|
+
| Capability | Source location | Local evidence |
|
|
28
|
+
| --- | --- | --- |
|
|
29
|
+
| Text, font, heading, alignment and indentation | `src/document/schema.ts`, `src/ai/executor.ts` | `tests/ai-executor.test.mjs` Mark merge, cross-style replacement and block transform; `tests/component-ai.test.mjs` clipboard and editing |
|
|
30
|
+
| Lists, task lists and quotes | `src/document/schema.ts`, `src/ai/executor.ts` | `tests/ai-executor.test.mjs` list/quote transform and scoped insertion |
|
|
31
|
+
| Links | `src/document/nodes/link-block.ts`, `src/ai-protocol/references.ts` | `tests/collaboration.test.mjs` unauthorized external link rejection |
|
|
32
|
+
| Tables and themes | `src/document/nodes/themed-table.ts`, `src/document/nodes/table-cells.ts`, `src/ai/executor.ts` | `tests/ai-executor.test.mjs` atomic row/column/merge/split/theme operations; `tests/component-ai.test.mjs` streamed table |
|
|
33
|
+
| Columns | `src/document/nodes/columns-block.ts`, `src/ai/executor.ts` | `tests/protocol.test.mjs` structured stream; `tests/component-ai.test.mjs` preview, ZIP reopen and manual edit |
|
|
34
|
+
| Highlight, code and formula | `src/document/nodes/highlight-block.ts`, `src/document/nodes/office-code-block.ts`, `src/document/nodes/formula-block.ts` | `tests/component-ai.test.mjs` custom-node preview and native ZIP round-trip; `tests/ai-executor.test.mjs` highlight attributes |
|
|
35
|
+
| Date and countdown | Displayed dates are paragraph text; `src/document/nodes/countdown-block.ts` is the timer node | `packages/skills/norio-rich-text/examples/custom-blocks-document.json` is Schema-checked by the Skill's `scripts/check-package.mjs`; no system reminder is scheduled |
|
|
36
|
+
| Divider | `src/document/schema.ts`, `src/ai/executor.ts` | `tests/protocol.test.mjs` shared Schema fixture; host visual styling is not asserted |
|
|
37
|
+
| Image, video and file | `src/document/nodes/image-block.ts`, `src/document/nodes/video-block.ts`, `src/document/nodes/local-file-block.ts`, `src/nordox/index.ts` | `tests/protocol.test.mjs` independent embed/reference strategies; `tests/component-ai.test.mjs` image round-trip; Skill media example round-trip |
|
|
38
|
+
| Mention and comment | `src/document/nodes/mention.ts`, `src/ai-protocol/references.ts`, `src/ai/bridge.ts` | `tests/collaboration.test.mjs` external-reference authorization; host identity and thread callbacks remain required |
|
|
39
|
+
| Watermark and UI controls | `src/components/RichTextEditor.vue`, `src/feature-codes.ts` | No AI body operation; existing editor UI regression is an application check |
|
|
40
|
+
| Selection and streaming | `src/ai/bridge.ts`, `src/ai-protocol/stream.ts`, `src/ai/consume-stream.ts` | `tests/collaboration.test.mjs` selection, Yjs, preview and transport; `tests/component-ai.test.mjs` mounted preview and disposal |
|
|
41
|
+
| Native file and resources | `src/nordox/index.ts`, `src/components/RichTextEditor.vue` | `tests/protocol.test.mjs` ZIP/error limits; `tests/component-ai.test.mjs` open/export; `tests/skill-cli.test.mjs` CLI |
|
|
42
|
+
|
|
43
|
+
Execution permits only structured operations and context-issued `targetRef`s. The Bridge rejects preview-mode writes, stale/deleted targets, expired contexts, unauthorized operation names and newly introduced external references not approved by the host. A host can also set per-context `writePolicy` for Mark/node attributes and table actions; hide/show controls alone do not provide authorization. Browser-only native UI commands are not all expressible as one AI operation; the table above names the supported operation path rather than promising every UI variation.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
# Compatibility and migration
|
|
2
|
+
|
|
3
|
+
- Package: `@norio-office/rich-text@0.7.1`; document Schema version `1`, patch/stream protocol version `1`, Nordox format version `1`. Node 20+ is supported for `ai-protocol`, `nordox` and the Skill CLI. Vue/Tiptap peer versions remain those in `package.json`.
|
|
4
|
+
- Existing bare Tiptap JSON remains a valid import/intermediate format. `.nordox` is an actual ZIP with `manifest.json`, `document.json`, and optional `assets/`; it is not renamed JSON. Unknown future versions fail with `NORDOX_VERSION_UNSUPPORTED`; no implicit destructive migration occurs.
|
|
5
|
+
- Old blocks without `aiId` are assigned IDs on load. Copied blocks with duplicate IDs receive new ones; a move keeps its ID. `migrateRichTextDocument(json, 'legacy-json')` exposes the same explicit normalization for bare JSON, and `packNordox` uses it without mutating the caller. Unknown Schema versions return `SCHEMA_VERSION_UNSUPPORTED`. The identity migration is not a user edit or normal change event.
|
|
6
|
+
- Single-user contexts use strict revision matching: **any** intervening document change requires a fresh context. Yjs contexts use the current collaboration binding's relative positions and content fingerprint; unrelated remote edits may move a target, but edits to the target conflict. The preview is a local decoration and is not broadcast.
|
|
7
|
+
- `assetPackaging` is optional. New resources default to reference; resources loaded as embedded remain embedded unless an export explicitly changes that kind. An embedded-to-reference conversion without a reliable address fails. ZIP pack/unpack includes limits on archive bytes, entries, individual resources, total extraction and compression ratio.
|
|
8
|
+
- Comments are host-managed records and watermark is a visual setting, not body JSON. Mentions and media still need host callbacks/authorization. The Bridge does not create comment threads, upload resources or schedule countdown reminders. Hiding a UI feature via `featureCodes` is not an AI authorization policy; hosts must pass an AI `policy` and restrict tools they expose.
|
|
9
|
+
- Existing `v-model`, single-user editing and Yjs providers do not change their integration contract. The browser example shows mock streaming only. Real model, NorioWork, storage, cross-host transfer and remote-provider checks are integration work after this package is installed.
|
package/docs/icons.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# 图标素材与统一组件
|
|
2
|
+
|
|
3
|
+
2026-10-14 确认的规则:
|
|
4
|
+
|
|
5
|
+
| 用途 | 用户提供素材的位置 | 组件内使用副本 | 统一组件 |
|
|
6
|
+
| --- | --- | --- | --- |
|
|
7
|
+
| 彩色图标 | 工程根目录 `icon/color/` | `src/assets/icons/color/` | `OfficeColorIcon` |
|
|
8
|
+
| 非彩色图标 | 工程根目录 `icon/text/` | `src/assets/icons/mono/` | `OfficeIcon` |
|
|
9
|
+
|
|
10
|
+
`icon/` 是接收素材的目录,不是运行时资源目录。直接放在根目录的文件只是临时素材;接入前先归类,再复制到对应组件的资源库。`src/icons.ts` 自动将组件内 SVG 注册为文件名对应的图标名称。
|
|
11
|
+
|
|
12
|
+
业务界面通过名称使用图标,不直接导入素材路径,也不自行写 `<img>` 或插入原始 SVG。保留用户提供图标的颜色和形状,不擅自把彩色图标转换成普通图标。
|
|
13
|
+
|
|
14
|
+
```vue
|
|
15
|
+
<OfficeColorIcon name="ai-mark" :size="17" background-color="transparent" />
|
|
16
|
+
<OfficeIcon name="close" :size="16" background-color="transparent" />
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
编辑器 AI 目标按钮和蓝色标记浮签都使用彩色图标 `ai-mark`。浮签由 ProseMirror 原生 DOM 管理,其图标区域挂载同一个 `OfficeColorIcon`,浮签销毁时卸载组件。
|
|
20
|
+
|
|
21
|
+
素材目录的 `text` 和内部资源目录的 `mono` 各司其职,不批量改名,也不移动与当前接入无关的素材。历史文档中的 `material/icon`、`material/color-icon` 是旧素材目录记录,当前新增素材按上表处理。
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
<script setup lang="ts">
|
|
2
|
+
import { onBeforeUnmount, onMounted, ref } from 'vue'
|
|
3
|
+
import type { JSONContent } from '@tiptap/core'
|
|
4
|
+
import { RichTextEditor, type RichTextEditorInstance } from '@norio-office/rich-text'
|
|
5
|
+
import { consumeRichTextAiStream, createRichTextAiBridge, createRichTextToolHandlers, type RichTextAiBridge, type RichTextAiTarget, type RichTextToolHandlers } from '@norio-office/rich-text/ai'
|
|
6
|
+
|
|
7
|
+
const editor = ref<RichTextEditorInstance | null>(null)
|
|
8
|
+
const content = ref<JSONContent>({ type: 'doc', content: [{ type: 'paragraph', content: [{ type: 'text', text: 'Select this text and run the mock AI stream.' }] }] })
|
|
9
|
+
const mode = ref<'edit' | 'preview'>('edit')
|
|
10
|
+
const status = ref('就绪')
|
|
11
|
+
const busy = ref(false)
|
|
12
|
+
const activeTarget = ref<RichTextAiTarget | null>(null)
|
|
13
|
+
let bridge: RichTextAiBridge | null = null
|
|
14
|
+
let handlers: RichTextToolHandlers | null = null
|
|
15
|
+
let unsubscribe: (() => void) | null = null
|
|
16
|
+
let requestAbort: AbortController | null = null
|
|
17
|
+
|
|
18
|
+
onMounted(() => {
|
|
19
|
+
if (!editor.value) return
|
|
20
|
+
bridge = createRichTextAiBridge(editor.value, { documentId: 'browser-example', policy: { allowWholeDocument: false } })
|
|
21
|
+
unsubscribe = bridge.onEvent(event => {
|
|
22
|
+
if (event.type !== 'ai-target-change') return
|
|
23
|
+
activeTarget.value = event.target
|
|
24
|
+
if (!event.target && event.reason !== 'commit') requestAbort?.abort()
|
|
25
|
+
})
|
|
26
|
+
handlers = createRichTextToolHandlers(bridge, {
|
|
27
|
+
async createDocument({ bytes }) {
|
|
28
|
+
return { documentId: `local-${bytes.byteLength}` }
|
|
29
|
+
},
|
|
30
|
+
})
|
|
31
|
+
// A real host registers these handlers with its model/runtime rather than invoking them from body text.
|
|
32
|
+
void handlers.richtext_get_capabilities({})
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
onBeforeUnmount(() => { requestAbort?.abort(); unsubscribe?.(); bridge?.dispose(); handlers = null })
|
|
36
|
+
|
|
37
|
+
function clearRange() {
|
|
38
|
+
if (activeTarget.value) bridge?.clearAiTarget({ targetId: activeTarget.value.targetId, reason: 'host-close' })
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function runMockToolPatch() {
|
|
42
|
+
if (!bridge || !handlers || !activeTarget.value || busy.value || mode.value !== 'edit') return
|
|
43
|
+
busy.value = true
|
|
44
|
+
try {
|
|
45
|
+
const requestId = crypto.randomUUID()
|
|
46
|
+
const edit = bridge.createEditContext({ requestId, instruction: 'Rewrite the selected text.', targetId: activeTarget.value.targetId })
|
|
47
|
+
if (edit.selection.kind !== 'textRange') {
|
|
48
|
+
status.value = '请先选择一段文字'
|
|
49
|
+
return
|
|
50
|
+
}
|
|
51
|
+
const result = await handlers.richtext_apply_patch({
|
|
52
|
+
protocolVersion: 1, documentId: 'browser-example', requestId,
|
|
53
|
+
contextId: edit.contextId, baseRevision: edit.baseRevision,
|
|
54
|
+
operations: [{ type: 'replaceText', targetRef: edit.targetRefs[0], text: '这段文字已通过 AI 工具局部改写。' }],
|
|
55
|
+
})
|
|
56
|
+
status.value = result.ok ? result.data.changed ? '局部编辑已应用' : '无变化' : result.error.message
|
|
57
|
+
} catch (error) {
|
|
58
|
+
status.value = error instanceof Error ? error.message : '执行失败'
|
|
59
|
+
} finally {
|
|
60
|
+
busy.value = false
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function runMockStream() {
|
|
65
|
+
if (!bridge || !activeTarget.value || busy.value || mode.value !== 'edit') return
|
|
66
|
+
busy.value = true
|
|
67
|
+
requestAbort = new AbortController()
|
|
68
|
+
try {
|
|
69
|
+
const requestId = crypto.randomUUID()
|
|
70
|
+
const edit = bridge.createEditContext({ requestId, instruction: 'Generate or revise the selection.', targetId: activeTarget.value.targetId })
|
|
71
|
+
const streamMode = edit.selection.kind === 'textRange' ? 'replaceText' : 'insertContent'
|
|
72
|
+
const { streamId } = bridge.beginStream({ contextId: edit.contextId, requestId, mode: streamMode, targetRef: edit.targetRefs[0] })
|
|
73
|
+
let seq = 0
|
|
74
|
+
async function* chunks() {
|
|
75
|
+
const event = (type: string, payload: Record<string, unknown>) => `${JSON.stringify({ protocolVersion: 1, streamId, seq: ++seq, type, payload })}\n`
|
|
76
|
+
if (streamMode === 'insertContent') yield event('node.open', { nodeRef: 'new-paragraph', nodeType: 'paragraph' })
|
|
77
|
+
for (const text of ['这是一段', '真正逐步到达的', ' AI 示例内容。']) {
|
|
78
|
+
await new Promise(resolve => setTimeout(resolve, 180))
|
|
79
|
+
yield event('text.delta', { nodeRef: streamMode === 'replaceText' ? 'replacement' : 'new-paragraph', text })
|
|
80
|
+
}
|
|
81
|
+
if (streamMode === 'insertContent') yield event('node.close', { nodeRef: 'new-paragraph' })
|
|
82
|
+
yield event('stream.end', {})
|
|
83
|
+
}
|
|
84
|
+
status.value = '生成中'
|
|
85
|
+
const result = await consumeRichTextAiStream(bridge, chunks(), { streamId, signal: requestAbort.signal })
|
|
86
|
+
status.value = 'document' in result ? '文档已生成' : result.changed ? '已应用' : '无变化'
|
|
87
|
+
} catch (error) {
|
|
88
|
+
status.value = error instanceof Error ? error.message : '执行失败'
|
|
89
|
+
} finally {
|
|
90
|
+
requestAbort = null
|
|
91
|
+
busy.value = false
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async function openFile(event: Event) {
|
|
96
|
+
const file = (event.target as HTMLInputElement).files?.[0]
|
|
97
|
+
if (!file || !editor.value) return
|
|
98
|
+
try {
|
|
99
|
+
await editor.value.openNordox(file)
|
|
100
|
+
status.value = `已打开 ${file.name}`
|
|
101
|
+
} catch (error) {
|
|
102
|
+
status.value = error instanceof Error ? error.message : '打开失败'
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async function download() {
|
|
107
|
+
if (!editor.value) return
|
|
108
|
+
try {
|
|
109
|
+
const blob = await editor.value.exportNordox({ assetPackaging: { images: 'reference' } })
|
|
110
|
+
const url = URL.createObjectURL(blob)
|
|
111
|
+
const link = document.createElement('a')
|
|
112
|
+
link.href = url
|
|
113
|
+
link.download = 'AI 示例.nordox'
|
|
114
|
+
link.click()
|
|
115
|
+
setTimeout(() => URL.revokeObjectURL(url), 1000)
|
|
116
|
+
status.value = '已导出'
|
|
117
|
+
} catch (error) {
|
|
118
|
+
status.value = error instanceof Error ? error.message : '导出失败'
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
</script>
|
|
122
|
+
|
|
123
|
+
<template>
|
|
124
|
+
<div class="example">
|
|
125
|
+
<header class="controls">
|
|
126
|
+
<strong>Norio AI 编辑示例</strong>
|
|
127
|
+
<button type="button" :disabled="busy || mode !== 'edit'" @click="runMockStream">运行模拟流</button>
|
|
128
|
+
<button type="button" :disabled="busy || mode !== 'edit'" @click="runMockToolPatch">运行模拟局部编辑</button>
|
|
129
|
+
<label class="file-input">打开 .nordox<input type="file" accept=".nordox" @change="openFile" /></label>
|
|
130
|
+
<button type="button" @click="download">导出 .nordox</button>
|
|
131
|
+
<label>模式 <select v-model="mode"><option value="edit">编辑</option><option value="preview">预览</option></select></label>
|
|
132
|
+
<span v-if="activeTarget" class="target-summary">{{ activeTarget.summary }} · {{ activeTarget.previewText || '光标位置' }}
|
|
133
|
+
<button type="button" title="取消 AI 编辑范围" aria-label="取消 AI 编辑范围" @click="clearRange">×</button>
|
|
134
|
+
</span>
|
|
135
|
+
<span class="status" role="status">{{ status }}</span>
|
|
136
|
+
</header>
|
|
137
|
+
<RichTextEditor ref="editor" v-model="content" :mode="mode" :show-ai-target-button="true" document-name="AI 示例" />
|
|
138
|
+
</div>
|
|
139
|
+
</template>
|
|
140
|
+
|
|
141
|
+
<style scoped>
|
|
142
|
+
:global(body) { margin: 0; font-family: Arial, sans-serif; }
|
|
143
|
+
.example { min-height: 100vh; background: #fff; }
|
|
144
|
+
.controls { display: flex; align-items: center; gap: 12px; min-height: 52px; padding: 0 16px; border-bottom: 1px solid #d7dee8; color: #17243a; flex-wrap: wrap; }
|
|
145
|
+
.controls button, .controls select, .file-input { border: 1px solid #b9c6d8; background: #fff; color: #17243a; padding: 6px 9px; cursor: pointer; font: inherit; }
|
|
146
|
+
.controls button:disabled { opacity: .5; cursor: default; }
|
|
147
|
+
.file-input input { display: none; }
|
|
148
|
+
.status { margin-left: auto; color: #53667d; font-size: 13px; }
|
|
149
|
+
.target-summary { display: inline-flex; align-items: center; gap: 6px; max-width: 320px; overflow: hidden; white-space: nowrap; color: #1769e8; font-size: 13px; }
|
|
150
|
+
.target-summary button { padding: 0 5px; }
|
|
151
|
+
</style>
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="zh-CN">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="UTF-8" />
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
6
|
+
<title>Norio Rich Text AI Example</title>
|
|
7
|
+
</head>
|
|
8
|
+
<body>
|
|
9
|
+
<div id="app"></div>
|
|
10
|
+
<script type="module" src="/main.ts"></script>
|
|
11
|
+
</body>
|
|
12
|
+
</html>
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { dirname, resolve } from 'node:path'
|
|
2
|
+
import { fileURLToPath } from 'node:url'
|
|
3
|
+
|
|
4
|
+
import vue from '@vitejs/plugin-vue'
|
|
5
|
+
import { defineConfig } from 'vite'
|
|
6
|
+
|
|
7
|
+
const root = dirname(fileURLToPath(import.meta.url))
|
|
8
|
+
|
|
9
|
+
export default defineConfig({
|
|
10
|
+
root,
|
|
11
|
+
plugins: [vue()],
|
|
12
|
+
server: { port: 4179 },
|
|
13
|
+
build: { outDir: resolve(root, 'dist'), emptyOutDir: true },
|
|
14
|
+
})
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { open, readFile } from 'node:fs/promises'
|
|
2
|
+
|
|
3
|
+
import { getRichTextToolDefinitions, validateRichTextDocument } from '@norio-office/rich-text/ai-protocol'
|
|
4
|
+
import { packNordox, unpackNordox } from '@norio-office/rich-text/nordox'
|
|
5
|
+
|
|
6
|
+
const [input, output] = process.argv.slice(2)
|
|
7
|
+
if (!input || !output) {
|
|
8
|
+
process.stderr.write('Usage: node examples/ai/node.mjs draft.json result.nordox\n')
|
|
9
|
+
process.exitCode = 1
|
|
10
|
+
} else {
|
|
11
|
+
try {
|
|
12
|
+
const draft = JSON.parse(await readFile(input, 'utf8'))
|
|
13
|
+
const validation = validateRichTextDocument(draft)
|
|
14
|
+
if (!validation.valid) throw new Error(JSON.stringify(validation.errors))
|
|
15
|
+
const bytes = await packNordox(validation.document, { title: 'AI draft' })
|
|
16
|
+
const confirmed = await unpackNordox(bytes)
|
|
17
|
+
const file = await open(output, 'wx')
|
|
18
|
+
try { await file.writeFile(bytes) }
|
|
19
|
+
finally { await file.close() }
|
|
20
|
+
process.stdout.write(`${JSON.stringify({
|
|
21
|
+
output, format: confirmed.manifest.format, bytes: bytes.byteLength,
|
|
22
|
+
availableTools: getRichTextToolDefinitions().map(tool => tool.name),
|
|
23
|
+
})}\n`)
|
|
24
|
+
} catch (error) {
|
|
25
|
+
process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`)
|
|
26
|
+
process.exitCode = 1
|
|
27
|
+
}
|
|
28
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@norio-office/rich-text",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"description": "A reusable Vue 3 rich text editor component built with Tiptap 3.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.umd.cjs",
|
|
@@ -12,12 +12,25 @@
|
|
|
12
12
|
"import": "./dist/index.js",
|
|
13
13
|
"require": "./dist/index.umd.cjs"
|
|
14
14
|
},
|
|
15
|
+
"./ai-protocol": {
|
|
16
|
+
"types": "./dist/ai-protocol/index.d.ts",
|
|
17
|
+
"import": "./dist/ai-protocol/index.js"
|
|
18
|
+
},
|
|
19
|
+
"./nordox": {
|
|
20
|
+
"types": "./dist/nordox/index.d.ts",
|
|
21
|
+
"import": "./dist/nordox/index.js"
|
|
22
|
+
},
|
|
23
|
+
"./ai": {
|
|
24
|
+
"types": "./dist/ai/index.d.ts",
|
|
25
|
+
"import": "./dist/ai/index.js"
|
|
26
|
+
},
|
|
15
27
|
"./style.css": "./dist/style.css"
|
|
16
28
|
},
|
|
17
29
|
"files": [
|
|
18
30
|
"dist",
|
|
19
31
|
"README.md",
|
|
20
32
|
"docs",
|
|
33
|
+
"examples/ai",
|
|
21
34
|
"yjs",
|
|
22
35
|
"LICENSE"
|
|
23
36
|
],
|
|
@@ -65,6 +78,7 @@
|
|
|
65
78
|
"yjs": "^13.6.30"
|
|
66
79
|
},
|
|
67
80
|
"dependencies": {
|
|
81
|
+
"fflate": "^0.8.3",
|
|
68
82
|
"html2canvas": "^1.4.1",
|
|
69
83
|
"jspdf": "^4.2.1",
|
|
70
84
|
"katex": "^0.16.44",
|