@astryx-vue/richtext 0.0.0-stage → 0.5.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/LICENSE +21 -0
- package/README.md +62 -2
- package/css.d.ts +3 -0
- package/dist/index.d.ts +394 -0
- package/dist/index.js +2288 -0
- package/dist/markdown.d.ts +2 -0
- package/dist/markdown.js +2 -0
- package/dist/markdownSerializers-BLgqlNe3.d.ts +88 -0
- package/dist/markdownSerializers-ByYsTuIA.js +2492 -0
- package/package.json +140 -3
- package/richtext.css +5 -0
- package/styles/richtext-document.css +269 -0
- package/styles/richtext-editor.css +117 -0
- package/styles/richtext-toolbar.css +54 -0
- package/styles/richtext-view.css +23 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,2288 @@
|
|
|
1
|
+
import { a as createRichTextExtension, c as $getTaskState, d as DEFAULT_NODES, f as $firstSelectedText, g as setRichTextExtensionNodeDecorator, h as RichTextExtensionNode, i as RichTextExtensionError, l as $setTaskState, m as $selectedExtensionNodesOnly, n as markdownToEditorStateJSON, o as pluginsOf, p as $isRichTextExtensionNode, r as $exportMarkdownKeepingSource, s as DEFAULT_TRANSFORMERS, t as editorStateJSONToMarkdown, u as registerTaskListEditing } from "./markdownSerializers-ByYsTuIA.js";
|
|
2
|
+
import { Fragment, Teleport, computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createTextVNode, createVNode, defineComponent, h, inject, mergeProps, nextTick, onBeforeUnmount, onMounted, openBlock, provide, renderList, renderSlot, resolveDynamicComponent, shallowRef, toDisplayString, unref, useAttrs, useId, useTemplateRef, watch, watchEffect, withCtx, withModifiers } from "vue";
|
|
3
|
+
import { HorizontalRuleExtension, TabIndentationExtension, buildEditorFromExtensions, defineExtension } from "@lexical/extension";
|
|
4
|
+
import { HistoryExtension } from "@lexical/history";
|
|
5
|
+
import { $createLinkNode, $isLinkNode, LinkExtension, TOGGLE_LINK_COMMAND, createLinkMatcherWithRegExp, registerAutoLink } from "@lexical/link";
|
|
6
|
+
import { $isListItemNode, $isListNode, CheckListExtension, INSERT_ORDERED_LIST_COMMAND, INSERT_UNORDERED_LIST_COMMAND, ListNode } from "@lexical/list";
|
|
7
|
+
import { registerMarkdownShortcuts } from "@lexical/markdown";
|
|
8
|
+
import { $createHeadingNode, $createQuoteNode, $isHeadingNode, $isQuoteNode, RichTextExtension } from "@lexical/rich-text";
|
|
9
|
+
import { $isTableCellNode, $isTableNode, $isTableRowNode, TableExtension, TableNode } from "@lexical/table";
|
|
10
|
+
import { $createNodeSelection, $createParagraphNode, $createTextNode, $getNodeByKey, $getRoot, $getSelection, $isElementNode, $isNodeSelection, $isParagraphNode, $isRangeSelection, $isTextNode, $setSelection, BLUR_COMMAND, CAN_REDO_COMMAND, CAN_UNDO_COMMAND, CLICK_COMMAND, COMMAND_PRIORITY_CRITICAL, COMMAND_PRIORITY_HIGH, COMMAND_PRIORITY_LOW, COMMAND_PRIORITY_NORMAL, FORMAT_TEXT_COMMAND, HISTORY_MERGE_TAG, IS_APPLE, KEY_ARROW_DOWN_COMMAND, KEY_DOWN_COMMAND, KEY_ESCAPE_COMMAND, KEY_TAB_COMMAND, REDO_COMMAND, SELECTION_CHANGE_COMMAND, TEXT_TYPE_TO_FORMAT, TextNode, UNDO_COMMAND, configExtension, isExactShortcutMatch, mergeRegister } from "lexical";
|
|
11
|
+
import { $isCodeNode, CodeNode } from "@lexical/code";
|
|
12
|
+
import { $dfs, $getNearestNodeOfType, addClassNamesToElement, mergeRegister as mergeRegister$1, removeClassNamesFromElement } from "@lexical/utils";
|
|
13
|
+
import { parseInlineAst, parseMarkdownAst } from "@astryx-vue/core/Markdown/parser";
|
|
14
|
+
import { $generateHtmlFromNodes, DOMRenderExtension, domOverride } from "@lexical/html";
|
|
15
|
+
import { Button, CheckboxInput, Dialog, DialogHeader, Divider, Field, HIGHLIGHTED_TOKEN_TYPES, HStack, Icon, IconButton, Layout, LayoutContent, LayoutFooter, Selector, TextInput, ToggleButton, Toolbar, VisuallyHidden, tokenize, useAstryxMessages, useCopyToClipboard, useSemanticIcon } from "@astryx-vue/core";
|
|
16
|
+
import { MarkdownPluginNodeRenderer } from "@astryx-vue/core/Markdown/plugin-renderer";
|
|
17
|
+
import "../styles/richtext-document.css";
|
|
18
|
+
import "../styles/richtext-editor.css";
|
|
19
|
+
import { $setBlocksType } from "@lexical/selection";
|
|
20
|
+
import "../styles/richtext-toolbar.css";
|
|
21
|
+
import "../styles/richtext-view.css";
|
|
22
|
+
//#region src/editor/context.ts
|
|
23
|
+
/** 编辑器根组件把 Lexical 编辑器挂在这个键上,工具栏和插件组件从它取。 */
|
|
24
|
+
const editorKey = Symbol("astryx-richtext-editor");
|
|
25
|
+
/** 读当前的 Lexical 编辑器。只能在 `<RichTextEditor>` 或 `<RichTextView>` 里面用。 */
|
|
26
|
+
function useLexicalEditor() {
|
|
27
|
+
const provided = inject(editorKey, null);
|
|
28
|
+
const editor = typeof provided === "function" ? provided() : provided;
|
|
29
|
+
if (editor === null) throw new Error("useLexicalEditor() 必须在 <RichTextEditor> 或 <RichTextView> 里调用,并且编辑器已经建好");
|
|
30
|
+
return editor;
|
|
31
|
+
}
|
|
32
|
+
//#endregion
|
|
33
|
+
//#region src/editor/blockExit.ts
|
|
34
|
+
function isCodeOrTable(node) {
|
|
35
|
+
return node != null && ($isCodeNode(node) || $isTableNode(node));
|
|
36
|
+
}
|
|
37
|
+
function shouldInsertAfterBlock(node) {
|
|
38
|
+
return isCodeOrTable(node) && (node.getNextSibling() === null || isCodeOrTable(node.getNextSibling()));
|
|
39
|
+
}
|
|
40
|
+
function isAtEnd(point, block) {
|
|
41
|
+
const last = block.getLastDescendant();
|
|
42
|
+
if ($isTextNode(last)) return point.key === last.getKey() && point.offset === last.getTextContentSize();
|
|
43
|
+
const element = $isElementNode(last) ? last : last?.getParent();
|
|
44
|
+
return element != null && point.key === element.getKey() && point.offset === element.getChildrenSize();
|
|
45
|
+
}
|
|
46
|
+
function registerBlockExit(editor) {
|
|
47
|
+
return editor.registerCommand(KEY_ARROW_DOWN_COMMAND, (event) => {
|
|
48
|
+
const selection = $getSelection();
|
|
49
|
+
if (!$isRangeSelection(selection) || !selection.isCollapsed()) return false;
|
|
50
|
+
const anchor = selection.anchor.getNode();
|
|
51
|
+
const block = [anchor, ...anchor.getParents()].find(shouldInsertAfterBlock);
|
|
52
|
+
const parent = block?.getParent();
|
|
53
|
+
if (!block || !parent || !isAtEnd(selection.anchor, block)) return false;
|
|
54
|
+
const paragraph = $createParagraphNode();
|
|
55
|
+
parent.splice(block.getIndexWithinParent() + 1, 0, [paragraph]);
|
|
56
|
+
paragraph.select();
|
|
57
|
+
event.preventDefault();
|
|
58
|
+
return true;
|
|
59
|
+
}, COMMAND_PRIORITY_HIGH);
|
|
60
|
+
}
|
|
61
|
+
//#endregion
|
|
62
|
+
//#region src/editor/plugins/nextFrame.ts
|
|
63
|
+
/**
|
|
64
|
+
* 把一件事排到下一帧再做,同一帧里排多次只做一次。返回 `{ schedule, cancel }`。
|
|
65
|
+
*
|
|
66
|
+
* 量位置、改样式这类事要等浏览器排完版才有意义,而且编辑器一次更新会触发很多次监听,
|
|
67
|
+
* 合并到每帧一次才不浪费。服务端没有 `requestAnimationFrame`,这时什么也不做:
|
|
68
|
+
* 服务端只渲染编辑器的外框,这些事本来就是浏览器里才需要的。
|
|
69
|
+
*/
|
|
70
|
+
function createFrameScheduler(task) {
|
|
71
|
+
let frame = 0;
|
|
72
|
+
return {
|
|
73
|
+
schedule() {
|
|
74
|
+
if (frame !== 0 || typeof requestAnimationFrame === "undefined") return;
|
|
75
|
+
frame = requestAnimationFrame(() => {
|
|
76
|
+
frame = 0;
|
|
77
|
+
task();
|
|
78
|
+
});
|
|
79
|
+
},
|
|
80
|
+
cancel() {
|
|
81
|
+
if (frame !== 0 && typeof cancelAnimationFrame !== "undefined") cancelAnimationFrame(frame);
|
|
82
|
+
frame = 0;
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
//#endregion
|
|
87
|
+
//#region src/editor/plugins/tableColumnFloor.ts
|
|
88
|
+
const TABLE_COLUMN_MIN_CH = 4;
|
|
89
|
+
const TABLE_COLUMN_MAX_CH = 24;
|
|
90
|
+
const TABLE_COLUMN_TARGET_LINES = 2;
|
|
91
|
+
const TABLE_HEADER_ONE_LINE_MAX_CH = 20;
|
|
92
|
+
/**
|
|
93
|
+
* 每一列的最小宽度(单位 `ch`),按每个单元格的字数算,表头行在最前:
|
|
94
|
+
* 最长的格子最多折成两行,表头尽量一行读完(到上限为止),每一列都落在上下限之间。
|
|
95
|
+
*/
|
|
96
|
+
function tableColumnFloors(rows) {
|
|
97
|
+
const [header, ...body] = rows;
|
|
98
|
+
if (header === void 0) return [];
|
|
99
|
+
return header.map((headerLength, column) => {
|
|
100
|
+
const longest = Math.max(headerLength, ...body.map((row) => row[column] ?? 0));
|
|
101
|
+
const bodyFloor = Math.ceil(longest / TABLE_COLUMN_TARGET_LINES);
|
|
102
|
+
return Math.min(TABLE_COLUMN_MAX_CH, Math.max(TABLE_COLUMN_MIN_CH, bodyFloor, Math.min(headerLength, TABLE_HEADER_ONE_LINE_MAX_CH)));
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* 每次更新之后,给每张顶层表格的表头单元格设上这一列的最小宽度,让它跟着编辑走。
|
|
107
|
+
*
|
|
108
|
+
* 和 core 的 Markdown 表格列宽一致:浏览器的自动表格布局本来就让每列至少和最长的词一样宽,
|
|
109
|
+
* 但正文列里最长的词很短,窄表格会一行只放一个词。这里让一列最长的格子折成大约两行,
|
|
110
|
+
* 表头在上限内保持一行,每列有上下限;更宽的表格在自己的容器里横向滚动。
|
|
111
|
+
* 用 `ch` 加在 content-box 的格子上,所以跟着读者的字号走,内边距也不占这份宽度。
|
|
112
|
+
*/
|
|
113
|
+
function registerTableColumnFloor(editor) {
|
|
114
|
+
const frame = createFrameScheduler(() => {
|
|
115
|
+
editor.getEditorState().read(() => {
|
|
116
|
+
for (const table of $getRoot().getChildren().filter($isTableNode)) {
|
|
117
|
+
const rows = table.getChildren().filter($isTableRowNode).map((row) => row.getChildren().filter($isTableCellNode));
|
|
118
|
+
const floors = tableColumnFloors(rows.map((cells) => cells.map((cell) => cell.getTextContentSize())));
|
|
119
|
+
rows[0]?.forEach((cell, column) => {
|
|
120
|
+
const element = editor.getElementByKey(cell.getKey());
|
|
121
|
+
const floor = `${floors[column]}ch`;
|
|
122
|
+
if (element !== null && element.style.minWidth !== floor) element.style.minWidth = floor;
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
});
|
|
126
|
+
});
|
|
127
|
+
const stop = editor.registerUpdateListener(frame.schedule);
|
|
128
|
+
frame.schedule();
|
|
129
|
+
return () => {
|
|
130
|
+
frame.cancel();
|
|
131
|
+
stop();
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
//#endregion
|
|
135
|
+
//#region src/editor/tabEscape.ts
|
|
136
|
+
/**
|
|
137
|
+
* 按下这些键不算「离开 Escape 状态」:Escape(重新进入)、Tab(正是要离开的那一下),
|
|
138
|
+
* 以及单独的修饰键——Shift+Tab 之前会先收到一次 Shift 的按下,不能因此取消。
|
|
139
|
+
*/
|
|
140
|
+
const KEEP_ARMED_KEYS = /* @__PURE__ */ new Set([
|
|
141
|
+
"Escape",
|
|
142
|
+
"Tab",
|
|
143
|
+
"Shift",
|
|
144
|
+
"Control",
|
|
145
|
+
"Alt",
|
|
146
|
+
"Meta"
|
|
147
|
+
]);
|
|
148
|
+
/**
|
|
149
|
+
* 让键盘用户能离开编辑器(WCAG 2.1.2,不能困住键盘)。
|
|
150
|
+
*
|
|
151
|
+
* 编辑器里 Tab 用来缩进,不处理的话焦点会被困住。这里的做法:按过 Escape 之后,
|
|
152
|
+
* 下一次 Tab(或 Shift+Tab)交给浏览器去移动焦点,不再缩进;按任何别的键、
|
|
153
|
+
* 或者离开编辑器,就恢复成缩进。
|
|
154
|
+
*
|
|
155
|
+
* Lexical 按优先级从高到低依次问命令处理器,谁先返回 true 谁说了算。缩进处理器
|
|
156
|
+
* 优先级最低,所以这里用 `COMMAND_PRIORITY_LOW` 抢在它前面:已经按过 Escape 时
|
|
157
|
+
* 返回 true 但不调用 `preventDefault()`,缩进处理器收不到事件,浏览器照常移动焦点。
|
|
158
|
+
*/
|
|
159
|
+
function registerTabFocusEscape(editor) {
|
|
160
|
+
let armed = false;
|
|
161
|
+
return mergeRegister(editor.registerCommand(KEY_ESCAPE_COMMAND, () => {
|
|
162
|
+
armed = true;
|
|
163
|
+
return true;
|
|
164
|
+
}, COMMAND_PRIORITY_LOW), editor.registerCommand(KEY_TAB_COMMAND, () => {
|
|
165
|
+
if (!armed) return false;
|
|
166
|
+
armed = false;
|
|
167
|
+
return true;
|
|
168
|
+
}, COMMAND_PRIORITY_LOW), editor.registerCommand(KEY_DOWN_COMMAND, (event) => {
|
|
169
|
+
if (armed && !KEEP_ARMED_KEYS.has(event.key)) armed = false;
|
|
170
|
+
return false;
|
|
171
|
+
}, COMMAND_PRIORITY_LOW), editor.registerCommand(BLUR_COMMAND, () => {
|
|
172
|
+
armed = false;
|
|
173
|
+
return false;
|
|
174
|
+
}, COMMAND_PRIORITY_LOW));
|
|
175
|
+
}
|
|
176
|
+
//#endregion
|
|
177
|
+
//#region src/editor/textSemantics.ts
|
|
178
|
+
const STRIKETHROUGH = TEXT_TYPE_TO_FORMAT.strikethrough;
|
|
179
|
+
const BOLD_ITALIC = TEXT_TYPE_TO_FORMAT.bold | TEXT_TYPE_TO_FORMAT.italic;
|
|
180
|
+
/**
|
|
181
|
+
* 这个版本的文字节点外面要套哪几层元素,最外层在前。
|
|
182
|
+
* 读的是这个版本自己的 `__format`:Lexical 的 getter 读的是最新版本,
|
|
183
|
+
* 拿 `prevNode.hasFormat()` 得到的是新值,不是旧值。
|
|
184
|
+
*/
|
|
185
|
+
function wrappersOf(node) {
|
|
186
|
+
const format = node.__format;
|
|
187
|
+
const wrappers = [];
|
|
188
|
+
if ((format & STRIKETHROUGH) !== 0) wrappers.push("del");
|
|
189
|
+
if ((format & BOLD_ITALIC) === BOLD_ITALIC) wrappers.push("em");
|
|
190
|
+
return wrappers;
|
|
191
|
+
}
|
|
192
|
+
function sameWrappers(a, b) {
|
|
193
|
+
return a.length === b.length && a.every((tag, index) => tag === b[index]);
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* 删除线文字外面套 `<del>`,粗斜体外面套 `<em>`,和 core 的 Markdown 渲染出来的元素一致,
|
|
197
|
+
* 读屏软件才能读出「删除」和「强调」。Lexical 自己建的文字元素原样放在里面,所以文档、
|
|
198
|
+
* Markdown 和选区模型都不变;Lexical 找文字时从最外层往下走就能找到它。
|
|
199
|
+
*/
|
|
200
|
+
const TextSemanticsExtension = configExtension(DOMRenderExtension, { overrides: [domOverride([TextNode], {
|
|
201
|
+
$createDOM(node, $next) {
|
|
202
|
+
let element = $next();
|
|
203
|
+
for (const tag of [...wrappersOf(node)].reverse()) {
|
|
204
|
+
const wrapper = document.createElement(tag);
|
|
205
|
+
wrapper.append(element);
|
|
206
|
+
element = wrapper;
|
|
207
|
+
}
|
|
208
|
+
return element;
|
|
209
|
+
},
|
|
210
|
+
$updateDOM(nextNode, prevNode, dom, $next, editor) {
|
|
211
|
+
const wrappers = wrappersOf(nextNode);
|
|
212
|
+
if (!sameWrappers(wrappers, wrappersOf(prevNode))) return true;
|
|
213
|
+
if (wrappers.length === 0) return $next();
|
|
214
|
+
let element = dom;
|
|
215
|
+
for (const tag of wrappers) {
|
|
216
|
+
if (element?.tagName.toLowerCase() !== tag) return true;
|
|
217
|
+
element = element.firstElementChild;
|
|
218
|
+
}
|
|
219
|
+
if (element === null) return true;
|
|
220
|
+
return nextNode.updateDOM(prevNode, element, editor._config);
|
|
221
|
+
}
|
|
222
|
+
})] });
|
|
223
|
+
//#endregion
|
|
224
|
+
//#region src/editor/plugins/codeHighlightRules.ts
|
|
225
|
+
/** 主题给每个代码块加的类名(`theme.ts`);颜色规则靠它找到编辑器里的代码块。 */
|
|
226
|
+
const CODE_SYNTAX_CLASS = "astryx-richtext-code";
|
|
227
|
+
let injected = false;
|
|
228
|
+
/**
|
|
229
|
+
* 注入一次代码块的颜色规则:每种 token 取和 core 的 CodeBlock 同一个语法色变量
|
|
230
|
+
* (`--astryx-code-syntax-*`),所以换语法主题时编辑器和 CodeBlock 一起变。
|
|
231
|
+
*/
|
|
232
|
+
function ensureSyntaxRules() {
|
|
233
|
+
if (injected || typeof document === "undefined") return;
|
|
234
|
+
injected = true;
|
|
235
|
+
const style = document.createElement("style");
|
|
236
|
+
style.setAttribute("data-astryx-richtext-code-syntax", "");
|
|
237
|
+
style.textContent = HIGHLIGHTED_TOKEN_TYPES.map((type) => `.${CODE_SYNTAX_CLASS}::highlight(astryx-${type}) { color: var(--astryx-code-syntax-${type}, currentColor); }`).join("\n");
|
|
238
|
+
document.head.append(style);
|
|
239
|
+
}
|
|
240
|
+
/** 浏览器有没有 CSS Custom Highlight API。 */
|
|
241
|
+
function supportsHighlights() {
|
|
242
|
+
return typeof CSS !== "undefined" && "highlights" in CSS && typeof Highlight !== "undefined";
|
|
243
|
+
}
|
|
244
|
+
//#endregion
|
|
245
|
+
//#region src/editor/theme.ts
|
|
246
|
+
/**
|
|
247
|
+
* 把 Lexical 的主题槽位对应到普通 CSS 类名。样式在 `richtext.css` 里,用 core 的设计变量,
|
|
248
|
+
* 放在 `astryx.components` 层,使用方的样式表可以直接覆盖。
|
|
249
|
+
*/
|
|
250
|
+
function sharedEditorTheme() {
|
|
251
|
+
return {
|
|
252
|
+
paragraph: "astryx-richtext__paragraph",
|
|
253
|
+
markdownExtensionBlock: "astryx-richtext__paragraph",
|
|
254
|
+
heading: {
|
|
255
|
+
h1: "astryx-richtext__heading astryx-richtext__h1",
|
|
256
|
+
h2: "astryx-richtext__heading astryx-richtext__h2",
|
|
257
|
+
h3: "astryx-richtext__heading astryx-richtext__h3",
|
|
258
|
+
h4: "astryx-richtext__heading astryx-richtext__h4",
|
|
259
|
+
h5: "astryx-richtext__heading astryx-richtext__h5",
|
|
260
|
+
h6: "astryx-richtext__heading astryx-richtext__h6"
|
|
261
|
+
},
|
|
262
|
+
quote: "astryx-richtext__quote",
|
|
263
|
+
list: {
|
|
264
|
+
ul: "astryx-richtext__list",
|
|
265
|
+
ol: "astryx-richtext__list",
|
|
266
|
+
listitem: "astryx-richtext__list-item",
|
|
267
|
+
nested: { listitem: "astryx-richtext__list-item" },
|
|
268
|
+
ulDepth: [
|
|
269
|
+
"astryx-richtext__ul-0",
|
|
270
|
+
"astryx-richtext__ul-1",
|
|
271
|
+
"astryx-richtext__ul-2"
|
|
272
|
+
],
|
|
273
|
+
olDepth: [
|
|
274
|
+
"astryx-richtext__ol-0",
|
|
275
|
+
"astryx-richtext__ol-1",
|
|
276
|
+
"astryx-richtext__ol-2"
|
|
277
|
+
]
|
|
278
|
+
},
|
|
279
|
+
link: "astryx-richtext__link",
|
|
280
|
+
text: {
|
|
281
|
+
bold: "astryx-richtext__bold",
|
|
282
|
+
italic: "astryx-richtext__italic",
|
|
283
|
+
underline: "astryx-richtext__underline",
|
|
284
|
+
strikethrough: "astryx-richtext__strikethrough",
|
|
285
|
+
code: "astryx-richtext__inline-code"
|
|
286
|
+
},
|
|
287
|
+
code: `astryx-richtext__code ${CODE_SYNTAX_CLASS}`,
|
|
288
|
+
hr: "astryx-richtext__hr",
|
|
289
|
+
hrSelected: "astryx-richtext__selected",
|
|
290
|
+
markdownExtensionSelected: "astryx-richtext__selected",
|
|
291
|
+
table: "astryx-richtext__table",
|
|
292
|
+
tableRow: "astryx-richtext__table-row",
|
|
293
|
+
tableCell: "astryx-richtext__table-cell",
|
|
294
|
+
tableCellHeader: "astryx-richtext__table-cell-header",
|
|
295
|
+
tableCellSelected: "astryx-richtext__table-cell-selected",
|
|
296
|
+
tableScrollableWrapper: "astryx-richtext__table-wrap"
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
//#endregion
|
|
300
|
+
//#region src/editor/createEditor.ts
|
|
301
|
+
function createRichTextEditor(options = {}) {
|
|
302
|
+
const { namespace = "astryx-editor", initialState, editable = true, nodes = [], hasMarkdownShortcuts = true, transformers = DEFAULT_TRANSFORMERS, theme = sharedEditorTheme(), extensions = [] } = options;
|
|
303
|
+
const root = defineExtension({
|
|
304
|
+
name: "@astryx-vue/richtext/editor",
|
|
305
|
+
namespace,
|
|
306
|
+
theme,
|
|
307
|
+
editable,
|
|
308
|
+
nodes: [...DEFAULT_NODES, ...nodes],
|
|
309
|
+
dependencies: [
|
|
310
|
+
RichTextExtension,
|
|
311
|
+
HistoryExtension,
|
|
312
|
+
LinkExtension,
|
|
313
|
+
CheckListExtension,
|
|
314
|
+
configExtension(TabIndentationExtension, {
|
|
315
|
+
disabled: false,
|
|
316
|
+
maxIndent: null
|
|
317
|
+
}),
|
|
318
|
+
HorizontalRuleExtension,
|
|
319
|
+
configExtension(TableExtension, {
|
|
320
|
+
hasCellMerge: false,
|
|
321
|
+
hasCellBackgroundColor: false,
|
|
322
|
+
hasTabHandler: false,
|
|
323
|
+
hasHorizontalScroll: true
|
|
324
|
+
}),
|
|
325
|
+
TextSemanticsExtension,
|
|
326
|
+
...extensions
|
|
327
|
+
],
|
|
328
|
+
$initialEditorState: initialState ?? void 0,
|
|
329
|
+
register: (editor) => mergeRegister(registerBlockExit(editor), registerTabFocusEscape(editor), registerTableColumnFloor(editor), hasMarkdownShortcuts ? registerMarkdownShortcuts(editor, [...transformers]) : () => {}),
|
|
330
|
+
onError(error) {
|
|
331
|
+
throw error;
|
|
332
|
+
}
|
|
333
|
+
});
|
|
334
|
+
return buildEditorFromExtensions(root);
|
|
335
|
+
}
|
|
336
|
+
//#endregion
|
|
337
|
+
//#region src/editor/icons.ts
|
|
338
|
+
/**
|
|
339
|
+
* 工具栏每个控件用的图标键。主题可以用 `defineTheme({ icons: { 'richtext:bold': 'lucide:bold' } })`
|
|
340
|
+
* 按键换成自己的图标;没换的就用下面包内自带的图形。
|
|
341
|
+
* 键带 `richtext:` 前缀,不会和 core 的语义图标名冲突。
|
|
342
|
+
*/
|
|
343
|
+
const RICHTEXT_ICON_KEYS = {
|
|
344
|
+
bold: "richtext:bold",
|
|
345
|
+
italic: "richtext:italic",
|
|
346
|
+
underline: "richtext:underline",
|
|
347
|
+
strikethrough: "richtext:strikethrough",
|
|
348
|
+
code: "richtext:code",
|
|
349
|
+
link: "richtext:link",
|
|
350
|
+
paragraph: "richtext:paragraph",
|
|
351
|
+
h1: "richtext:h1",
|
|
352
|
+
h2: "richtext:h2",
|
|
353
|
+
h3: "richtext:h3",
|
|
354
|
+
quote: "richtext:quote",
|
|
355
|
+
bullet: "richtext:bullet",
|
|
356
|
+
number: "richtext:number",
|
|
357
|
+
undo: "richtext:undo",
|
|
358
|
+
redo: "richtext:redo"
|
|
359
|
+
};
|
|
360
|
+
const STROKE = {
|
|
361
|
+
"stroke": "currentColor",
|
|
362
|
+
"stroke-width": "2"
|
|
363
|
+
};
|
|
364
|
+
const ROUND = {
|
|
365
|
+
"stroke-linecap": "round",
|
|
366
|
+
"stroke-linejoin": "round"
|
|
367
|
+
};
|
|
368
|
+
function path(d, extra = {}) {
|
|
369
|
+
return {
|
|
370
|
+
tag: "path",
|
|
371
|
+
attrs: {
|
|
372
|
+
d,
|
|
373
|
+
fill: "none",
|
|
374
|
+
...STROKE,
|
|
375
|
+
...extra
|
|
376
|
+
}
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
/** 24×24 画布上的线条图形,和上游工具栏内置的那套一致。 */
|
|
380
|
+
const SHAPES = {
|
|
381
|
+
bold: [path("M6 4h7a4 4 0 0 1 0 8H6zM6 12h8a4 4 0 0 1 0 8H6z", { "stroke-linejoin": "round" })],
|
|
382
|
+
italic: [path("M10 4h6M8 20h6M14 4l-4 16", { "stroke-linecap": "round" })],
|
|
383
|
+
underline: [path("M6 4v6a6 6 0 0 0 12 0V4M5 21h14", { "stroke-linecap": "round" })],
|
|
384
|
+
strikethrough: [path("M4 12h16M8 6a4 3 0 0 1 8 0M8 16a4 3 0 0 0 8 0", { "stroke-linecap": "round" })],
|
|
385
|
+
code: [path("M9 8l-4 4 4 4M15 8l4 4-4 4", ROUND)],
|
|
386
|
+
link: [path("M10 13a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-1.5 1.5M14 11a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l1.5-1.5", ROUND)],
|
|
387
|
+
quote: [path("M6 17h3l2-4V7H5v6h3zM15 17h3l2-4V7h-6v6h3z", { "stroke-linejoin": "round" })],
|
|
388
|
+
bullet: [path("M9 6h11M9 12h11M9 18h11", { "stroke-linecap": "round" }), ...[
|
|
389
|
+
6,
|
|
390
|
+
12,
|
|
391
|
+
18
|
|
392
|
+
].map((cy) => ({
|
|
393
|
+
tag: "circle",
|
|
394
|
+
attrs: {
|
|
395
|
+
cx: "4.5",
|
|
396
|
+
cy: String(cy),
|
|
397
|
+
r: "1.5",
|
|
398
|
+
fill: "currentColor"
|
|
399
|
+
}
|
|
400
|
+
}))],
|
|
401
|
+
number: [path("M10 6h10M10 12h10M10 18h10", { "stroke-linecap": "round" }), ...[
|
|
402
|
+
["1", 8],
|
|
403
|
+
["2", 14],
|
|
404
|
+
["3", 20]
|
|
405
|
+
].map(([text, y]) => ({
|
|
406
|
+
tag: "text",
|
|
407
|
+
text,
|
|
408
|
+
attrs: {
|
|
409
|
+
"x": "2",
|
|
410
|
+
"y": String(y),
|
|
411
|
+
"font-size": "6",
|
|
412
|
+
"fill": "currentColor"
|
|
413
|
+
}
|
|
414
|
+
}))],
|
|
415
|
+
undo: [path("M9 4.5L4 9.5l5 5M4 9.5h11a5 5 0 0 1 0 10", ROUND)],
|
|
416
|
+
redo: [path("M15 4.5l5 5-5 5M20 9.5H9a5 5 0 0 0 0 10", ROUND)]
|
|
417
|
+
};
|
|
418
|
+
/** 段落和标题没有图形,用一小段文字当图标。 */
|
|
419
|
+
const TEXT_LABELS = {
|
|
420
|
+
paragraph: "¶",
|
|
421
|
+
h1: "H1",
|
|
422
|
+
h2: "H2",
|
|
423
|
+
h3: "H3"
|
|
424
|
+
};
|
|
425
|
+
/** 包内自带的图标:线条图形或文字,画在 16px 的盒子里,颜色跟随文字。 */
|
|
426
|
+
function builtInIcon(name) {
|
|
427
|
+
const label = TEXT_LABELS[name];
|
|
428
|
+
if (label !== void 0) return defineComponent({
|
|
429
|
+
name: `RichTextGlyph_${name}`,
|
|
430
|
+
setup: () => () => h("span", {
|
|
431
|
+
"class": "astryx-richtext-toolbar__text-glyph",
|
|
432
|
+
"aria-hidden": "true"
|
|
433
|
+
}, label)
|
|
434
|
+
});
|
|
435
|
+
const shapes = SHAPES[name] ?? [];
|
|
436
|
+
return defineComponent({
|
|
437
|
+
name: `RichTextIcon_${name}`,
|
|
438
|
+
setup: () => () => h("svg", {
|
|
439
|
+
"width": 16,
|
|
440
|
+
"height": 16,
|
|
441
|
+
"viewBox": "0 0 24 24",
|
|
442
|
+
"fill": "none",
|
|
443
|
+
"aria-hidden": "true"
|
|
444
|
+
}, shapes.map((shape) => h(shape.tag, shape.attrs, shape.tag === "text" ? shape.text : void 0)))
|
|
445
|
+
});
|
|
446
|
+
}
|
|
447
|
+
//#endregion
|
|
448
|
+
//#region src/linkUtils.ts
|
|
449
|
+
/**
|
|
450
|
+
* @file linkUtils.ts
|
|
451
|
+
* @input Uses only the DOM URL constructor (guarded via try/catch for SSR/edge).
|
|
452
|
+
* @output Exports `sanitizeUrl`, `validateUrl`, and the URL/email matcher regexes
|
|
453
|
+
* used by the AutoLink wiring.
|
|
454
|
+
* @position @astryxdesign/richtext helper shared by RichTextEditorToolbar (link
|
|
455
|
+
* button) and the AutoLink matchers in RichTextEditor. Kept dependency-free so
|
|
456
|
+
* both can import it without pulling in extra `@lexical/*` surface.
|
|
457
|
+
*
|
|
458
|
+
* SYNC: When modified, update:
|
|
459
|
+
* - /packages/richtext/src/RichTextEditorToolbar.tsx (link button)
|
|
460
|
+
* - /packages/richtext/src/RichTextEditor.tsx (AutoLink matchers)
|
|
461
|
+
* - /packages/richtext/src/RichTextEditor.test.tsx (tests)
|
|
462
|
+
* - /packages/richtext/src/RichTextEditor.doc.mjs (link docs)
|
|
463
|
+
* - /packages/richtext/src/index.ts (exports / barrel)
|
|
464
|
+
*
|
|
465
|
+
* NOTE: Mirrors the Lexical playground's url.ts (`sanitizeUrl` / `validateUrl`
|
|
466
|
+
* / `URL_REGEX` / `EMAIL_REGEX`). Sanitization is the security-critical part:
|
|
467
|
+
* it blocks `javascript:`, `data:`, and other non-http(s)/mailto/tel schemes
|
|
468
|
+
* from being written into a LinkNode's href, so an inserted link can never
|
|
469
|
+
* smuggle in an executable URL.
|
|
470
|
+
*/
|
|
471
|
+
/**
|
|
472
|
+
* Schemes a link is allowed to carry. Anything else (notably `javascript:`,
|
|
473
|
+
* `data:`, `vbscript:`) is rejected by {@link validateUrl} and coerced to
|
|
474
|
+
* `about:blank` by {@link sanitizeUrl}, so a malicious paste can't produce a
|
|
475
|
+
* clickable code-execution link.
|
|
476
|
+
*/
|
|
477
|
+
const SAFE_PROTOCOLS = /* @__PURE__ */ new Set([
|
|
478
|
+
"http:",
|
|
479
|
+
"https:",
|
|
480
|
+
"mailto:",
|
|
481
|
+
"tel:"
|
|
482
|
+
]);
|
|
483
|
+
/** Matches a scheme prefix like `https:` / `mailto:` at the start of a string. */
|
|
484
|
+
const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
|
|
485
|
+
/**
|
|
486
|
+
* Matches a bare URL for AutoLink. Adapted from the Lexical playground.
|
|
487
|
+
* Intentionally permissive on path/query so real-world URLs linkify.
|
|
488
|
+
*/
|
|
489
|
+
const URL_MATCHER = /((https?:\/\/(www\.)?)|(www\.))[-\w@:%.+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-\w()@:%+.~#?&/=]*)/;
|
|
490
|
+
/** Matches a bare email address for AutoLink (rendered as a `mailto:` link). */
|
|
491
|
+
const EMAIL_MATCHER = /(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\])|(([a-z\-0-9]+\.)+[a-z]{2,}))/i;
|
|
492
|
+
/** Prepend a default `https://` scheme to a bare host so it parses as absolute. */
|
|
493
|
+
function withDefaultScheme(url) {
|
|
494
|
+
return HAS_SCHEME.test(url) ? url : `https://${url}`;
|
|
495
|
+
}
|
|
496
|
+
/**
|
|
497
|
+
* Return a safe href for `url`, or `'about:blank'` if it can't be parsed or uses
|
|
498
|
+
* a disallowed scheme. A scheme-less input like `example.com` is treated as
|
|
499
|
+
* `https://example.com`. Use this before writing any user-supplied string into
|
|
500
|
+
* a link's href.
|
|
501
|
+
*/
|
|
502
|
+
function sanitizeUrl(url) {
|
|
503
|
+
const trimmed = url.trim();
|
|
504
|
+
if (trimmed === "") return "about:blank";
|
|
505
|
+
try {
|
|
506
|
+
const parsed = new URL(withDefaultScheme(trimmed));
|
|
507
|
+
if (!SAFE_PROTOCOLS.has(parsed.protocol.toLowerCase())) return "about:blank";
|
|
508
|
+
return parsed.href;
|
|
509
|
+
} catch {
|
|
510
|
+
return "about:blank";
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
/**
|
|
514
|
+
* Whether `url` is a well-formed, safe (http/https/mailto/tel) URL. Used to
|
|
515
|
+
* decide whether an entered link value is acceptable before dispatching the
|
|
516
|
+
* toggle-link command. Shares the {@link SAFE_PROTOCOLS} allowlist with
|
|
517
|
+
* {@link sanitizeUrl} so the two never disagree.
|
|
518
|
+
*/
|
|
519
|
+
function validateUrl(url) {
|
|
520
|
+
const trimmed = url.trim();
|
|
521
|
+
if (trimmed === "") return false;
|
|
522
|
+
try {
|
|
523
|
+
const parsed = new URL(withDefaultScheme(trimmed));
|
|
524
|
+
return SAFE_PROTOCOLS.has(parsed.protocol.toLowerCase());
|
|
525
|
+
} catch {
|
|
526
|
+
return false;
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
//#endregion
|
|
530
|
+
//#region src/editor/plugins/autoLink.ts
|
|
531
|
+
/**
|
|
532
|
+
* 自动生成的链接都带这两个属性,在新标签页打开。只要有 `target="_blank"`,
|
|
533
|
+
* 就必须同时有 `rel="noopener noreferrer"`,否则被打开的页面能通过 `window.opener` 反过来操控原页面。
|
|
534
|
+
*/
|
|
535
|
+
const NEW_TAB_LINK_ATTRIBUTES = {
|
|
536
|
+
target: "_blank",
|
|
537
|
+
rel: "noopener noreferrer"
|
|
538
|
+
};
|
|
539
|
+
/**
|
|
540
|
+
* 默认的两个匹配器:网址(没写协议就补 `https://`)和邮箱(写成 `mailto:` 链接)。
|
|
541
|
+
* 网址都过一遍 `sanitizeUrl`,所以写进去的只可能是 http、https、mailto、tel。
|
|
542
|
+
*/
|
|
543
|
+
const DEFAULT_LINK_MATCHERS = [(text) => {
|
|
544
|
+
const match = createLinkMatcherWithRegExp(URL_MATCHER, (url) => sanitizeUrl(url))(text);
|
|
545
|
+
return match ? {
|
|
546
|
+
...match,
|
|
547
|
+
attributes: NEW_TAB_LINK_ATTRIBUTES
|
|
548
|
+
} : null;
|
|
549
|
+
}, (text) => {
|
|
550
|
+
const match = createLinkMatcherWithRegExp(EMAIL_MATCHER, (email) => `mailto:${email}`)(text);
|
|
551
|
+
return match ? {
|
|
552
|
+
...match,
|
|
553
|
+
attributes: NEW_TAB_LINK_ATTRIBUTES
|
|
554
|
+
} : null;
|
|
555
|
+
}];
|
|
556
|
+
/**
|
|
557
|
+
* 把输入或粘贴的网址、邮箱自动变成链接。返回取消注册的函数。
|
|
558
|
+
* 需要 `AutoLinkNode`,默认节点里已经有了。
|
|
559
|
+
*/
|
|
560
|
+
function registerRichTextAutoLink(editor, options = {}) {
|
|
561
|
+
const config = {
|
|
562
|
+
matchers: options.matchers ?? DEFAULT_LINK_MATCHERS,
|
|
563
|
+
changeHandlers: options.onChange ? [options.onChange] : [],
|
|
564
|
+
excludeParents: []
|
|
565
|
+
};
|
|
566
|
+
return registerAutoLink(editor, config);
|
|
567
|
+
}
|
|
568
|
+
//#endregion
|
|
569
|
+
//#region src/editor/plugins/useOverlayPlacements.ts
|
|
570
|
+
/**
|
|
571
|
+
* 编辑区上面有些东西(代码块的标题栏、任务项的勾选框)不能放进可编辑的文字里,
|
|
572
|
+
* 只能是编辑区的兄弟元素,画在对应文档块的上方。这个函数负责「量位置、跟着变」:
|
|
573
|
+
* 文档更新、编辑区尺寸变化、窗口缩放之后,下一帧重新量一次,结果没变就不触发重画。
|
|
574
|
+
*
|
|
575
|
+
* `measure` 在 Lexical 的只读上下文里调用(可以用 `$` 开头的函数),
|
|
576
|
+
* `origin` 是容器的位置,用来把元素的屏幕坐标换成相对容器的坐标。
|
|
577
|
+
*/
|
|
578
|
+
function useOverlayPlacements(editor, measure, isSame) {
|
|
579
|
+
const placements = shallowRef([]);
|
|
580
|
+
const frame = createFrameScheduler(() => {
|
|
581
|
+
const container = editor.getRootElement()?.parentElement ?? null;
|
|
582
|
+
if (container === null) {
|
|
583
|
+
if (placements.value.length > 0) placements.value = [];
|
|
584
|
+
return;
|
|
585
|
+
}
|
|
586
|
+
const origin = container.getBoundingClientRect();
|
|
587
|
+
const next = editor.getEditorState().read(() => measure(origin));
|
|
588
|
+
if (!isSame(placements.value, next)) placements.value = next;
|
|
589
|
+
});
|
|
590
|
+
const schedule = frame.schedule;
|
|
591
|
+
const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(schedule);
|
|
592
|
+
const stopRoot = editor.registerRootListener((root) => {
|
|
593
|
+
observer?.disconnect();
|
|
594
|
+
if (root !== null) observer?.observe(root);
|
|
595
|
+
schedule();
|
|
596
|
+
});
|
|
597
|
+
const stopUpdate = editor.registerUpdateListener(schedule);
|
|
598
|
+
const hasWindow = typeof window !== "undefined";
|
|
599
|
+
if (hasWindow) window.addEventListener("resize", schedule);
|
|
600
|
+
schedule();
|
|
601
|
+
onBeforeUnmount(() => {
|
|
602
|
+
frame.cancel();
|
|
603
|
+
observer?.disconnect();
|
|
604
|
+
stopRoot();
|
|
605
|
+
stopUpdate();
|
|
606
|
+
if (hasWindow) window.removeEventListener("resize", schedule);
|
|
607
|
+
});
|
|
608
|
+
return placements;
|
|
609
|
+
}
|
|
610
|
+
//#endregion
|
|
611
|
+
//#region src/editor/plugins/CodeBlockHeaderPlugin.ts
|
|
612
|
+
const PLAIN_TEXT = "plaintext";
|
|
613
|
+
/**
|
|
614
|
+
* 标题栏上写不写语言,和 core 的 CodeBlock 一致:围栏没写语言就不写,
|
|
615
|
+
* 恰好是 `plaintext` 也不写(core 的 Markdown 会给没有信息串的围栏补上它)。
|
|
616
|
+
*/
|
|
617
|
+
function displayLanguageOf(language) {
|
|
618
|
+
return language == null || language === "" || language === PLAIN_TEXT ? null : language;
|
|
619
|
+
}
|
|
620
|
+
function samePlacements$1(a, b) {
|
|
621
|
+
return a.length === b.length && a.every((p, i) => {
|
|
622
|
+
const q = b[i];
|
|
623
|
+
return p.key === q.key && p.language === q.language && p.top === q.top && p.left === q.left && p.width === q.width;
|
|
624
|
+
});
|
|
625
|
+
}
|
|
626
|
+
/** 绝对定位用的内联样式:位置是量出来的屏幕坐标,已经把方向算进去了。 */
|
|
627
|
+
function positionStyle(p) {
|
|
628
|
+
return {
|
|
629
|
+
position: "absolute",
|
|
630
|
+
top: `${p.top}px`,
|
|
631
|
+
left: `${p.left}px`,
|
|
632
|
+
width: `${p.width}px`
|
|
633
|
+
};
|
|
634
|
+
}
|
|
635
|
+
const CodeBlockHeader = defineComponent({
|
|
636
|
+
name: "AstryxRichTextCodeBlockHeader",
|
|
637
|
+
props: { placement: {
|
|
638
|
+
type: Object,
|
|
639
|
+
required: true
|
|
640
|
+
} },
|
|
641
|
+
setup(props) {
|
|
642
|
+
const editor = useLexicalEditor();
|
|
643
|
+
const messages = useAstryxMessages();
|
|
644
|
+
const { copy, isCopied } = useCopyToClipboard({ announce: messages.value.codeBlock.copied });
|
|
645
|
+
function copyCode() {
|
|
646
|
+
const code = editor.getEditorState().read(() => $getNodeByKey(props.placement.key)?.getTextContent() ?? "");
|
|
647
|
+
copy(code);
|
|
648
|
+
}
|
|
649
|
+
return () => {
|
|
650
|
+
const { placement } = props;
|
|
651
|
+
const label = isCopied.value ? messages.value.codeBlock.copied : messages.value.codeBlock.copyCode;
|
|
652
|
+
const button = h(IconButton, {
|
|
653
|
+
label,
|
|
654
|
+
variant: "ghost",
|
|
655
|
+
size: "sm",
|
|
656
|
+
tooltip: messages.value.codeBlock.copyCode,
|
|
657
|
+
class: "astryx-richtext-code-header__copy",
|
|
658
|
+
onClick: copyCode
|
|
659
|
+
}, { default: () => h(Icon, {
|
|
660
|
+
icon: isCopied.value ? "check" : "copy",
|
|
661
|
+
size: "sm",
|
|
662
|
+
color: "inherit"
|
|
663
|
+
}) });
|
|
664
|
+
if (placement.language === null) return h("div", {
|
|
665
|
+
"class": "astryx-richtext-code-header astryx-richtext-code-header--corner",
|
|
666
|
+
"data-richtext-code-header": "",
|
|
667
|
+
"style": positionStyle(placement)
|
|
668
|
+
}, [button]);
|
|
669
|
+
return h("div", {
|
|
670
|
+
"class": "astryx-richtext-code-header",
|
|
671
|
+
"data-richtext-code-header": "",
|
|
672
|
+
"style": positionStyle(placement)
|
|
673
|
+
}, [h("span", { class: "astryx-richtext-code-header__title" }, placement.language), button]);
|
|
674
|
+
};
|
|
675
|
+
}
|
|
676
|
+
});
|
|
677
|
+
/**
|
|
678
|
+
* 在每个顶层代码块上面画一条标题栏(语言名加复制按钮),跟着文档、编辑区尺寸、窗口变化。
|
|
679
|
+
* 没有界面输入,放进 `<RichTextEditor>` 的默认插槽即可;编辑器默认已经带上了它。
|
|
680
|
+
*/
|
|
681
|
+
const CodeBlockHeaderPlugin = defineComponent({
|
|
682
|
+
name: "AstryxRichTextCodeBlockHeaderPlugin",
|
|
683
|
+
setup() {
|
|
684
|
+
const editor = useLexicalEditor();
|
|
685
|
+
const placements = useOverlayPlacements(editor, (origin) => {
|
|
686
|
+
return $getRoot().getChildren().filter($isCodeNode).flatMap((node) => {
|
|
687
|
+
const element = editor.getElementByKey(node.getKey());
|
|
688
|
+
if (element === null) return [];
|
|
689
|
+
const box = element.getBoundingClientRect();
|
|
690
|
+
return [{
|
|
691
|
+
key: node.getKey(),
|
|
692
|
+
language: displayLanguageOf(node.getLanguage()),
|
|
693
|
+
top: box.top - origin.top + element.clientTop,
|
|
694
|
+
left: box.left - origin.left + element.clientLeft,
|
|
695
|
+
width: element.clientWidth
|
|
696
|
+
}];
|
|
697
|
+
});
|
|
698
|
+
}, samePlacements$1);
|
|
699
|
+
return () => placements.value.map((p) => h(CodeBlockHeader, {
|
|
700
|
+
key: p.key,
|
|
701
|
+
placement: p
|
|
702
|
+
}));
|
|
703
|
+
}
|
|
704
|
+
});
|
|
705
|
+
//#endregion
|
|
706
|
+
//#region src/editor/plugins/flatHighlight.ts
|
|
707
|
+
function highlightFor(type) {
|
|
708
|
+
const host = CSS.highlights;
|
|
709
|
+
if (host === void 0) return null;
|
|
710
|
+
const name = `astryx-${type}`;
|
|
711
|
+
let highlight = host.get(name);
|
|
712
|
+
if (highlight === void 0) {
|
|
713
|
+
highlight = new Highlight();
|
|
714
|
+
host.set(name, highlight);
|
|
715
|
+
}
|
|
716
|
+
return highlight;
|
|
717
|
+
}
|
|
718
|
+
/** 一个整体偏移落在哪个文字节点的第几个字符。 */
|
|
719
|
+
function resolveOffset(slices, offset) {
|
|
720
|
+
for (const slice of slices) if (offset >= slice.start && offset <= slice.start + slice.length) return {
|
|
721
|
+
node: slice.node,
|
|
722
|
+
offset: offset - slice.start
|
|
723
|
+
};
|
|
724
|
+
return null;
|
|
725
|
+
}
|
|
726
|
+
/**
|
|
727
|
+
* 给「一整块平铺的文字」上色:元素里没有 `[data-line]` 这样的分行结构,
|
|
728
|
+
* 文字可能是好几个文字节点,也可能是一个带 `\n` 的大节点。
|
|
729
|
+
* 把每行的 token 偏移换算成整块文字里的偏移,再落到具体的文字节点上。
|
|
730
|
+
* 返回一个函数,调用后撤掉这次加的全部范围。
|
|
731
|
+
*
|
|
732
|
+
* core 的 `applyHighlightRanges` 只认 `[data-line]` 结构,编辑器里的代码块不是那种结构,所以单独写这个。
|
|
733
|
+
*/
|
|
734
|
+
function applyFlatHighlightRanges(element, tokenLines) {
|
|
735
|
+
const applied = [];
|
|
736
|
+
const slices = [];
|
|
737
|
+
const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT);
|
|
738
|
+
let total = 0;
|
|
739
|
+
for (let node = walker.nextNode(); node !== null; node = walker.nextNode()) {
|
|
740
|
+
const text = node;
|
|
741
|
+
slices.push({
|
|
742
|
+
node: text,
|
|
743
|
+
start: total,
|
|
744
|
+
length: text.length
|
|
745
|
+
});
|
|
746
|
+
total += text.length;
|
|
747
|
+
}
|
|
748
|
+
const cleanup = () => {
|
|
749
|
+
for (const { highlight, range } of applied) highlight.delete(range);
|
|
750
|
+
};
|
|
751
|
+
if (slices.length === 0) return cleanup;
|
|
752
|
+
const fullText = element.textContent ?? "";
|
|
753
|
+
let lineOffset = 0;
|
|
754
|
+
for (const line of tokenLines) {
|
|
755
|
+
for (const token of line) {
|
|
756
|
+
const start = resolveOffset(slices, lineOffset + token.start);
|
|
757
|
+
const end = resolveOffset(slices, lineOffset + token.end);
|
|
758
|
+
const highlight = highlightFor(token.type);
|
|
759
|
+
if (start === null || end === null || highlight === null) continue;
|
|
760
|
+
try {
|
|
761
|
+
const range = new Range();
|
|
762
|
+
range.setStart(start.node, start.offset);
|
|
763
|
+
range.setEnd(end.node, end.offset);
|
|
764
|
+
highlight.add(range);
|
|
765
|
+
applied.push({
|
|
766
|
+
highlight,
|
|
767
|
+
range
|
|
768
|
+
});
|
|
769
|
+
} catch {}
|
|
770
|
+
}
|
|
771
|
+
const newline = fullText.indexOf("\n", lineOffset);
|
|
772
|
+
lineOffset = newline === -1 ? fullText.length : newline + 1;
|
|
773
|
+
}
|
|
774
|
+
return cleanup;
|
|
775
|
+
}
|
|
776
|
+
//#endregion
|
|
777
|
+
//#region src/editor/plugins/CodeSyntaxPlugin.ts
|
|
778
|
+
/**
|
|
779
|
+
* 给「画出来的文字」排好的 token。
|
|
780
|
+
*
|
|
781
|
+
* 代码块里的换行有两种画法:文字里保留 `\n`,或者每个换行是一个没有文字的元素。
|
|
782
|
+
* 前者按行给 token,后者要把所有行的偏移接成一整行。画出来的文字对不上代码时
|
|
783
|
+
* (正在更新的瞬间)返回 null,这样不会把颜色涂在错的位置上。
|
|
784
|
+
*/
|
|
785
|
+
function renderedTokens(code, language, rendered) {
|
|
786
|
+
const lines = tokenize(code, language);
|
|
787
|
+
if (rendered === code) return lines;
|
|
788
|
+
if (rendered !== code.replaceAll("\n", "")) return null;
|
|
789
|
+
const flat = [];
|
|
790
|
+
let offset = 0;
|
|
791
|
+
code.split("\n").forEach((line, index) => {
|
|
792
|
+
for (const token of lines[index] ?? []) flat.push({
|
|
793
|
+
type: token.type,
|
|
794
|
+
start: offset + token.start,
|
|
795
|
+
end: offset + token.end
|
|
796
|
+
});
|
|
797
|
+
offset += line.length;
|
|
798
|
+
});
|
|
799
|
+
return [flat];
|
|
800
|
+
}
|
|
801
|
+
/**
|
|
802
|
+
* 给编辑器里的代码块上色。用浏览器的 CSS Custom Highlight API 画颜色,不动文字本身,
|
|
803
|
+
* 所以不会影响光标和选区;代码或语言变了才重新算。不支持这个 API 的浏览器显示纯色代码。
|
|
804
|
+
*/
|
|
805
|
+
const CodeSyntaxPlugin = defineComponent({
|
|
806
|
+
name: "AstryxRichTextCodeSyntaxPlugin",
|
|
807
|
+
setup() {
|
|
808
|
+
const editor = useLexicalEditor();
|
|
809
|
+
if (!supportsHighlights()) return () => null;
|
|
810
|
+
ensureSyntaxRules();
|
|
811
|
+
const blocks = /* @__PURE__ */ new Set();
|
|
812
|
+
const colored = /* @__PURE__ */ new Map();
|
|
813
|
+
function uncolor(key) {
|
|
814
|
+
colored.get(key)?.cleanup();
|
|
815
|
+
colored.delete(key);
|
|
816
|
+
}
|
|
817
|
+
function color(key) {
|
|
818
|
+
const block = editor.getEditorState().read(() => {
|
|
819
|
+
const node = $getNodeByKey(key);
|
|
820
|
+
return $isCodeNode(node) ? {
|
|
821
|
+
code: node.getTextContent(),
|
|
822
|
+
language: node.getLanguage() ?? ""
|
|
823
|
+
} : null;
|
|
824
|
+
});
|
|
825
|
+
const element = editor.getElementByKey(key);
|
|
826
|
+
if (block === null || element === null) {
|
|
827
|
+
uncolor(key);
|
|
828
|
+
return;
|
|
829
|
+
}
|
|
830
|
+
const previous = colored.get(key);
|
|
831
|
+
if (previous !== void 0 && previous.element === element && previous.code === block.code && previous.language === block.language) return;
|
|
832
|
+
previous?.cleanup();
|
|
833
|
+
const tokens = renderedTokens(block.code, block.language, element.textContent ?? "");
|
|
834
|
+
if (tokens === null) {
|
|
835
|
+
colored.delete(key);
|
|
836
|
+
return;
|
|
837
|
+
}
|
|
838
|
+
colored.set(key, {
|
|
839
|
+
element,
|
|
840
|
+
...block,
|
|
841
|
+
cleanup: applyFlatHighlightRanges(element, tokens)
|
|
842
|
+
});
|
|
843
|
+
}
|
|
844
|
+
const stopMutations = editor.registerMutationListener(CodeNode, (mutations) => {
|
|
845
|
+
for (const [key, mutation] of mutations) if (mutation === "destroyed") {
|
|
846
|
+
blocks.delete(key);
|
|
847
|
+
uncolor(key);
|
|
848
|
+
} else {
|
|
849
|
+
blocks.add(key);
|
|
850
|
+
color(key);
|
|
851
|
+
}
|
|
852
|
+
}, { skipInitialization: false });
|
|
853
|
+
const stopUpdates = editor.registerUpdateListener(() => {
|
|
854
|
+
for (const key of blocks) color(key);
|
|
855
|
+
});
|
|
856
|
+
onBeforeUnmount(() => {
|
|
857
|
+
stopMutations();
|
|
858
|
+
stopUpdates();
|
|
859
|
+
for (const key of [...colored.keys()]) uncolor(key);
|
|
860
|
+
blocks.clear();
|
|
861
|
+
});
|
|
862
|
+
return () => null;
|
|
863
|
+
}
|
|
864
|
+
});
|
|
865
|
+
//#endregion
|
|
866
|
+
//#region src/editor/plugins/MarkdownExtensionsPlugin.ts
|
|
867
|
+
/**
|
|
868
|
+
* 从存下来的节点原文,用已采用的插件重新读一遍,得到 core 认的那个节点。
|
|
869
|
+
* 没有同名同版本的插件、或者这段原文已经不被这个插件读成「同一个节点」时返回 null。
|
|
870
|
+
*/
|
|
871
|
+
function deriveExtensionNode(facts, plugins) {
|
|
872
|
+
const plugin = plugins.find((entry) => entry.name === facts.plugin);
|
|
873
|
+
if (plugin === void 0 || plugin.apiVersion !== facts.apiVersion) return null;
|
|
874
|
+
const nodes = facts.display === "inline" ? parseInlineAst(facts.source, { plugins: [plugin] }) : parseMarkdownAst(facts.source, { plugins: [plugin] }).children;
|
|
875
|
+
const [node] = nodes;
|
|
876
|
+
if (nodes.length !== 1 || node?.type !== "extension") return null;
|
|
877
|
+
const extension = node;
|
|
878
|
+
return extension.plugin === facts.plugin && extension.name === facts.name && extension.display === facts.display && extension.source === facts.source ? extension : null;
|
|
879
|
+
}
|
|
880
|
+
/**
|
|
881
|
+
* 插件节点可以放在哪些格式里面,最外层在前,和编辑器画文字的方式一致(`textSemantics.ts`):
|
|
882
|
+
* 先删除线,再斜体,再粗体。
|
|
883
|
+
*/
|
|
884
|
+
const MARKS = [
|
|
885
|
+
["strikethrough", "del"],
|
|
886
|
+
["italic", "em"],
|
|
887
|
+
["bold", "strong"]
|
|
888
|
+
];
|
|
889
|
+
/** 切换这些格式时,插件节点会跟着走。 */
|
|
890
|
+
const NODE_FORMATS = new Set(MARKS.map(([format]) => format));
|
|
891
|
+
/** 把插件节点的内容画出来;放在粗体、斜体、删除线里面的节点,画在同样的元素里面。 */
|
|
892
|
+
const ExtensionNodeView = defineComponent({
|
|
893
|
+
name: "AstryxRichTextExtensionNodeView",
|
|
894
|
+
props: {
|
|
895
|
+
facts: {
|
|
896
|
+
type: Object,
|
|
897
|
+
required: true
|
|
898
|
+
},
|
|
899
|
+
format: {
|
|
900
|
+
type: Number,
|
|
901
|
+
required: true
|
|
902
|
+
},
|
|
903
|
+
plugins: {
|
|
904
|
+
type: Array,
|
|
905
|
+
required: true
|
|
906
|
+
}
|
|
907
|
+
},
|
|
908
|
+
setup(props) {
|
|
909
|
+
return () => {
|
|
910
|
+
const node = deriveExtensionNode(props.facts, props.plugins);
|
|
911
|
+
let content = node === null ? props.facts.source : h(MarkdownPluginNodeRenderer, {
|
|
912
|
+
plugins: props.plugins,
|
|
913
|
+
node
|
|
914
|
+
});
|
|
915
|
+
for (const [type, tag] of [...MARKS].reverse()) if ((props.format & TEXT_TYPE_TO_FORMAT[type]) !== 0) content = h(tag, [content]);
|
|
916
|
+
return content;
|
|
917
|
+
};
|
|
918
|
+
}
|
|
919
|
+
});
|
|
920
|
+
/**
|
|
921
|
+
* 给所有插件节点重新画一遍:标一下脏,Lexical 就会用编辑器现在的画法再画。
|
|
922
|
+
* 这不是编辑,所以不进撤销历史。
|
|
923
|
+
*/
|
|
924
|
+
function redrawExtensionNodes(editor) {
|
|
925
|
+
editor.update(() => {
|
|
926
|
+
for (const { node } of $dfs()) if ($isRichTextExtensionNode(node)) node.markDirty();
|
|
927
|
+
}, { tag: HISTORY_MERGE_TAG });
|
|
928
|
+
}
|
|
929
|
+
/** 工具栏切换格式后,这个范围选区里「正好会开着」的状态;范围里没有文字、只有节点时返回 null。 */
|
|
930
|
+
function $nextTextFormat(selection, format) {
|
|
931
|
+
const first = $firstSelectedText(selection);
|
|
932
|
+
return first === null ? null : (first.getFormatFlags(format, null) & TEXT_TYPE_TO_FORMAT[format]) !== 0;
|
|
933
|
+
}
|
|
934
|
+
/** 选中的插件节点要显示焦点环:按 Lexical 的选区状态加减主题里的类名。 */
|
|
935
|
+
function syncSelectedRing(editor) {
|
|
936
|
+
const selectedKeys = /* @__PURE__ */ new Set();
|
|
937
|
+
return editor.registerUpdateListener(({ editorState }) => {
|
|
938
|
+
const className = editor._config.theme.markdownExtensionSelected;
|
|
939
|
+
if (typeof className !== "string" || className === "") return;
|
|
940
|
+
const now = /* @__PURE__ */ new Set();
|
|
941
|
+
editorState.read(() => {
|
|
942
|
+
for (const { node } of $dfs()) if ($isRichTextExtensionNode(node) && node.isSelected()) now.add(node.getKey());
|
|
943
|
+
});
|
|
944
|
+
for (const key of now) {
|
|
945
|
+
const element = editor.getElementByKey(key);
|
|
946
|
+
if (element !== null) addClassNamesToElement(element, className);
|
|
947
|
+
}
|
|
948
|
+
for (const key of selectedKeys) if (!now.has(key)) {
|
|
949
|
+
const element = editor.getElementByKey(key);
|
|
950
|
+
if (element !== null) removeClassNamesFromElement(element, className);
|
|
951
|
+
}
|
|
952
|
+
selectedKeys.clear();
|
|
953
|
+
for (const key of now) selectedKeys.add(key);
|
|
954
|
+
});
|
|
955
|
+
}
|
|
956
|
+
/**
|
|
957
|
+
* 让编辑器用已采用的插件画 Markdown 插件节点,返回取消注册的函数。
|
|
958
|
+
* 先检查配置(冲突就抛 `RichTextExtensionError`);每个节点都用采用的插件从原文重新读一遍、
|
|
959
|
+
* 交给 core 的 `MarkdownPluginNodeRenderer` 画,所以画法、兜底、出错都和 Markdown 里一样;
|
|
960
|
+
* 存下来的数据不会单独拿来画;插件不认了、或者插件没采用的节点,显示它的原文。
|
|
961
|
+
*/
|
|
962
|
+
function registerMarkdownExtensions(editor, options) {
|
|
963
|
+
const plugins = pluginsOf(options.extensions, options.transformers);
|
|
964
|
+
const unset = setRichTextExtensionNodeDecorator(editor, (facts, format, nodeKey) => h(ExtensionNodeView, {
|
|
965
|
+
key: nodeKey,
|
|
966
|
+
facts,
|
|
967
|
+
format,
|
|
968
|
+
plugins
|
|
969
|
+
}));
|
|
970
|
+
redrawExtensionNodes(editor);
|
|
971
|
+
const stopClick = editor.registerCommand(CLICK_COMMAND, (event) => {
|
|
972
|
+
if (!editor.isEditable() || !(event.target instanceof Node)) return false;
|
|
973
|
+
for (const [key, node] of editor.getEditorState()._nodeMap) {
|
|
974
|
+
if (!$isRichTextExtensionNodeShallow(node)) continue;
|
|
975
|
+
const element = editor.getElementByKey(key);
|
|
976
|
+
if (element !== null && element.contains(event.target)) {
|
|
977
|
+
editor.update(() => {
|
|
978
|
+
const selection = $createNodeSelection();
|
|
979
|
+
selection.add(key);
|
|
980
|
+
$setSelection(selection);
|
|
981
|
+
});
|
|
982
|
+
return true;
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
return false;
|
|
986
|
+
}, COMMAND_PRIORITY_LOW);
|
|
987
|
+
const stopFormat = editor.registerCommand(FORMAT_TEXT_COMMAND, (format) => {
|
|
988
|
+
const selection = $getSelection();
|
|
989
|
+
if (!NODE_FORMATS.has(format) || selection === null) return false;
|
|
990
|
+
const nodes = selection.getNodes().filter((node) => $isRichTextExtensionNode(node) && node.isInline());
|
|
991
|
+
if (nodes.length === 0) return false;
|
|
992
|
+
const textState = $isRangeSelection(selection) ? $nextTextFormat(selection, format) : null;
|
|
993
|
+
if ($isRangeSelection(selection)) selection.formatText(format);
|
|
994
|
+
const isOn = textState ?? !nodes.every((node) => node.hasFormat(format));
|
|
995
|
+
for (const node of nodes) node.setFormatFlag(format, isOn);
|
|
996
|
+
return true;
|
|
997
|
+
}, COMMAND_PRIORITY_LOW);
|
|
998
|
+
const stopRing = syncSelectedRing(editor);
|
|
999
|
+
return () => {
|
|
1000
|
+
stopRing();
|
|
1001
|
+
stopFormat();
|
|
1002
|
+
stopClick();
|
|
1003
|
+
unset();
|
|
1004
|
+
redrawExtensionNodes(editor);
|
|
1005
|
+
};
|
|
1006
|
+
}
|
|
1007
|
+
/** 点击检测要遍历节点表,这里不在 Lexical 的读上下文里,所以只看节点对象的类,不调用 `$` 函数。 */
|
|
1008
|
+
function $isRichTextExtensionNodeShallow(node) {
|
|
1009
|
+
return node instanceof RichTextExtensionNode;
|
|
1010
|
+
}
|
|
1011
|
+
/**
|
|
1012
|
+
* 没有界面的组件:用 `markdownExtensions` 采用的插件画 Markdown 插件节点。
|
|
1013
|
+
* `<RichTextEditor>` 和 `<RichTextView>` 在传了 `markdownExtensions` 时自己会用它。
|
|
1014
|
+
*/
|
|
1015
|
+
const MarkdownExtensionsPlugin = defineComponent({
|
|
1016
|
+
name: "AstryxRichTextMarkdownExtensionsPlugin",
|
|
1017
|
+
props: {
|
|
1018
|
+
extensions: {
|
|
1019
|
+
type: Array,
|
|
1020
|
+
required: true
|
|
1021
|
+
},
|
|
1022
|
+
transformers: {
|
|
1023
|
+
type: Array,
|
|
1024
|
+
required: true
|
|
1025
|
+
}
|
|
1026
|
+
},
|
|
1027
|
+
setup(props) {
|
|
1028
|
+
const editor = useLexicalEditor();
|
|
1029
|
+
let stop;
|
|
1030
|
+
watchEffect(() => {
|
|
1031
|
+
stop?.();
|
|
1032
|
+
stop = registerMarkdownExtensions(editor, {
|
|
1033
|
+
extensions: props.extensions,
|
|
1034
|
+
transformers: props.transformers
|
|
1035
|
+
});
|
|
1036
|
+
});
|
|
1037
|
+
onBeforeUnmount(() => stop?.());
|
|
1038
|
+
return () => null;
|
|
1039
|
+
}
|
|
1040
|
+
});
|
|
1041
|
+
//#endregion
|
|
1042
|
+
//#region src/editor/plugins/RichTextEditorAutoLinkPlugin.ts
|
|
1043
|
+
/**
|
|
1044
|
+
* 没有界面的组件:放在 `<RichTextEditor>` 的默认插槽里,输入或粘贴的网址、邮箱就会自动变成链接。
|
|
1045
|
+
*
|
|
1046
|
+
* ```vue
|
|
1047
|
+
* <RichTextEditor label="Notes">
|
|
1048
|
+
* <RichTextEditorAutoLinkPlugin />
|
|
1049
|
+
* </RichTextEditor>
|
|
1050
|
+
* ```
|
|
1051
|
+
*/
|
|
1052
|
+
const RichTextEditorAutoLinkPlugin = defineComponent({
|
|
1053
|
+
name: "AstryxRichTextEditorAutoLinkPlugin",
|
|
1054
|
+
props: {
|
|
1055
|
+
/** 要识别哪些写法,默认网址和邮箱。用 `createLinkMatcherWithRegExp` 可以加自己的,比如工单号。 */
|
|
1056
|
+
matchers: {
|
|
1057
|
+
type: Array,
|
|
1058
|
+
default: void 0
|
|
1059
|
+
} },
|
|
1060
|
+
emits: {
|
|
1061
|
+
/** 自动加、改、去掉链接时触发:新网址(去掉时是 `null`)和原来的网址。 */
|
|
1062
|
+
change: (_url, _prevUrl) => true },
|
|
1063
|
+
setup(props, { emit }) {
|
|
1064
|
+
const editor = useLexicalEditor();
|
|
1065
|
+
let stop;
|
|
1066
|
+
watchEffect(() => {
|
|
1067
|
+
stop?.();
|
|
1068
|
+
stop = registerRichTextAutoLink(editor, {
|
|
1069
|
+
matchers: props.matchers,
|
|
1070
|
+
onChange: (url, prevUrl) => emit("change", url, prevUrl)
|
|
1071
|
+
});
|
|
1072
|
+
});
|
|
1073
|
+
onBeforeUnmount(() => stop?.());
|
|
1074
|
+
return () => null;
|
|
1075
|
+
}
|
|
1076
|
+
});
|
|
1077
|
+
//#endregion
|
|
1078
|
+
//#region src/editor/plugins/tableScrollRegion.ts
|
|
1079
|
+
/** 只有表格比容器宽的时候,滚动区域才占一个 Tab 停靠点。 */
|
|
1080
|
+
function syncTabStop(wrapper) {
|
|
1081
|
+
if (wrapper.scrollWidth > wrapper.clientWidth) wrapper.tabIndex = 0;
|
|
1082
|
+
else wrapper.removeAttribute("tabindex");
|
|
1083
|
+
}
|
|
1084
|
+
/**
|
|
1085
|
+
* 只读视图里没有光标,键盘没办法滚动宽表格里的内容。所以和 core `Table` 的滚动区域一样:
|
|
1086
|
+
* 每张表格外面的容器是一个叫「表格」的分组,只在表格溢出时才占一个 Tab 停靠点,
|
|
1087
|
+
* 放得下的表格不加停靠点。停靠点是显式写的,因为有的浏览器不会自己让滚动容器可聚焦。
|
|
1088
|
+
*/
|
|
1089
|
+
function registerTableScrollRegion(editor, label) {
|
|
1090
|
+
const regions = /* @__PURE__ */ new Map();
|
|
1091
|
+
function release(key) {
|
|
1092
|
+
regions.get(key)?.observer?.disconnect();
|
|
1093
|
+
regions.delete(key);
|
|
1094
|
+
}
|
|
1095
|
+
function track(key) {
|
|
1096
|
+
const wrapper = editor.getElementByKey(key);
|
|
1097
|
+
if (!(wrapper instanceof HTMLDivElement)) {
|
|
1098
|
+
release(key);
|
|
1099
|
+
return;
|
|
1100
|
+
}
|
|
1101
|
+
if (regions.get(key)?.wrapper === wrapper) {
|
|
1102
|
+
syncTabStop(wrapper);
|
|
1103
|
+
return;
|
|
1104
|
+
}
|
|
1105
|
+
release(key);
|
|
1106
|
+
wrapper.setAttribute("role", "group");
|
|
1107
|
+
wrapper.setAttribute("aria-label", label());
|
|
1108
|
+
let observer = null;
|
|
1109
|
+
if (typeof ResizeObserver !== "undefined") {
|
|
1110
|
+
observer = new ResizeObserver(() => syncTabStop(wrapper));
|
|
1111
|
+
observer.observe(wrapper);
|
|
1112
|
+
const table = wrapper.querySelector(":scope > table");
|
|
1113
|
+
if (table !== null) observer.observe(table);
|
|
1114
|
+
}
|
|
1115
|
+
regions.set(key, {
|
|
1116
|
+
wrapper,
|
|
1117
|
+
observer
|
|
1118
|
+
});
|
|
1119
|
+
syncTabStop(wrapper);
|
|
1120
|
+
}
|
|
1121
|
+
const stop = editor.registerMutationListener(TableNode, (mutations) => {
|
|
1122
|
+
for (const [key, mutation] of mutations) if (mutation === "destroyed") release(key);
|
|
1123
|
+
else track(key);
|
|
1124
|
+
}, { skipInitialization: false });
|
|
1125
|
+
return () => {
|
|
1126
|
+
stop();
|
|
1127
|
+
for (const key of [...regions.keys()]) release(key);
|
|
1128
|
+
};
|
|
1129
|
+
}
|
|
1130
|
+
//#endregion
|
|
1131
|
+
//#region src/editor/plugins/TaskCheckboxPlugin.ts
|
|
1132
|
+
/** core 小号勾选框的宽度。从右往左排版时,勾选框要贴着项的右边。 */
|
|
1133
|
+
const CHECKBOX_SIZE = 20;
|
|
1134
|
+
/** 主题靠这个属性认出任务项:不画列表标记,给勾选框留位置。 */
|
|
1135
|
+
const TASK_ATTRIBUTE = "data-richtext-task";
|
|
1136
|
+
/**
|
|
1137
|
+
* 文档里所有自己有文字的无序列表项,按文档顺序,并标明是不是任务项。
|
|
1138
|
+
* 只装着一个子列表的项是 Lexical 用来放嵌套列表的外壳,没有文字,不算。
|
|
1139
|
+
*/
|
|
1140
|
+
function $bulletItems() {
|
|
1141
|
+
const items = [];
|
|
1142
|
+
const visit = (node) => {
|
|
1143
|
+
if (!$isListNode(node)) return;
|
|
1144
|
+
for (const item of node.getChildren()) {
|
|
1145
|
+
if (!$isListItemNode(item)) continue;
|
|
1146
|
+
if (!(item.getChildrenSize() === 1 && $isListNode(item.getFirstChild())) && node.getListType() !== "number") items.push({
|
|
1147
|
+
item,
|
|
1148
|
+
task: $getTaskState(item)
|
|
1149
|
+
});
|
|
1150
|
+
item.getChildren().forEach(visit);
|
|
1151
|
+
}
|
|
1152
|
+
};
|
|
1153
|
+
$getRoot().getChildren().forEach(visit);
|
|
1154
|
+
return items;
|
|
1155
|
+
}
|
|
1156
|
+
function samePlacements(a, b) {
|
|
1157
|
+
return a.length === b.length && a.every((p, i) => {
|
|
1158
|
+
const q = b[i];
|
|
1159
|
+
return p.key === q.key && p.checked === q.checked && p.label === q.label && p.top === q.top && p.left === q.left;
|
|
1160
|
+
});
|
|
1161
|
+
}
|
|
1162
|
+
/**
|
|
1163
|
+
* 任务项的勾选框。
|
|
1164
|
+
*
|
|
1165
|
+
* 列表项不能同时当复选框用(Lexical 自己的勾选列表会给它换一个角色),可编辑的文字里也塞不进别的元素。
|
|
1166
|
+
* 所以项还是列表项,只加一个属性让主题去掉标记、留出位置;勾选框是编辑区的兄弟元素,
|
|
1167
|
+
* 画在项开头的空位上。项用 `aria-owns` 把勾选框认作自己的,读屏软件就能在项里、按文档顺序找到它和它的状态。
|
|
1168
|
+
* 勾选框不占 Tab 停靠点,否则它们会排在整篇文档之后:编辑时用 Mod+Enter 勾选光标所在的项,只读时它们是只读的。
|
|
1169
|
+
*/
|
|
1170
|
+
const TaskCheckboxPlugin = defineComponent({
|
|
1171
|
+
name: "AstryxRichTextTaskCheckboxPlugin",
|
|
1172
|
+
props: {
|
|
1173
|
+
/** 只读或禁用时,勾选框不能改,也不监听 Enter 和 Mod+Enter。 */
|
|
1174
|
+
isReadOnly: {
|
|
1175
|
+
type: Boolean,
|
|
1176
|
+
default: false
|
|
1177
|
+
} },
|
|
1178
|
+
setup(props) {
|
|
1179
|
+
const editor = useLexicalEditor();
|
|
1180
|
+
const idPrefix = `astryx-richtext-task-${useId()}`;
|
|
1181
|
+
let stopEditing;
|
|
1182
|
+
watchEffect(() => {
|
|
1183
|
+
stopEditing?.();
|
|
1184
|
+
stopEditing = props.isReadOnly ? void 0 : registerTaskListEditing(editor);
|
|
1185
|
+
});
|
|
1186
|
+
onBeforeUnmount(() => stopEditing?.());
|
|
1187
|
+
const placements = useOverlayPlacements(editor, (origin) => {
|
|
1188
|
+
if (editor.getRootElement() === null) return [];
|
|
1189
|
+
return $bulletItems().flatMap(({ item, task }) => {
|
|
1190
|
+
const element = editor.getElementByKey(item.getKey());
|
|
1191
|
+
if (element === null) return [];
|
|
1192
|
+
if (task === null) {
|
|
1193
|
+
element.removeAttribute(TASK_ATTRIBUTE);
|
|
1194
|
+
element.removeAttribute("aria-owns");
|
|
1195
|
+
return [];
|
|
1196
|
+
}
|
|
1197
|
+
element.setAttribute(TASK_ATTRIBUTE, "");
|
|
1198
|
+
element.removeAttribute("role");
|
|
1199
|
+
element.removeAttribute("aria-checked");
|
|
1200
|
+
element.removeAttribute("tabindex");
|
|
1201
|
+
element.setAttribute("aria-owns", `${idPrefix}-${item.getKey()}`);
|
|
1202
|
+
const box = element.getBoundingClientRect();
|
|
1203
|
+
const style = getComputedStyle(element);
|
|
1204
|
+
const isRtl = style.direction === "rtl";
|
|
1205
|
+
return [{
|
|
1206
|
+
key: item.getKey(),
|
|
1207
|
+
checked: task === "checked",
|
|
1208
|
+
label: item.getTextContent(),
|
|
1209
|
+
top: box.top - origin.top + Number.parseFloat(style.paddingTop || "0"),
|
|
1210
|
+
left: (isRtl ? box.right - CHECKBOX_SIZE : box.left) - origin.left
|
|
1211
|
+
}];
|
|
1212
|
+
});
|
|
1213
|
+
}, samePlacements);
|
|
1214
|
+
function setChecked(key, checked) {
|
|
1215
|
+
editor.update(() => {
|
|
1216
|
+
const node = $getNodeByKey(key);
|
|
1217
|
+
if ($isListItemNode(node)) $setTaskState(node, checked ? "checked" : "unchecked");
|
|
1218
|
+
});
|
|
1219
|
+
}
|
|
1220
|
+
return () => placements.value.map((p) => h("div", {
|
|
1221
|
+
"key": p.key,
|
|
1222
|
+
"id": `${idPrefix}-${p.key}`,
|
|
1223
|
+
"class": "astryx-richtext-task-checkbox",
|
|
1224
|
+
"data-richtext-task-checkbox": "",
|
|
1225
|
+
"style": {
|
|
1226
|
+
position: "absolute",
|
|
1227
|
+
top: `${p.top}px`,
|
|
1228
|
+
left: `${p.left}px`
|
|
1229
|
+
}
|
|
1230
|
+
}, [h(CheckboxInput, {
|
|
1231
|
+
modelValue: p.checked,
|
|
1232
|
+
size: "sm",
|
|
1233
|
+
label: p.label,
|
|
1234
|
+
isLabelHidden: true,
|
|
1235
|
+
isReadOnly: props.isReadOnly,
|
|
1236
|
+
tabindex: -1,
|
|
1237
|
+
onChange: (checked) => setChecked(p.key, checked)
|
|
1238
|
+
})]));
|
|
1239
|
+
}
|
|
1240
|
+
});
|
|
1241
|
+
//#endregion
|
|
1242
|
+
//#region src/editor/DecoratorTeleports.ts
|
|
1243
|
+
/**
|
|
1244
|
+
* Lexical 的装饰节点(DecoratorNode)在文档里只占一个位置,里面画什么交给界面框架。
|
|
1245
|
+
* 这个组件监听编辑器的装饰节点变化,把每个节点的 `decorate()` 返回值用 `Teleport`
|
|
1246
|
+
* 画进 Lexical 给它建好的那个元素里。Vue 的组件树、响应式和 `provide`/`inject` 因此
|
|
1247
|
+
* 都能在节点内容里照常使用。
|
|
1248
|
+
*
|
|
1249
|
+
* `decorate()` 返回 Vue 的 `VNodeChild`(组件、字符串、vnode);返回 `null` 的节点不画。
|
|
1250
|
+
*/
|
|
1251
|
+
const DecoratorTeleports = defineComponent({
|
|
1252
|
+
name: "AstryxRichTextDecoratorTeleports",
|
|
1253
|
+
props: { editor: {
|
|
1254
|
+
type: Object,
|
|
1255
|
+
required: true
|
|
1256
|
+
} },
|
|
1257
|
+
setup(props) {
|
|
1258
|
+
const decorators = shallowRef({ ...props.editor.getDecorators() });
|
|
1259
|
+
const stop = props.editor.registerDecoratorListener((next) => {
|
|
1260
|
+
decorators.value = { ...next };
|
|
1261
|
+
});
|
|
1262
|
+
onBeforeUnmount(stop);
|
|
1263
|
+
return () => Object.entries(decorators.value).flatMap(([key, content]) => {
|
|
1264
|
+
const element = props.editor.getElementByKey(key);
|
|
1265
|
+
if (element === null || content == null) return [];
|
|
1266
|
+
return [h(Teleport, {
|
|
1267
|
+
to: element,
|
|
1268
|
+
key
|
|
1269
|
+
}, [content])];
|
|
1270
|
+
});
|
|
1271
|
+
}
|
|
1272
|
+
});
|
|
1273
|
+
//#endregion
|
|
1274
|
+
//#region src/editor/messages.ts
|
|
1275
|
+
/**
|
|
1276
|
+
* 取编辑器和工具栏的文案。文案放在 core 的 `locale/messages/rich-text-editor.ts` 里,
|
|
1277
|
+
* 随 `<InternationalizationProvider>` 的语言切换;包本身不再自带译文。
|
|
1278
|
+
*/
|
|
1279
|
+
function useRichTextMessages() {
|
|
1280
|
+
const messages = useAstryxMessages();
|
|
1281
|
+
const table = computed(() => messages.value.richTextEditor);
|
|
1282
|
+
return (key) => {
|
|
1283
|
+
let node = table.value;
|
|
1284
|
+
for (const part of key.split(".")) node = node?.[part];
|
|
1285
|
+
return typeof node === "string" ? node : key;
|
|
1286
|
+
};
|
|
1287
|
+
}
|
|
1288
|
+
//#endregion
|
|
1289
|
+
//#region src/editor/RichTextEditor.vue
|
|
1290
|
+
const _hoisted_1$2 = [
|
|
1291
|
+
"data-size",
|
|
1292
|
+
"data-status",
|
|
1293
|
+
"data-disabled",
|
|
1294
|
+
"data-readonly",
|
|
1295
|
+
"data-with-toolbar"
|
|
1296
|
+
];
|
|
1297
|
+
const _hoisted_2 = { class: "astryx-richtext-editor__body" };
|
|
1298
|
+
const _hoisted_3 = { class: "astryx-richtext-editor__root" };
|
|
1299
|
+
const _hoisted_4 = [
|
|
1300
|
+
"data-label-id",
|
|
1301
|
+
"data-described-by",
|
|
1302
|
+
"data-empty",
|
|
1303
|
+
"onVnodeMounted",
|
|
1304
|
+
"onVnodeUpdated"
|
|
1305
|
+
];
|
|
1306
|
+
const _hoisted_5 = ["data-over"];
|
|
1307
|
+
const COUNTER_WARNING_THRESHOLD = .8;
|
|
1308
|
+
const _sfc_main = /*@__PURE__*/ defineComponent({
|
|
1309
|
+
name: "AstryxRichTextEditor",
|
|
1310
|
+
inheritAttrs: false,
|
|
1311
|
+
__name: "RichTextEditor",
|
|
1312
|
+
props: {
|
|
1313
|
+
label: {},
|
|
1314
|
+
isLabelHidden: { type: Boolean },
|
|
1315
|
+
description: {},
|
|
1316
|
+
isOptional: { type: Boolean },
|
|
1317
|
+
isRequired: { type: Boolean },
|
|
1318
|
+
defaultValue: {},
|
|
1319
|
+
placeholder: {},
|
|
1320
|
+
isReadOnly: { type: Boolean },
|
|
1321
|
+
isDisabled: { type: Boolean },
|
|
1322
|
+
status: {},
|
|
1323
|
+
statusVariant: { default: "attached" },
|
|
1324
|
+
width: {},
|
|
1325
|
+
minHeight: { default: "4.5rem" },
|
|
1326
|
+
labelTooltip: {},
|
|
1327
|
+
size: { default: "md" },
|
|
1328
|
+
nodes: {},
|
|
1329
|
+
extensions: {},
|
|
1330
|
+
markdownExtensions: {},
|
|
1331
|
+
hasMarkdownShortcuts: {
|
|
1332
|
+
type: Boolean,
|
|
1333
|
+
default: true
|
|
1334
|
+
},
|
|
1335
|
+
transformers: {},
|
|
1336
|
+
hasAutoFocus: { type: Boolean },
|
|
1337
|
+
tabEscapeHint: {},
|
|
1338
|
+
maxLength: {},
|
|
1339
|
+
namespace: { default: "astryx-editor" }
|
|
1340
|
+
},
|
|
1341
|
+
emits: ["change"],
|
|
1342
|
+
setup(__props, { expose: __expose, emit: __emit }) {
|
|
1343
|
+
const props = __props;
|
|
1344
|
+
const emit = __emit;
|
|
1345
|
+
const attrs = useAttrs();
|
|
1346
|
+
const t = useRichTextMessages();
|
|
1347
|
+
const coreMessages = useAstryxMessages();
|
|
1348
|
+
/** 清空时用的状态:根下面一个空段落。用 `setEditorState` 重置,也会触发 `change`。 */
|
|
1349
|
+
const EMPTY_EDITOR_STATE = JSON.stringify({ root: {
|
|
1350
|
+
children: [{
|
|
1351
|
+
children: [],
|
|
1352
|
+
direction: null,
|
|
1353
|
+
format: "",
|
|
1354
|
+
indent: 0,
|
|
1355
|
+
type: "paragraph",
|
|
1356
|
+
version: 1
|
|
1357
|
+
}],
|
|
1358
|
+
direction: null,
|
|
1359
|
+
format: "",
|
|
1360
|
+
indent: 0,
|
|
1361
|
+
type: "root",
|
|
1362
|
+
version: 1
|
|
1363
|
+
} });
|
|
1364
|
+
const inputId = `astryx-rich-text-${useId()}`;
|
|
1365
|
+
const placeholderId = `${inputId}-placeholder`;
|
|
1366
|
+
const counterId = `${inputId}-counter`;
|
|
1367
|
+
const tabEscapeHintId = `${inputId}-tab-escape`;
|
|
1368
|
+
const surface = useTemplateRef("surface");
|
|
1369
|
+
const editor = shallowRef();
|
|
1370
|
+
const isEmpty = shallowRef(true);
|
|
1371
|
+
const charCount = shallowRef(0);
|
|
1372
|
+
const editable = computed(() => !props.isReadOnly && !props.isDisabled);
|
|
1373
|
+
const tabEscapeHint = computed(() => props.tabEscapeHint ?? t("tabEscapeHint"));
|
|
1374
|
+
const hasTabEscapeHint = computed(() => editable.value && tabEscapeHint.value !== "");
|
|
1375
|
+
function describedBy(fieldDescribedBy) {
|
|
1376
|
+
return [
|
|
1377
|
+
fieldDescribedBy,
|
|
1378
|
+
props.placeholder ? placeholderId : null,
|
|
1379
|
+
props.maxLength != null ? counterId : null,
|
|
1380
|
+
hasTabEscapeHint.value ? tabEscapeHintId : null
|
|
1381
|
+
].filter(Boolean).join(" ") || void 0;
|
|
1382
|
+
}
|
|
1383
|
+
const isOverLimit = computed(() => props.maxLength != null && charCount.value > props.maxLength);
|
|
1384
|
+
const counterAnnouncement = computed(() => {
|
|
1385
|
+
const max = props.maxLength;
|
|
1386
|
+
if (max == null || charCount.value < max * COUNTER_WARNING_THRESHOLD) return "";
|
|
1387
|
+
return charCount.value > max ? coreMessages.value.textArea.charactersOverLimit(charCount.value - max) : coreMessages.value.textArea.charactersRemaining(max - charCount.value);
|
|
1388
|
+
});
|
|
1389
|
+
function cssLength(value) {
|
|
1390
|
+
return typeof value === "number" ? `${value}px` : value;
|
|
1391
|
+
}
|
|
1392
|
+
/** 把编辑器的根元素设成可编辑区,并补上 Lexical 不会给的无障碍属性。 */
|
|
1393
|
+
function syncSurfaceAttributes(root) {
|
|
1394
|
+
if (root === null) return;
|
|
1395
|
+
root.id = inputId;
|
|
1396
|
+
root.contentEditable = editable.value ? "true" : "false";
|
|
1397
|
+
root.setAttribute("role", "textbox");
|
|
1398
|
+
root.setAttribute("aria-multiline", "true");
|
|
1399
|
+
root.classList.add("astryx-richtext-editor__content");
|
|
1400
|
+
root.style.setProperty("--astryx-richtext-min-height", cssLength(props.minHeight));
|
|
1401
|
+
setOrRemove(root, "aria-required", props.isRequired && !props.isOptional ? "true" : null);
|
|
1402
|
+
setOrRemove(root, "aria-invalid", props.status?.type === "error" ? "true" : null);
|
|
1403
|
+
setOrRemove(root, "aria-placeholder", props.placeholder ?? null);
|
|
1404
|
+
root.removeAttribute("aria-disabled");
|
|
1405
|
+
root.removeAttribute("aria-readonly");
|
|
1406
|
+
if (props.isDisabled) {
|
|
1407
|
+
root.setAttribute("aria-disabled", "true");
|
|
1408
|
+
root.removeAttribute("tabindex");
|
|
1409
|
+
} else if (props.isReadOnly) {
|
|
1410
|
+
root.setAttribute("aria-readonly", "true");
|
|
1411
|
+
root.tabIndex = 0;
|
|
1412
|
+
} else root.removeAttribute("tabindex");
|
|
1413
|
+
}
|
|
1414
|
+
function setOrRemove(element, name, value) {
|
|
1415
|
+
if (value === null) element.removeAttribute(name);
|
|
1416
|
+
else element.setAttribute(name, value);
|
|
1417
|
+
}
|
|
1418
|
+
function labelAttributes(root, labelId, fieldDescribedBy) {
|
|
1419
|
+
if (root === null) return;
|
|
1420
|
+
if (props.isLabelHidden) root.setAttribute("aria-label", props.label);
|
|
1421
|
+
else root.setAttribute("aria-labelledby", labelId);
|
|
1422
|
+
setOrRemove(root, "aria-describedby", describedBy(fieldDescribedBy) ?? null);
|
|
1423
|
+
}
|
|
1424
|
+
const labelState = {
|
|
1425
|
+
labelId: "",
|
|
1426
|
+
describedBy: void 0
|
|
1427
|
+
};
|
|
1428
|
+
function applyAttributes() {
|
|
1429
|
+
const root = editor.value?.getRootElement() ?? null;
|
|
1430
|
+
syncSurfaceAttributes(root);
|
|
1431
|
+
labelAttributes(root, labelState.labelId, labelState.describedBy);
|
|
1432
|
+
}
|
|
1433
|
+
/**
|
|
1434
|
+
* 占位文字是否该显示:文档里只有一个空段落。有了分割线、表格这类没有文字的块,也不该显示。
|
|
1435
|
+
* 和 Lexical 官方的 `$canShowPlaceholder` 判断一致,这里直接读,免得多装一个依赖。
|
|
1436
|
+
*/
|
|
1437
|
+
function readEmpty(instance) {
|
|
1438
|
+
return instance.getEditorState().read(() => {
|
|
1439
|
+
const root = $getRoot();
|
|
1440
|
+
if (root.getTextContent() !== "" || instance.isComposing()) return false;
|
|
1441
|
+
const first = root.getFirstChild();
|
|
1442
|
+
return root.getChildrenSize() === 0 || root.getChildrenSize() === 1 && $isParagraphNode(first) && first.isEmpty();
|
|
1443
|
+
});
|
|
1444
|
+
}
|
|
1445
|
+
const instance = createRichTextEditor({
|
|
1446
|
+
namespace: props.namespace,
|
|
1447
|
+
initialState: props.defaultValue,
|
|
1448
|
+
editable: editable.value,
|
|
1449
|
+
nodes: props.nodes,
|
|
1450
|
+
extensions: props.extensions,
|
|
1451
|
+
hasMarkdownShortcuts: props.hasMarkdownShortcuts,
|
|
1452
|
+
transformers: props.transformers
|
|
1453
|
+
});
|
|
1454
|
+
editor.value = instance;
|
|
1455
|
+
let stopListening;
|
|
1456
|
+
onMounted(() => {
|
|
1457
|
+
const root = surface.value;
|
|
1458
|
+
if (root === null) return;
|
|
1459
|
+
instance.setRootElement(root);
|
|
1460
|
+
applyAttributes();
|
|
1461
|
+
isEmpty.value = readEmpty(instance);
|
|
1462
|
+
charCount.value = root.textContent?.length ?? 0;
|
|
1463
|
+
stopListening = instance.registerUpdateListener(({ editorState, dirtyElements, dirtyLeaves, tags }) => {
|
|
1464
|
+
isEmpty.value = readEmpty(instance);
|
|
1465
|
+
charCount.value = instance.getRootElement()?.textContent?.length ?? 0;
|
|
1466
|
+
if (dirtyElements.size === 0 && dirtyLeaves.size === 0 || tags.has("history-merge")) return;
|
|
1467
|
+
emit("change", editorState, instance);
|
|
1468
|
+
});
|
|
1469
|
+
if (props.hasAutoFocus) instance.focus();
|
|
1470
|
+
});
|
|
1471
|
+
onBeforeUnmount(() => {
|
|
1472
|
+
stopListening?.();
|
|
1473
|
+
instance.setRootElement(null);
|
|
1474
|
+
instance.dispose();
|
|
1475
|
+
});
|
|
1476
|
+
watch(editable, (next) => {
|
|
1477
|
+
editor.value?.setEditable(next);
|
|
1478
|
+
applyAttributes();
|
|
1479
|
+
});
|
|
1480
|
+
watch(() => [
|
|
1481
|
+
props.isReadOnly,
|
|
1482
|
+
props.isDisabled,
|
|
1483
|
+
props.isRequired,
|
|
1484
|
+
props.isOptional,
|
|
1485
|
+
props.isLabelHidden,
|
|
1486
|
+
props.label,
|
|
1487
|
+
props.placeholder,
|
|
1488
|
+
props.minHeight,
|
|
1489
|
+
props.status?.type,
|
|
1490
|
+
props.maxLength,
|
|
1491
|
+
hasTabEscapeHint.value
|
|
1492
|
+
], applyAttributes, { flush: "post" });
|
|
1493
|
+
provide(editorKey, instance);
|
|
1494
|
+
function requireEditor() {
|
|
1495
|
+
return instance;
|
|
1496
|
+
}
|
|
1497
|
+
const transformers = computed(() => [...props.transformers ?? DEFAULT_TRANSFORMERS]);
|
|
1498
|
+
__expose({
|
|
1499
|
+
focus() {
|
|
1500
|
+
if (editable.value) requireEditor().focus();
|
|
1501
|
+
},
|
|
1502
|
+
clear() {
|
|
1503
|
+
if (!editable.value) return;
|
|
1504
|
+
instance.setEditorState(instance.parseEditorState(EMPTY_EDITOR_STATE));
|
|
1505
|
+
},
|
|
1506
|
+
getEditorState: () => requireEditor().getEditorState(),
|
|
1507
|
+
getMarkdown: () => requireEditor().getEditorState().read(() => $exportMarkdownKeepingSource(transformers.value)),
|
|
1508
|
+
getHTML: () => {
|
|
1509
|
+
return instance.getEditorState().read(() => $generateHtmlFromNodes(instance, null));
|
|
1510
|
+
},
|
|
1511
|
+
getEditor: requireEditor
|
|
1512
|
+
});
|
|
1513
|
+
const rootAttrs = computed(() => ({
|
|
1514
|
+
class: attrs.class,
|
|
1515
|
+
style: attrs.style
|
|
1516
|
+
}));
|
|
1517
|
+
const restAttrs = computed(() => {
|
|
1518
|
+
const { class: _class, style: _style, ...rest } = attrs;
|
|
1519
|
+
return rest;
|
|
1520
|
+
});
|
|
1521
|
+
return (_ctx, _cache) => {
|
|
1522
|
+
return openBlock(), createElementBlock(Fragment, null, [createVNode(unref(Field), mergeProps({
|
|
1523
|
+
label: __props.label,
|
|
1524
|
+
"input-id": inputId,
|
|
1525
|
+
description: __props.description,
|
|
1526
|
+
width: __props.width,
|
|
1527
|
+
"is-label-hidden": __props.isLabelHidden,
|
|
1528
|
+
"is-disabled": __props.isDisabled,
|
|
1529
|
+
"is-optional": __props.isOptional,
|
|
1530
|
+
"is-required": __props.isRequired,
|
|
1531
|
+
"label-tooltip": __props.labelTooltip,
|
|
1532
|
+
status: __props.status,
|
|
1533
|
+
"status-variant": __props.statusVariant
|
|
1534
|
+
}, rootAttrs.value), {
|
|
1535
|
+
default: withCtx((field) => [createElementVNode("div", {
|
|
1536
|
+
class: "astryx-richtext-editor",
|
|
1537
|
+
"data-size": __props.size,
|
|
1538
|
+
"data-status": __props.status?.type,
|
|
1539
|
+
"data-disabled": __props.isDisabled || void 0,
|
|
1540
|
+
"data-readonly": __props.isReadOnly || void 0,
|
|
1541
|
+
"data-with-toolbar": _ctx.$slots.toolbar ? "" : void 0
|
|
1542
|
+
}, [
|
|
1543
|
+
renderSlot(_ctx.$slots, "toolbar"),
|
|
1544
|
+
createElementVNode("div", _hoisted_2, [createElementVNode("div", _hoisted_3, [
|
|
1545
|
+
createElementVNode("div", mergeProps({
|
|
1546
|
+
ref_key: "surface",
|
|
1547
|
+
ref: surface
|
|
1548
|
+
}, restAttrs.value, {
|
|
1549
|
+
spellcheck: "true",
|
|
1550
|
+
"data-label-id": field.labelId,
|
|
1551
|
+
"data-described-by": field.describedBy,
|
|
1552
|
+
"data-empty": isEmpty.value || void 0,
|
|
1553
|
+
style: { "--astryx-richtext-min-height": cssLength(__props.minHeight) },
|
|
1554
|
+
onVnodeMounted: () => {
|
|
1555
|
+
labelState.labelId = field.labelId;
|
|
1556
|
+
labelState.describedBy = field.describedBy;
|
|
1557
|
+
applyAttributes();
|
|
1558
|
+
},
|
|
1559
|
+
onVnodeUpdated: () => {
|
|
1560
|
+
labelState.labelId = field.labelId;
|
|
1561
|
+
labelState.describedBy = field.describedBy;
|
|
1562
|
+
applyAttributes();
|
|
1563
|
+
}
|
|
1564
|
+
}), null, 16, _hoisted_4),
|
|
1565
|
+
__props.placeholder && isEmpty.value ? (openBlock(), createElementBlock("div", {
|
|
1566
|
+
key: 0,
|
|
1567
|
+
id: placeholderId,
|
|
1568
|
+
class: "astryx-richtext-editor__placeholder",
|
|
1569
|
+
"aria-hidden": "true"
|
|
1570
|
+
}, toDisplayString(__props.placeholder), 1)) : createCommentVNode("v-if", true),
|
|
1571
|
+
createCommentVNode("\n 这几个叠在编辑区上面:位置是相对「编辑区的父元素」量出来的,\n 所以要和编辑区同级放在这个定位元素里,不能放到外面去。\n "),
|
|
1572
|
+
createVNode(unref(TaskCheckboxPlugin), { "is-read-only": !editable.value }, null, 8, ["is-read-only"]),
|
|
1573
|
+
createVNode(unref(CodeBlockHeaderPlugin)),
|
|
1574
|
+
createVNode(unref(CodeSyntaxPlugin)),
|
|
1575
|
+
__props.markdownExtensions && __props.markdownExtensions.length > 0 ? (openBlock(), createBlock(unref(MarkdownExtensionsPlugin), {
|
|
1576
|
+
key: 1,
|
|
1577
|
+
extensions: __props.markdownExtensions,
|
|
1578
|
+
transformers: transformers.value
|
|
1579
|
+
}, null, 8, ["extensions", "transformers"])) : createCommentVNode("v-if", true)
|
|
1580
|
+
])]),
|
|
1581
|
+
editor.value ? (openBlock(), createBlock(unref(DecoratorTeleports), {
|
|
1582
|
+
key: 0,
|
|
1583
|
+
editor: editor.value
|
|
1584
|
+
}, null, 8, ["editor"])) : createCommentVNode("v-if", true),
|
|
1585
|
+
renderSlot(_ctx.$slots, "default")
|
|
1586
|
+
], 8, _hoisted_1$2), hasTabEscapeHint.value ? (openBlock(), createBlock(unref(VisuallyHidden), {
|
|
1587
|
+
key: 0,
|
|
1588
|
+
id: tabEscapeHintId
|
|
1589
|
+
}, {
|
|
1590
|
+
default: withCtx(() => [createTextVNode(toDisplayString(tabEscapeHint.value), 1)]),
|
|
1591
|
+
_: 1
|
|
1592
|
+
})) : createCommentVNode("v-if", true)]),
|
|
1593
|
+
_: 3
|
|
1594
|
+
}, 16, [
|
|
1595
|
+
"label",
|
|
1596
|
+
"description",
|
|
1597
|
+
"width",
|
|
1598
|
+
"is-label-hidden",
|
|
1599
|
+
"is-disabled",
|
|
1600
|
+
"is-optional",
|
|
1601
|
+
"is-required",
|
|
1602
|
+
"label-tooltip",
|
|
1603
|
+
"status",
|
|
1604
|
+
"status-variant"
|
|
1605
|
+
]), __props.maxLength != null ? (openBlock(), createElementBlock("div", {
|
|
1606
|
+
key: 0,
|
|
1607
|
+
id: counterId,
|
|
1608
|
+
class: "astryx-richtext-editor__counter",
|
|
1609
|
+
"data-over": isOverLimit.value || void 0
|
|
1610
|
+
}, [createTextVNode(toDisplayString(charCount.value) + "/" + toDisplayString(__props.maxLength) + " ", 1), createVNode(unref(VisuallyHidden), { "aria-live": "polite" }, {
|
|
1611
|
+
default: withCtx(() => [createTextVNode(toDisplayString(counterAnnouncement.value), 1)]),
|
|
1612
|
+
_: 1
|
|
1613
|
+
})], 8, _hoisted_5)) : createCommentVNode("v-if", true)], 64);
|
|
1614
|
+
};
|
|
1615
|
+
}
|
|
1616
|
+
});
|
|
1617
|
+
//#endregion
|
|
1618
|
+
//#region src/editor/ToolbarIcon.vue
|
|
1619
|
+
const _hoisted_1$1 = ["data-directional"];
|
|
1620
|
+
const _sfc_main$3 = /*@__PURE__*/ defineComponent({
|
|
1621
|
+
name: "AstryxRichTextToolbarIcon",
|
|
1622
|
+
__name: "ToolbarIcon",
|
|
1623
|
+
props: {
|
|
1624
|
+
name: {},
|
|
1625
|
+
isDirectional: { type: Boolean }
|
|
1626
|
+
},
|
|
1627
|
+
setup(__props) {
|
|
1628
|
+
const props = __props;
|
|
1629
|
+
const themed = useSemanticIcon(() => RICHTEXT_ICON_KEYS[props.name]);
|
|
1630
|
+
const Fallback = computed(() => builtInIcon(props.name));
|
|
1631
|
+
return (_ctx, _cache) => {
|
|
1632
|
+
return openBlock(), createElementBlock("span", {
|
|
1633
|
+
class: "astryx-richtext-toolbar__glyph",
|
|
1634
|
+
"data-directional": __props.isDirectional || void 0,
|
|
1635
|
+
"aria-hidden": "true"
|
|
1636
|
+
}, [unref(themed) ? (openBlock(), createBlock(unref(Icon), {
|
|
1637
|
+
key: 0,
|
|
1638
|
+
name: unref(themed),
|
|
1639
|
+
size: "sm"
|
|
1640
|
+
}, null, 8, ["name"])) : (openBlock(), createBlock(resolveDynamicComponent(Fallback.value), { key: 1 }))], 8, _hoisted_1$1);
|
|
1641
|
+
};
|
|
1642
|
+
}
|
|
1643
|
+
});
|
|
1644
|
+
//#endregion
|
|
1645
|
+
//#region src/editor/useLinkDialog.ts
|
|
1646
|
+
/**
|
|
1647
|
+
* 链接对话框的状态和动作。对话框一打开编辑器就失焦、选区没了,
|
|
1648
|
+
* 所以打开前先存下选区,提交时放回去,再下指令。
|
|
1649
|
+
*/
|
|
1650
|
+
function useLinkDialog(options) {
|
|
1651
|
+
const { editor, state, t } = options;
|
|
1652
|
+
const isOpen = shallowRef(false);
|
|
1653
|
+
const isEditing = shallowRef(false);
|
|
1654
|
+
const url = shallowRef("");
|
|
1655
|
+
const error = shallowRef("");
|
|
1656
|
+
function restoreSelection() {
|
|
1657
|
+
const saved = state.savedSelection.value;
|
|
1658
|
+
if (saved === null) return;
|
|
1659
|
+
editor.update(() => {
|
|
1660
|
+
$setSelection(saved.clone());
|
|
1661
|
+
});
|
|
1662
|
+
}
|
|
1663
|
+
/** 把网址写进选区。网址不安全时什么也不做并返回 false。 */
|
|
1664
|
+
function apply(entered) {
|
|
1665
|
+
const trimmed = entered.trim();
|
|
1666
|
+
const safe = sanitizeUrl(trimmed);
|
|
1667
|
+
if (safe === "about:blank") return false;
|
|
1668
|
+
restoreSelection();
|
|
1669
|
+
const attributes = options.hasNewTabLinks() ? {
|
|
1670
|
+
target: "_blank",
|
|
1671
|
+
rel: "noopener noreferrer"
|
|
1672
|
+
} : {};
|
|
1673
|
+
if (!editor.dispatchCommand(TOGGLE_LINK_COMMAND, {
|
|
1674
|
+
url: safe,
|
|
1675
|
+
...attributes
|
|
1676
|
+
})) editor.update(() => {
|
|
1677
|
+
const selection = $getSelection();
|
|
1678
|
+
if ($isRangeSelection(selection) && selection.isCollapsed()) {
|
|
1679
|
+
const node = $createLinkNode(safe, attributes);
|
|
1680
|
+
node.append($createTextNode(trimmed));
|
|
1681
|
+
selection.insertNodes([node]);
|
|
1682
|
+
}
|
|
1683
|
+
});
|
|
1684
|
+
return true;
|
|
1685
|
+
}
|
|
1686
|
+
function closeToEditor() {
|
|
1687
|
+
isOpen.value = false;
|
|
1688
|
+
error.value = "";
|
|
1689
|
+
requestAnimationFrame(() => editor.focus());
|
|
1690
|
+
}
|
|
1691
|
+
function toggle() {
|
|
1692
|
+
if (!editor.isEditable()) return;
|
|
1693
|
+
const context = state.readLinkContext();
|
|
1694
|
+
const prompt = options.promptForUrl();
|
|
1695
|
+
if (prompt !== void 0) {
|
|
1696
|
+
if (context.isLink) {
|
|
1697
|
+
restoreSelection();
|
|
1698
|
+
editor.dispatchCommand(TOGGLE_LINK_COMMAND, null);
|
|
1699
|
+
return;
|
|
1700
|
+
}
|
|
1701
|
+
const entered = prompt(context.selectedText);
|
|
1702
|
+
if (entered != null && entered.trim() !== "") apply(entered);
|
|
1703
|
+
return;
|
|
1704
|
+
}
|
|
1705
|
+
url.value = context.url || (context.selectedText.startsWith("http") ? context.selectedText : "https://");
|
|
1706
|
+
isEditing.value = context.isLink;
|
|
1707
|
+
error.value = "";
|
|
1708
|
+
isOpen.value = true;
|
|
1709
|
+
}
|
|
1710
|
+
function setOpen(open) {
|
|
1711
|
+
isOpen.value = open;
|
|
1712
|
+
error.value = "";
|
|
1713
|
+
}
|
|
1714
|
+
function submit() {
|
|
1715
|
+
if (!apply(url.value)) {
|
|
1716
|
+
error.value = t("link.invalidUrl");
|
|
1717
|
+
return false;
|
|
1718
|
+
}
|
|
1719
|
+
closeToEditor();
|
|
1720
|
+
return true;
|
|
1721
|
+
}
|
|
1722
|
+
function remove() {
|
|
1723
|
+
restoreSelection();
|
|
1724
|
+
editor.dispatchCommand(TOGGLE_LINK_COMMAND, null);
|
|
1725
|
+
closeToEditor();
|
|
1726
|
+
}
|
|
1727
|
+
return {
|
|
1728
|
+
isOpen,
|
|
1729
|
+
isEditing,
|
|
1730
|
+
url,
|
|
1731
|
+
error,
|
|
1732
|
+
toggle,
|
|
1733
|
+
setOpen,
|
|
1734
|
+
submit,
|
|
1735
|
+
remove
|
|
1736
|
+
};
|
|
1737
|
+
}
|
|
1738
|
+
//#endregion
|
|
1739
|
+
//#region src/editor/useToolbarState.ts
|
|
1740
|
+
const INLINE_FORMATS = [
|
|
1741
|
+
"bold",
|
|
1742
|
+
"italic",
|
|
1743
|
+
"underline",
|
|
1744
|
+
"strikethrough",
|
|
1745
|
+
"code"
|
|
1746
|
+
];
|
|
1747
|
+
/** 光标所在的链接节点:光标在链接文字里(父节点是链接),或选区就是链接本身。 */
|
|
1748
|
+
function $linkAt(selection) {
|
|
1749
|
+
const node = selection.anchor.getNode();
|
|
1750
|
+
const parent = node.getParent();
|
|
1751
|
+
if ($isLinkNode(node)) return node;
|
|
1752
|
+
return $isLinkNode(parent) ? parent : null;
|
|
1753
|
+
}
|
|
1754
|
+
/**
|
|
1755
|
+
* 让工具栏跟着选区走:哪些格式开着、当前块是什么、能不能撤销重做、是不是可编辑、
|
|
1756
|
+
* 光标是不是在链接里。编辑器每次更新、选区每次变化都重新读一遍。
|
|
1757
|
+
*/
|
|
1758
|
+
function useToolbarState(editor) {
|
|
1759
|
+
const activeFormats = shallowRef(/* @__PURE__ */ new Set());
|
|
1760
|
+
const blockType = shallowRef("paragraph");
|
|
1761
|
+
const isLink = shallowRef(false);
|
|
1762
|
+
const canUndo = shallowRef(false);
|
|
1763
|
+
const canRedo = shallowRef(false);
|
|
1764
|
+
const isEditable = shallowRef(editor.isEditable());
|
|
1765
|
+
const savedSelection = shallowRef(null);
|
|
1766
|
+
const lastLinkContext = shallowRef({
|
|
1767
|
+
selectedText: "",
|
|
1768
|
+
url: "",
|
|
1769
|
+
isLink: false
|
|
1770
|
+
});
|
|
1771
|
+
function $sync() {
|
|
1772
|
+
const selection = $getSelection();
|
|
1773
|
+
if (!$isRangeSelection(selection) && !$isNodeSelection(selection)) return;
|
|
1774
|
+
const nodesOnly = $selectedExtensionNodesOnly(selection);
|
|
1775
|
+
const formats = /* @__PURE__ */ new Set();
|
|
1776
|
+
for (const format of INLINE_FORMATS) if (nodesOnly !== null ? nodesOnly.every((node) => node.hasFormat(format)) : $isRangeSelection(selection) && selection.hasFormat(format)) formats.add(format);
|
|
1777
|
+
activeFormats.value = formats;
|
|
1778
|
+
if (!$isRangeSelection(selection)) return;
|
|
1779
|
+
const link = $linkAt(selection);
|
|
1780
|
+
isLink.value = link !== null;
|
|
1781
|
+
savedSelection.value = selection.clone();
|
|
1782
|
+
lastLinkContext.value = {
|
|
1783
|
+
selectedText: selection.getTextContent(),
|
|
1784
|
+
url: link?.getURL() ?? "",
|
|
1785
|
+
isLink: link !== null
|
|
1786
|
+
};
|
|
1787
|
+
const anchorNode = selection.anchor.getNode();
|
|
1788
|
+
const element = anchorNode.getKey() === "root" ? anchorNode : anchorNode.getTopLevelElementOrThrow();
|
|
1789
|
+
if ($isListNode(element)) {
|
|
1790
|
+
const list = $getNearestNodeOfType(anchorNode, ListNode);
|
|
1791
|
+
blockType.value = (list ?? element).getListType() === "number" ? "number" : "bullet";
|
|
1792
|
+
} else if ($isHeadingNode(element)) blockType.value = element.getTag();
|
|
1793
|
+
else blockType.value = $isQuoteNode(element) ? "quote" : "paragraph";
|
|
1794
|
+
}
|
|
1795
|
+
const stop = mergeRegister$1(editor.registerUpdateListener(({ editorState }) => editorState.read($sync)), editor.registerCommand(SELECTION_CHANGE_COMMAND, () => {
|
|
1796
|
+
$sync();
|
|
1797
|
+
return false;
|
|
1798
|
+
}, COMMAND_PRIORITY_CRITICAL), editor.registerCommand(CAN_UNDO_COMMAND, (payload) => {
|
|
1799
|
+
canUndo.value = payload;
|
|
1800
|
+
return false;
|
|
1801
|
+
}, COMMAND_PRIORITY_CRITICAL), editor.registerCommand(CAN_REDO_COMMAND, (payload) => {
|
|
1802
|
+
canRedo.value = payload;
|
|
1803
|
+
return false;
|
|
1804
|
+
}, COMMAND_PRIORITY_CRITICAL), editor.registerEditableListener((editable) => {
|
|
1805
|
+
isEditable.value = editable;
|
|
1806
|
+
}));
|
|
1807
|
+
onBeforeUnmount(stop);
|
|
1808
|
+
function readLinkContext() {
|
|
1809
|
+
editor.getEditorState().read(() => {
|
|
1810
|
+
const selection = $getSelection();
|
|
1811
|
+
if (!$isRangeSelection(selection)) return;
|
|
1812
|
+
const link = $linkAt(selection);
|
|
1813
|
+
savedSelection.value = selection.clone();
|
|
1814
|
+
lastLinkContext.value = {
|
|
1815
|
+
selectedText: selection.getTextContent(),
|
|
1816
|
+
url: link?.getURL() ?? "",
|
|
1817
|
+
isLink: link !== null
|
|
1818
|
+
};
|
|
1819
|
+
});
|
|
1820
|
+
return lastLinkContext.value;
|
|
1821
|
+
}
|
|
1822
|
+
return {
|
|
1823
|
+
activeFormats,
|
|
1824
|
+
blockType,
|
|
1825
|
+
isLink,
|
|
1826
|
+
canUndo,
|
|
1827
|
+
canRedo,
|
|
1828
|
+
isEditable,
|
|
1829
|
+
savedSelection,
|
|
1830
|
+
lastLinkContext,
|
|
1831
|
+
readLinkContext
|
|
1832
|
+
};
|
|
1833
|
+
}
|
|
1834
|
+
//#endregion
|
|
1835
|
+
//#region src/editor/RichTextEditorToolbar.vue
|
|
1836
|
+
const _hoisted_1 = { class: "astryx-richtext-toolbar__fixed" };
|
|
1837
|
+
const _sfc_main$1 = /*@__PURE__*/ defineComponent({
|
|
1838
|
+
name: "AstryxRichTextEditorToolbar",
|
|
1839
|
+
__name: "RichTextEditorToolbar",
|
|
1840
|
+
props: {
|
|
1841
|
+
label: {},
|
|
1842
|
+
headingLevels: { default: () => [
|
|
1843
|
+
"h1",
|
|
1844
|
+
"h2",
|
|
1845
|
+
"h3"
|
|
1846
|
+
] },
|
|
1847
|
+
size: { default: "sm" },
|
|
1848
|
+
hasLink: {
|
|
1849
|
+
type: Boolean,
|
|
1850
|
+
default: true
|
|
1851
|
+
},
|
|
1852
|
+
promptForUrl: {},
|
|
1853
|
+
hasNewTabLinks: {
|
|
1854
|
+
type: Boolean,
|
|
1855
|
+
default: true
|
|
1856
|
+
}
|
|
1857
|
+
},
|
|
1858
|
+
setup(__props) {
|
|
1859
|
+
const props = __props;
|
|
1860
|
+
const editor = useLexicalEditor();
|
|
1861
|
+
const t = useRichTextMessages();
|
|
1862
|
+
const state = useToolbarState(editor);
|
|
1863
|
+
const label = computed(() => props.label ?? t("toolbar.label"));
|
|
1864
|
+
const headingLabels = computed(() => ({
|
|
1865
|
+
h1: t("toolbar.heading1"),
|
|
1866
|
+
h2: t("toolbar.heading2"),
|
|
1867
|
+
h3: t("toolbar.heading3")
|
|
1868
|
+
}));
|
|
1869
|
+
const inlineLabels = computed(() => ({
|
|
1870
|
+
bold: t("toolbar.bold"),
|
|
1871
|
+
italic: t("toolbar.italic"),
|
|
1872
|
+
underline: t("toolbar.underline"),
|
|
1873
|
+
strikethrough: t("toolbar.strikethrough"),
|
|
1874
|
+
code: t("toolbar.inlineCode")
|
|
1875
|
+
}));
|
|
1876
|
+
const link = useLinkDialog({
|
|
1877
|
+
editor,
|
|
1878
|
+
state,
|
|
1879
|
+
t,
|
|
1880
|
+
hasNewTabLinks: () => props.hasNewTabLinks,
|
|
1881
|
+
promptForUrl: () => props.promptForUrl
|
|
1882
|
+
});
|
|
1883
|
+
const PRIMARY_MODIFIER = {
|
|
1884
|
+
ctrlKey: !IS_APPLE,
|
|
1885
|
+
metaKey: IS_APPLE
|
|
1886
|
+
};
|
|
1887
|
+
let stopLinkShortcut;
|
|
1888
|
+
watchEffect(() => {
|
|
1889
|
+
stopLinkShortcut?.();
|
|
1890
|
+
stopLinkShortcut = props.hasLink ? editor.registerCommand(KEY_DOWN_COMMAND, (event) => {
|
|
1891
|
+
if (!isExactShortcutMatch(event, "k", PRIMARY_MODIFIER)) return false;
|
|
1892
|
+
event.preventDefault();
|
|
1893
|
+
link.toggle();
|
|
1894
|
+
return true;
|
|
1895
|
+
}, COMMAND_PRIORITY_NORMAL) : void 0;
|
|
1896
|
+
});
|
|
1897
|
+
onBeforeUnmount(() => stopLinkShortcut?.());
|
|
1898
|
+
function toggleInline(format) {
|
|
1899
|
+
editor.dispatchCommand(FORMAT_TEXT_COMMAND, format);
|
|
1900
|
+
}
|
|
1901
|
+
function setBlock(next) {
|
|
1902
|
+
if (!state.isEditable.value || state.blockType.value === next) return;
|
|
1903
|
+
if (next === "bullet") {
|
|
1904
|
+
editor.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND, void 0);
|
|
1905
|
+
return;
|
|
1906
|
+
}
|
|
1907
|
+
if (next === "number") {
|
|
1908
|
+
editor.dispatchCommand(INSERT_ORDERED_LIST_COMMAND, void 0);
|
|
1909
|
+
return;
|
|
1910
|
+
}
|
|
1911
|
+
editor.update(() => {
|
|
1912
|
+
const selection = $getSelection();
|
|
1913
|
+
if (!$isRangeSelection(selection)) return;
|
|
1914
|
+
$setBlocksType(selection, () => {
|
|
1915
|
+
if (next === "quote") return $createQuoteNode();
|
|
1916
|
+
if (next === "h1" || next === "h2" || next === "h3") return $createHeadingNode(next);
|
|
1917
|
+
return $createParagraphNode();
|
|
1918
|
+
});
|
|
1919
|
+
});
|
|
1920
|
+
}
|
|
1921
|
+
/** 下拉里每一项前面的图标,也是触发器上显示的图标。 */
|
|
1922
|
+
function iconFor(name) {
|
|
1923
|
+
return () => h(_sfc_main$3, { name });
|
|
1924
|
+
}
|
|
1925
|
+
const blockOptions = computed(() => [
|
|
1926
|
+
{
|
|
1927
|
+
value: "paragraph",
|
|
1928
|
+
label: t("toolbar.paragraph"),
|
|
1929
|
+
icon: iconFor("paragraph")
|
|
1930
|
+
},
|
|
1931
|
+
...props.headingLevels.map((level) => ({
|
|
1932
|
+
value: level,
|
|
1933
|
+
label: headingLabels.value[level],
|
|
1934
|
+
icon: iconFor(level)
|
|
1935
|
+
})),
|
|
1936
|
+
{
|
|
1937
|
+
value: "bullet",
|
|
1938
|
+
label: t("toolbar.bulletedList"),
|
|
1939
|
+
icon: iconFor("bullet")
|
|
1940
|
+
},
|
|
1941
|
+
{
|
|
1942
|
+
value: "number",
|
|
1943
|
+
label: t("toolbar.numberedList"),
|
|
1944
|
+
icon: iconFor("number")
|
|
1945
|
+
},
|
|
1946
|
+
{
|
|
1947
|
+
value: "quote",
|
|
1948
|
+
label: t("toolbar.blockQuote"),
|
|
1949
|
+
icon: iconFor("quote")
|
|
1950
|
+
}
|
|
1951
|
+
]);
|
|
1952
|
+
return (_ctx, _cache) => {
|
|
1953
|
+
return openBlock(), createElementBlock(Fragment, null, [createVNode(unref(Toolbar), {
|
|
1954
|
+
label: label.value,
|
|
1955
|
+
size: __props.size,
|
|
1956
|
+
class: "astryx-richtext-toolbar"
|
|
1957
|
+
}, {
|
|
1958
|
+
start: withCtx(() => [createVNode(unref(HStack), {
|
|
1959
|
+
gap: 1,
|
|
1960
|
+
align: "center",
|
|
1961
|
+
role: "group",
|
|
1962
|
+
"aria-label": unref(t)("toolbar.actions"),
|
|
1963
|
+
class: "astryx-richtext-toolbar__actions"
|
|
1964
|
+
}, {
|
|
1965
|
+
default: withCtx(() => [
|
|
1966
|
+
createVNode(unref(IconButton), {
|
|
1967
|
+
label: unref(t)("toolbar.undo"),
|
|
1968
|
+
variant: "ghost",
|
|
1969
|
+
tooltip: unref(t)("toolbar.undo"),
|
|
1970
|
+
"is-disabled": !unref(state).isEditable.value || !unref(state).canUndo.value,
|
|
1971
|
+
onClick: _cache[0] || (_cache[0] = ($event) => unref(editor).dispatchCommand(unref(UNDO_COMMAND), void 0))
|
|
1972
|
+
}, {
|
|
1973
|
+
default: withCtx(() => [createVNode(_sfc_main$3, {
|
|
1974
|
+
name: "undo",
|
|
1975
|
+
"is-directional": ""
|
|
1976
|
+
})]),
|
|
1977
|
+
_: 1
|
|
1978
|
+
}, 8, [
|
|
1979
|
+
"label",
|
|
1980
|
+
"tooltip",
|
|
1981
|
+
"is-disabled"
|
|
1982
|
+
]),
|
|
1983
|
+
createVNode(unref(IconButton), {
|
|
1984
|
+
label: unref(t)("toolbar.redo"),
|
|
1985
|
+
variant: "ghost",
|
|
1986
|
+
tooltip: unref(t)("toolbar.redo"),
|
|
1987
|
+
"is-disabled": !unref(state).isEditable.value || !unref(state).canRedo.value,
|
|
1988
|
+
onClick: _cache[1] || (_cache[1] = ($event) => unref(editor).dispatchCommand(unref(REDO_COMMAND), void 0))
|
|
1989
|
+
}, {
|
|
1990
|
+
default: withCtx(() => [createVNode(_sfc_main$3, {
|
|
1991
|
+
name: "redo",
|
|
1992
|
+
"is-directional": ""
|
|
1993
|
+
})]),
|
|
1994
|
+
_: 1
|
|
1995
|
+
}, 8, [
|
|
1996
|
+
"label",
|
|
1997
|
+
"tooltip",
|
|
1998
|
+
"is-disabled"
|
|
1999
|
+
]),
|
|
2000
|
+
createVNode(unref(Divider), {
|
|
2001
|
+
orientation: "vertical",
|
|
2002
|
+
"aria-label": unref(t)("toolbar.historyDivider"),
|
|
2003
|
+
class: "astryx-richtext-toolbar__divider"
|
|
2004
|
+
}, null, 8, ["aria-label"]),
|
|
2005
|
+
createElementVNode("div", _hoisted_1, [createVNode(unref(Selector), {
|
|
2006
|
+
label: unref(t)("toolbar.blockFormat"),
|
|
2007
|
+
"is-label-hidden": "",
|
|
2008
|
+
variant: "ghost",
|
|
2009
|
+
size: __props.size,
|
|
2010
|
+
"model-value": unref(state).blockType.value,
|
|
2011
|
+
options: blockOptions.value,
|
|
2012
|
+
disabled: !unref(state).isEditable.value,
|
|
2013
|
+
"onUpdate:modelValue": _cache[2] || (_cache[2] = ($event) => setBlock($event))
|
|
2014
|
+
}, null, 8, [
|
|
2015
|
+
"label",
|
|
2016
|
+
"size",
|
|
2017
|
+
"model-value",
|
|
2018
|
+
"options",
|
|
2019
|
+
"disabled"
|
|
2020
|
+
])]),
|
|
2021
|
+
createVNode(unref(Divider), {
|
|
2022
|
+
orientation: "vertical",
|
|
2023
|
+
"aria-label": unref(t)("toolbar.formatDivider"),
|
|
2024
|
+
class: "astryx-richtext-toolbar__divider"
|
|
2025
|
+
}, null, 8, ["aria-label"]),
|
|
2026
|
+
(openBlock(true), createElementBlock(Fragment, null, renderList(unref(INLINE_FORMATS), (format) => {
|
|
2027
|
+
return openBlock(), createBlock(unref(ToggleButton), {
|
|
2028
|
+
key: format,
|
|
2029
|
+
label: inlineLabels.value[format],
|
|
2030
|
+
size: __props.size,
|
|
2031
|
+
"is-icon-only": "",
|
|
2032
|
+
tooltip: inlineLabels.value[format],
|
|
2033
|
+
"is-pressed": unref(state).activeFormats.value.has(format),
|
|
2034
|
+
"is-disabled": !unref(state).isEditable.value,
|
|
2035
|
+
onMousedown: _cache[3] || (_cache[3] = withModifiers(() => {}, ["prevent"])),
|
|
2036
|
+
onPressedChange: ($event) => toggleInline(format)
|
|
2037
|
+
}, {
|
|
2038
|
+
icon: withCtx(() => [createVNode(_sfc_main$3, { name: format }, null, 8, ["name"])]),
|
|
2039
|
+
_: 2
|
|
2040
|
+
}, 1032, [
|
|
2041
|
+
"label",
|
|
2042
|
+
"size",
|
|
2043
|
+
"tooltip",
|
|
2044
|
+
"is-pressed",
|
|
2045
|
+
"is-disabled",
|
|
2046
|
+
"onPressedChange"
|
|
2047
|
+
]);
|
|
2048
|
+
}), 128)),
|
|
2049
|
+
__props.hasLink ? (openBlock(), createBlock(unref(ToggleButton), {
|
|
2050
|
+
key: 0,
|
|
2051
|
+
label: unref(t)("toolbar.link"),
|
|
2052
|
+
size: __props.size,
|
|
2053
|
+
"is-icon-only": "",
|
|
2054
|
+
tooltip: unref(t)("toolbar.link"),
|
|
2055
|
+
"is-pressed": unref(state).isLink.value || unref(link).isOpen.value,
|
|
2056
|
+
"is-disabled": !unref(state).isEditable.value,
|
|
2057
|
+
"aria-haspopup": "dialog",
|
|
2058
|
+
"aria-expanded": unref(link).isOpen.value,
|
|
2059
|
+
onMousedown: _cache[4] || (_cache[4] = withModifiers(() => {}, ["prevent"])),
|
|
2060
|
+
onPressedChange: _cache[5] || (_cache[5] = ($event) => unref(link).toggle())
|
|
2061
|
+
}, {
|
|
2062
|
+
icon: withCtx(() => [createVNode(_sfc_main$3, { name: "link" })]),
|
|
2063
|
+
_: 1
|
|
2064
|
+
}, 8, [
|
|
2065
|
+
"label",
|
|
2066
|
+
"size",
|
|
2067
|
+
"tooltip",
|
|
2068
|
+
"is-pressed",
|
|
2069
|
+
"is-disabled",
|
|
2070
|
+
"aria-expanded"
|
|
2071
|
+
])) : createCommentVNode("v-if", true),
|
|
2072
|
+
_ctx.$slots.end ? (openBlock(), createElementBlock(Fragment, { key: 1 }, [createVNode(unref(Divider), {
|
|
2073
|
+
orientation: "vertical",
|
|
2074
|
+
class: "astryx-richtext-toolbar__divider"
|
|
2075
|
+
}), renderSlot(_ctx.$slots, "end")], 64)) : createCommentVNode("v-if", true)
|
|
2076
|
+
]),
|
|
2077
|
+
_: 3
|
|
2078
|
+
}, 8, ["aria-label"])]),
|
|
2079
|
+
_: 3
|
|
2080
|
+
}, 8, ["label", "size"]), __props.hasLink ? (openBlock(), createBlock(unref(Dialog), {
|
|
2081
|
+
key: 0,
|
|
2082
|
+
"is-open": unref(link).isOpen.value,
|
|
2083
|
+
purpose: "form",
|
|
2084
|
+
width: 400,
|
|
2085
|
+
onOpenChange: unref(link).setOpen
|
|
2086
|
+
}, {
|
|
2087
|
+
default: withCtx(() => [createCommentVNode("\n 表单只在打开时渲染:`TextInput` 的「挂载时聚焦」只在挂载那一刻生效,\n 内容一直留在页面里的话,第二次打开就不会再聚焦到网址输入框。\n "), unref(link).isOpen.value ? (openBlock(), createElementBlock("form", {
|
|
2088
|
+
key: 0,
|
|
2089
|
+
onSubmit: _cache[10] || (_cache[10] = withModifiers(($event) => unref(link).submit(), ["prevent"]))
|
|
2090
|
+
}, [createVNode(unref(Layout), { height: "auto" }, {
|
|
2091
|
+
header: withCtx(() => [createVNode(unref(DialogHeader), {
|
|
2092
|
+
title: unref(link).isEditing.value ? unref(t)("link.editTitle") : unref(t)("link.insertTitle"),
|
|
2093
|
+
onOpenChange: unref(link).setOpen
|
|
2094
|
+
}, null, 8, ["title", "onOpenChange"])]),
|
|
2095
|
+
footer: withCtx(() => [createVNode(unref(LayoutFooter), null, {
|
|
2096
|
+
default: withCtx(() => [createVNode(unref(HStack), {
|
|
2097
|
+
gap: 2,
|
|
2098
|
+
"h-align": "end"
|
|
2099
|
+
}, {
|
|
2100
|
+
default: withCtx(() => [
|
|
2101
|
+
unref(link).isEditing.value ? (openBlock(), createBlock(unref(Button), {
|
|
2102
|
+
key: 0,
|
|
2103
|
+
label: unref(t)("link.remove"),
|
|
2104
|
+
variant: "destructive",
|
|
2105
|
+
onClick: _cache[8] || (_cache[8] = ($event) => unref(link).remove())
|
|
2106
|
+
}, null, 8, ["label"])) : createCommentVNode("v-if", true),
|
|
2107
|
+
createVNode(unref(Button), {
|
|
2108
|
+
label: unref(t)("link.cancel"),
|
|
2109
|
+
variant: "secondary",
|
|
2110
|
+
onClick: _cache[9] || (_cache[9] = ($event) => unref(link).setOpen(false))
|
|
2111
|
+
}, null, 8, ["label"]),
|
|
2112
|
+
createVNode(unref(Button), {
|
|
2113
|
+
label: unref(link).isEditing.value ? unref(t)("link.update") : unref(t)("link.add"),
|
|
2114
|
+
variant: "primary",
|
|
2115
|
+
type: "submit"
|
|
2116
|
+
}, null, 8, ["label"])
|
|
2117
|
+
]),
|
|
2118
|
+
_: 1
|
|
2119
|
+
})]),
|
|
2120
|
+
_: 1
|
|
2121
|
+
})]),
|
|
2122
|
+
default: withCtx(() => [createVNode(unref(LayoutContent), null, {
|
|
2123
|
+
default: withCtx(() => [createVNode(unref(TextInput), {
|
|
2124
|
+
modelValue: unref(link).url.value,
|
|
2125
|
+
"onUpdate:modelValue": _cache[6] || (_cache[6] = ($event) => unref(link).url.value = $event),
|
|
2126
|
+
label: unref(t)("link.url"),
|
|
2127
|
+
width: "100%",
|
|
2128
|
+
"has-auto-focus": "",
|
|
2129
|
+
"status-variant": "detached",
|
|
2130
|
+
status: unref(link).error.value ? {
|
|
2131
|
+
type: "error",
|
|
2132
|
+
message: unref(link).error.value
|
|
2133
|
+
} : void 0,
|
|
2134
|
+
onChange: _cache[7] || (_cache[7] = ($event) => unref(link).error.value = "")
|
|
2135
|
+
}, null, 8, [
|
|
2136
|
+
"modelValue",
|
|
2137
|
+
"label",
|
|
2138
|
+
"status"
|
|
2139
|
+
])]),
|
|
2140
|
+
_: 1
|
|
2141
|
+
})]),
|
|
2142
|
+
_: 1
|
|
2143
|
+
})], 32)) : createCommentVNode("v-if", true)]),
|
|
2144
|
+
_: 1
|
|
2145
|
+
}, 8, ["is-open", "onOpenChange"])) : createCommentVNode("v-if", true)], 64);
|
|
2146
|
+
};
|
|
2147
|
+
}
|
|
2148
|
+
});
|
|
2149
|
+
//#endregion
|
|
2150
|
+
//#region src/editor/RichTextView.vue
|
|
2151
|
+
const _sfc_main$2 = /*@__PURE__*/ defineComponent({
|
|
2152
|
+
name: "AstryxRichTextView",
|
|
2153
|
+
inheritAttrs: false,
|
|
2154
|
+
__name: "RichTextView",
|
|
2155
|
+
props: {
|
|
2156
|
+
value: {},
|
|
2157
|
+
nodes: {},
|
|
2158
|
+
markdownExtensions: {},
|
|
2159
|
+
namespace: { default: "astryx-view" }
|
|
2160
|
+
},
|
|
2161
|
+
emits: ["parseError"],
|
|
2162
|
+
setup(__props, { emit: __emit }) {
|
|
2163
|
+
const props = __props;
|
|
2164
|
+
const emit = __emit;
|
|
2165
|
+
const attrs = useAttrs();
|
|
2166
|
+
const coreMessages = useAstryxMessages();
|
|
2167
|
+
const surface = shallowRef(null);
|
|
2168
|
+
const hasError = shallowRef(false);
|
|
2169
|
+
/** 状态必须是合法的 JSON;坏的 JSON 会在建编辑器时直接抛出,所以先验一遍。 */
|
|
2170
|
+
function parseProblem(value) {
|
|
2171
|
+
try {
|
|
2172
|
+
JSON.parse(value);
|
|
2173
|
+
return null;
|
|
2174
|
+
} catch (error) {
|
|
2175
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
2176
|
+
}
|
|
2177
|
+
}
|
|
2178
|
+
/**
|
|
2179
|
+
* 读的是持久化的内容:坏的 JSON、或者用了没注册的节点类型都可能出现,不能把整个页面带崩。
|
|
2180
|
+
* 建不出来就返回 null 并报告,由模板显示 `errorFallback`。
|
|
2181
|
+
*/
|
|
2182
|
+
function create(value) {
|
|
2183
|
+
const problem = parseProblem(value);
|
|
2184
|
+
if (problem !== null) {
|
|
2185
|
+
hasError.value = true;
|
|
2186
|
+
emit("parseError", problem);
|
|
2187
|
+
return null;
|
|
2188
|
+
}
|
|
2189
|
+
try {
|
|
2190
|
+
const instance = createRichTextEditor({
|
|
2191
|
+
namespace: props.namespace,
|
|
2192
|
+
initialState: value,
|
|
2193
|
+
editable: false,
|
|
2194
|
+
nodes: props.nodes,
|
|
2195
|
+
hasMarkdownShortcuts: false
|
|
2196
|
+
});
|
|
2197
|
+
hasError.value = false;
|
|
2198
|
+
return instance;
|
|
2199
|
+
} catch (error) {
|
|
2200
|
+
hasError.value = true;
|
|
2201
|
+
emit("parseError", error instanceof Error ? error : new Error(String(error)));
|
|
2202
|
+
return null;
|
|
2203
|
+
}
|
|
2204
|
+
}
|
|
2205
|
+
const editor = shallowRef(create(props.value));
|
|
2206
|
+
/** 已经挂到元素上的编辑器。插件要等它有了才装:不然它们第一次画的时候根元素还不存在。 */
|
|
2207
|
+
const attached = shallowRef(null);
|
|
2208
|
+
let stopTables;
|
|
2209
|
+
function dispose() {
|
|
2210
|
+
stopTables?.();
|
|
2211
|
+
stopTables = void 0;
|
|
2212
|
+
const instance = editor.value;
|
|
2213
|
+
instance?.setRootElement(null);
|
|
2214
|
+
instance?.dispose();
|
|
2215
|
+
}
|
|
2216
|
+
/** 把编辑器挂到元素上,并去掉 Lexical 写的 `role="textbox"` 和只对控件有效的 ARIA(原因见模板里的说明)。 */
|
|
2217
|
+
function attach() {
|
|
2218
|
+
const root = surface.value;
|
|
2219
|
+
const instance = editor.value;
|
|
2220
|
+
if (instance === null || root === null) return;
|
|
2221
|
+
instance.setRootElement(root);
|
|
2222
|
+
root.contentEditable = "false";
|
|
2223
|
+
root.removeAttribute("role");
|
|
2224
|
+
root.removeAttribute("aria-autocomplete");
|
|
2225
|
+
root.removeAttribute("aria-readonly");
|
|
2226
|
+
root.removeAttribute("aria-multiline");
|
|
2227
|
+
stopTables = registerTableScrollRegion(instance, () => coreMessages.value.table.label);
|
|
2228
|
+
attached.value = instance;
|
|
2229
|
+
}
|
|
2230
|
+
onMounted(attach);
|
|
2231
|
+
onBeforeUnmount(dispose);
|
|
2232
|
+
watch(() => props.value, (next) => {
|
|
2233
|
+
const problem = parseProblem(next);
|
|
2234
|
+
if (problem !== null) {
|
|
2235
|
+
attached.value = null;
|
|
2236
|
+
dispose();
|
|
2237
|
+
editor.value = null;
|
|
2238
|
+
hasError.value = true;
|
|
2239
|
+
emit("parseError", problem);
|
|
2240
|
+
return;
|
|
2241
|
+
}
|
|
2242
|
+
const instance = editor.value;
|
|
2243
|
+
if (hasError.value || instance === null) {
|
|
2244
|
+
editor.value = create(next);
|
|
2245
|
+
nextTick(attach);
|
|
2246
|
+
return;
|
|
2247
|
+
}
|
|
2248
|
+
instance.setEditorState(instance.parseEditorState(next));
|
|
2249
|
+
});
|
|
2250
|
+
provide(editorKey, () => attached.value ?? editor.value);
|
|
2251
|
+
const rootAttrs = computed(() => ({
|
|
2252
|
+
class: attrs.class,
|
|
2253
|
+
style: attrs.style
|
|
2254
|
+
}));
|
|
2255
|
+
const restAttrs = computed(() => {
|
|
2256
|
+
const { class: _class, style: _style, ...rest } = attrs;
|
|
2257
|
+
return rest;
|
|
2258
|
+
});
|
|
2259
|
+
return (_ctx, _cache) => {
|
|
2260
|
+
return openBlock(), createElementBlock("div", mergeProps({ class: "astryx-richtext-view" }, {
|
|
2261
|
+
...restAttrs.value,
|
|
2262
|
+
...rootAttrs.value
|
|
2263
|
+
}), [hasError.value ? renderSlot(_ctx.$slots, "errorFallback", {}, void 0, void 0, 0) : (openBlock(), createElementBlock(Fragment, { key: 1 }, [
|
|
2264
|
+
createCommentVNode("\n 这是文档内容,不是表单控件:Lexical 默认给可编辑区写 `role=\"textbox\"` 和只对控件有效的 ARIA,\n 不可编辑时也写。一个没有名字的 textbox 过不了 axe 的 `aria-input-field-name`,\n 视图本来就是内容而不是带标签的输入框,没有名字可给;而且把渲染出来的文档当成表单控件,\n 读屏软件就读不出它其实是内容。所以都去掉。想要「带标签的只读字段」用 `<RichTextEditor is-read-only>`。\n "),
|
|
2265
|
+
createElementVNode("div", {
|
|
2266
|
+
ref_key: "surface",
|
|
2267
|
+
ref: surface,
|
|
2268
|
+
class: "astryx-richtext-view__content"
|
|
2269
|
+
}, null, 512),
|
|
2270
|
+
attached.value ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [
|
|
2271
|
+
createVNode(unref(DecoratorTeleports), { editor: attached.value }, null, 8, ["editor"]),
|
|
2272
|
+
createCommentVNode(" 放在内容后面,复制按钮和勾选框在 Tab 顺序里才跟在内容后面。 "),
|
|
2273
|
+
createVNode(unref(CodeBlockHeaderPlugin)),
|
|
2274
|
+
createVNode(unref(CodeSyntaxPlugin)),
|
|
2275
|
+
__props.markdownExtensions && __props.markdownExtensions.length > 0 ? (openBlock(), createBlock(unref(MarkdownExtensionsPlugin), {
|
|
2276
|
+
key: 0,
|
|
2277
|
+
extensions: __props.markdownExtensions,
|
|
2278
|
+
transformers: []
|
|
2279
|
+
}, null, 8, ["extensions"])) : createCommentVNode("v-if", true),
|
|
2280
|
+
createVNode(unref(TaskCheckboxPlugin), { "is-read-only": "" }),
|
|
2281
|
+
renderSlot(_ctx.$slots, "default")
|
|
2282
|
+
], 64)) : createCommentVNode("v-if", true)
|
|
2283
|
+
], 64))], 16);
|
|
2284
|
+
};
|
|
2285
|
+
}
|
|
2286
|
+
});
|
|
2287
|
+
//#endregion
|
|
2288
|
+
export { DEFAULT_LINK_MATCHERS, NEW_TAB_LINK_ATTRIBUTES, RICHTEXT_ICON_KEYS, _sfc_main as RichTextEditor, RichTextEditorAutoLinkPlugin, _sfc_main$1 as RichTextEditorToolbar, RichTextExtensionError, _sfc_main$2 as RichTextView, createRichTextEditor, createRichTextExtension, editorKey, editorStateJSONToMarkdown, markdownToEditorStateJSON, sanitizeUrl, useLexicalEditor, validateUrl };
|