@ecomcx/ecomweb-editor 1.18.0 → 1.20.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/package.json +25 -7
- package/src/index.ts +26 -25
- package/src/{ask.tsx → legacy/ask.tsx} +2 -2
- package/src/{blockMeta.ts → legacy/block-meta.ts} +1 -1
- package/src/{blocks.tsx → legacy/blocks.tsx} +8 -32
- package/src/{content.ts → legacy/content.ts} +1 -1
- package/src/{handle.tsx → legacy/drag-handle.tsx} +3 -3
- package/src/{dynamic.tsx → legacy/dynamic.tsx} +7 -3
- package/src/{Editor.tsx → legacy/editor.tsx} +9 -9
- package/src/{extensions.ts → legacy/extensions.ts} +1 -1
- package/src/legacy/insert-pattern.ts +13 -0
- package/src/{inserter.tsx → legacy/inserter.tsx} +6 -5
- package/src/{inspector.tsx → legacy/inspector.tsx} +7 -7
- package/src/{layoutUi.tsx → legacy/layout-ui.tsx} +6 -5
- package/src/{layout.tsx → legacy/layout.tsx} +2 -2
- package/src/{media.ts → legacy/media.ts} +1 -1
- package/src/{nodes.tsx → legacy/nodes.tsx} +2 -2
- package/src/{outline.tsx → legacy/outline.tsx} +4 -4
- package/src/legacy/panels.ts +22 -0
- package/src/{rank.ts → legacy/rank.ts} +2 -2
- package/src/{registry.ts → legacy/registry.ts} +1 -1
- package/src/{handles.tsx → legacy/resize-handles.tsx} +1 -1
- package/src/{styleattr.ts → legacy/style-attr.ts} +15 -1
- package/src/{synced.tsx → legacy/synced.tsx} +2 -2
- package/src/{toolbar.tsx → legacy/toolbar.tsx} +7 -7
- package/src/{unknown.tsx → legacy/unknown.tsx} +1 -1
- package/src/shared/block-defs.ts +38 -0
- package/src/shared/color-swatch.tsx +19 -0
- package/src/{panels.ts → shared/panel-store.ts} +4 -21
- package/src/{patterns.ts → shared/patterns.ts} +0 -12
- package/src/{stylepanel.tsx → shared/style-panel.tsx} +2 -2
- package/src/{types.ts → shared/types.ts} +2 -0
- package/src/v2/blocks/compat.tsx +51 -0
- package/src/v2/blocks/index.ts +42 -0
- package/src/v2/blocks/layout.tsx +281 -0
- package/src/v2/blocks/media-actions.tsx +76 -0
- package/src/v2/blocks/media.tsx +234 -0
- package/src/v2/blocks/resize.tsx +111 -0
- package/src/v2/blocks/text.tsx +150 -0
- package/src/v2/blocks/theme.tsx +293 -0
- package/src/v2/blocks/tools.tsx +72 -0
- package/src/v2/canvas/block-list.tsx +216 -0
- package/src/v2/canvas/canvas-css.ts +131 -0
- package/src/v2/canvas/canvas.tsx +379 -0
- package/src/v2/canvas/dnd.ts +192 -0
- package/src/v2/context.tsx +146 -0
- package/src/v2/core/bindings.ts +64 -0
- package/src/v2/core/clipboard.ts +238 -0
- package/src/v2/core/host.ts +80 -0
- package/src/v2/core/model.ts +157 -0
- package/src/v2/core/ops.ts +151 -0
- package/src/v2/core/patterns.ts +10 -0
- package/src/v2/core/registry.ts +135 -0
- package/src/v2/core/store.ts +804 -0
- package/src/v2/core/structure.ts +106 -0
- package/src/v2/core/tables.ts +194 -0
- package/src/v2/editor.css +324 -0
- package/src/v2/editor.tsx +288 -0
- package/src/v2/index.ts +28 -0
- package/src/v2/labels.ts +349 -0
- package/src/v2/prefs.ts +69 -0
- package/src/v2/text/paste.ts +75 -0
- package/src/v2/text/rich-schema.ts +96 -0
- package/src/v2/text/rich-text.tsx +512 -0
- package/src/v2/ui/attr-form.tsx +182 -0
- package/src/v2/ui/attr-hints.ts +129 -0
- package/src/v2/ui/bindings.tsx +91 -0
- package/src/v2/ui/block-descriptions.ts +34 -0
- package/src/v2/ui/color-field.tsx +17 -0
- package/src/v2/ui/doc-title.tsx +45 -0
- package/src/v2/ui/inserter.tsx +300 -0
- package/src/v2/ui/inspector.tsx +85 -0
- package/src/v2/ui/layout-panel.tsx +159 -0
- package/src/v2/ui/list-view.tsx +65 -0
- package/src/v2/ui/options.tsx +242 -0
- package/src/v2/ui/style-controls.tsx +57 -0
- package/src/v2/ui/style-tab.tsx +158 -0
- package/src/v2/ui/toolbar.tsx +402 -0
- package/src/v2/ui/unit-controls.tsx +99 -0
- /package/src/{basic.tsx → legacy/basic.tsx} +0 -0
- /package/src/{blockops.ts → legacy/block-ops.ts} +0 -0
- /package/src/{boundary.tsx → legacy/boundary.tsx} +0 -0
- /package/src/{editor.css → legacy/editor.css} +0 -0
- /package/src/{insert.ts → legacy/insert.ts} +0 -0
- /package/src/{labels.ts → shared/labels.ts} +0 -0
- /package/src/{paste.ts → shared/paste.ts} +0 -0
- /package/src/{util.ts → shared/util.ts} +0 -0
|
@@ -0,0 +1,512 @@
|
|
|
1
|
+
import type { RichNode } from "@ecomcx/ecomweb-content";
|
|
2
|
+
import { toggleMark } from "prosemirror-commands";
|
|
3
|
+
import { keymap } from "prosemirror-keymap";
|
|
4
|
+
import { EditorState, Plugin, TextSelection } from "prosemirror-state";
|
|
5
|
+
import { EditorView } from "prosemirror-view";
|
|
6
|
+
import { createElement, useLayoutEffect, useRef, type CSSProperties, type Ref } from "react";
|
|
7
|
+
import { flushSync } from "react-dom";
|
|
8
|
+
import { useEditor, useEditorState, type EditorUi } from "../context";
|
|
9
|
+
import { inlineLength, makeBlock, type BNode } from "../core/model";
|
|
10
|
+
import { charToPos, docToInline, inlineToDoc, sameInline, type SchemaKind } from "./rich-schema";
|
|
11
|
+
import type { BlockProps } from "../core/registry";
|
|
12
|
+
import type { EditorStore } from "../core/store";
|
|
13
|
+
import { pasteIntoBlock } from "./paste";
|
|
14
|
+
import { flatten } from "../core/ops";
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Ô gõ chữ: ProseMirror gắn thẳng vào phần tử của khối (<p>, <h2>…) — không thêm thẻ bọc, nên CSS của theme áp đúng.
|
|
18
|
+
* - Chế độ khối chữ (mặc định): chữ là `block.inline`; Enter tách khối, Backspace đầu khối nối khối trước…
|
|
19
|
+
* - Chế độ thuộc tính (`onChange`): sửa một thuộc tính chữ (chữ trên nút, chú thích) — một dòng, không tách khối.
|
|
20
|
+
*/
|
|
21
|
+
export interface RichTextProps {
|
|
22
|
+
blockId: string;
|
|
23
|
+
value: RichNode[] | string | undefined;
|
|
24
|
+
tagName?: string;
|
|
25
|
+
className?: string;
|
|
26
|
+
style?: CSSProperties;
|
|
27
|
+
placeholder?: string;
|
|
28
|
+
/** Hiện chữ gợi ý cả khi không đang gõ (tiêu đề, chú thích). Mặc định chỉ khi đang gõ. */
|
|
29
|
+
placeholderAlways?: boolean;
|
|
30
|
+
/** Enter xuống dòng trong khối (mã nguồn). */
|
|
31
|
+
multiline?: boolean;
|
|
32
|
+
/** Không định dạng chữ. */
|
|
33
|
+
plain?: boolean;
|
|
34
|
+
/** Enter xuống dòng (hardBreak) thay vì tách khối, vẫn giữ định dạng (văn bản định dạng sẵn). */
|
|
35
|
+
breakOnEnter?: boolean;
|
|
36
|
+
/** Sửa thuộc tính (chuỗi) thay vì chữ của khối. */
|
|
37
|
+
onChange?(value: string): void;
|
|
38
|
+
/** Gắn props của khối vào chính ô gõ (khi ô gõ là phần tử gốc của khối). */
|
|
39
|
+
blockProps?: BlockProps;
|
|
40
|
+
editable?: boolean;
|
|
41
|
+
/** Định danh phụ (một khối có nhiều ô gõ thuộc tính). */
|
|
42
|
+
field?: string;
|
|
43
|
+
"aria-label"?: string;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** ProseMirror đang mở theo khối (thanh công cụ định dạng, liên kết đọc/ghi qua đây). */
|
|
47
|
+
export const richViews = new Map<string, EditorView>();
|
|
48
|
+
const viewKey = (blockId: string, field?: string) => (field ? `${blockId}#${field}` : blockId);
|
|
49
|
+
|
|
50
|
+
/** Loại schema của ô gõ: mã nguồn (chữ thuần, giữ khoảng trắng), định dạng sẵn (giữ khoảng trắng, có định dạng), chữ thường. */
|
|
51
|
+
const schemaKind = (p: RichTextProps): SchemaKind => (p.plain || p.multiline ? "code" : p.breakOnEnter ? "pre" : "inline");
|
|
52
|
+
const toInline = (v: RichNode[] | string | undefined): RichNode[] => (typeof v === "string" ? (v ? [{ type: "text", text: v }] : []) : v ?? []);
|
|
53
|
+
const toPlainString = (inline: RichNode[]) => inline.map((n) => (n.type === "text" ? n.text ?? "" : n.type === "hardBreak" ? "\n" : "")).join("");
|
|
54
|
+
|
|
55
|
+
export function RichText(props: RichTextProps) {
|
|
56
|
+
const ctx = useEditor();
|
|
57
|
+
const { store, ui } = ctx;
|
|
58
|
+
const elRef = useRef<HTMLElement | null>(null);
|
|
59
|
+
const viewRef = useRef<EditorView | null>(null);
|
|
60
|
+
const propsRef = useRef(props);
|
|
61
|
+
propsRef.current = props;
|
|
62
|
+
const lastValue = useRef<RichNode[]>(toInline(props.value));
|
|
63
|
+
const key = viewKey(props.blockId, props.field);
|
|
64
|
+
const editable = props.editable !== false;
|
|
65
|
+
|
|
66
|
+
useLayoutEffect(() => {
|
|
67
|
+
const el = elRef.current!;
|
|
68
|
+
const state = EditorState.create({ doc: inlineToDoc(lastValue.current, schemaKind(propsRef.current)), plugins: [richKeymap(store, ui, propsRef, () => ctx.prefs.get().keepCaretInsideBlock), selectionReporter(store, ui, propsRef)] });
|
|
69
|
+
const view = new EditorView({ mount: el }, {
|
|
70
|
+
state,
|
|
71
|
+
editable: () => propsRef.current.editable !== false,
|
|
72
|
+
attributes: { role: "textbox", "aria-multiline": propsRef.current.onChange ? "false" : "true" },
|
|
73
|
+
dispatchTransaction(tr) {
|
|
74
|
+
const v = viewRef.current;
|
|
75
|
+
if (!v) return;
|
|
76
|
+
const next = v.state.apply(tr);
|
|
77
|
+
v.updateState(next);
|
|
78
|
+
syncEmpty(v);
|
|
79
|
+
if (!tr.docChanged || tr.getMeta("external")) return;
|
|
80
|
+
const inline = docToInline(next.doc);
|
|
81
|
+
lastValue.current = inline;
|
|
82
|
+
const p = propsRef.current;
|
|
83
|
+
if (p.onChange) p.onChange(toPlainString(inline));
|
|
84
|
+
else {
|
|
85
|
+
store.setInline(p.blockId, inline, { id: p.blockId, offset: next.selection.from, to: next.selection.to });
|
|
86
|
+
detectSlash(v, store, ui, p);
|
|
87
|
+
}
|
|
88
|
+
},
|
|
89
|
+
handleTextInput: (v, from, to, text) => inputRule(v, store, propsRef.current, from, to, text),
|
|
90
|
+
handleKeyDown: (_v, e) => {
|
|
91
|
+
if (!e.metaKey && !e.ctrlKey && !e.altKey && (e.key.length === 1 || e.key === "Backspace" || e.key === "Enter")) ui.setTyping(true);
|
|
92
|
+
return false;
|
|
93
|
+
},
|
|
94
|
+
handlePaste: (v, event) => (propsRef.current.onChange ? false : pasteIntoBlock(ctx, propsRef.current.blockId, v, event)),
|
|
95
|
+
handleDOMEvents: {
|
|
96
|
+
// Kéo chuột từ ô này sang khối chữ khác → chọn chữ qua nhiều khối
|
|
97
|
+
mousedown: (v, e) => {
|
|
98
|
+
const p = propsRef.current;
|
|
99
|
+
if (e.button === 0 && !e.shiftKey && !p.onChange && !p.field) trackRangeDrag(store, v, p.blockId);
|
|
100
|
+
return false;
|
|
101
|
+
},
|
|
102
|
+
focus: () => {
|
|
103
|
+
const p = propsRef.current;
|
|
104
|
+
ui.activeRich = viewKey(p.blockId, p.field);
|
|
105
|
+
store.setEditing(p.blockId);
|
|
106
|
+
ui.bump();
|
|
107
|
+
return false;
|
|
108
|
+
},
|
|
109
|
+
},
|
|
110
|
+
});
|
|
111
|
+
viewRef.current = view;
|
|
112
|
+
richViews.set(key, view);
|
|
113
|
+
el.setAttribute("data-ecx-rich", "");
|
|
114
|
+
if (propsRef.current.field) el.setAttribute("data-ecx-field", propsRef.current.field);
|
|
115
|
+
syncEmpty(view);
|
|
116
|
+
return () => {
|
|
117
|
+
if (richViews.get(key) === view) richViews.delete(key);
|
|
118
|
+
viewRef.current = null;
|
|
119
|
+
view.destroy();
|
|
120
|
+
};
|
|
121
|
+
// Tạo lại khi đổi phần tử (h2 → h4: React thay thẻ mới); giá trị mới đồng bộ ở effect dưới
|
|
122
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
123
|
+
}, [key, props.tagName]);
|
|
124
|
+
|
|
125
|
+
// Giá trị đổi từ ngoài (hoàn tác, nối khối, cộng tác) → thay nội dung, giữ con trỏ trong giới hạn
|
|
126
|
+
useLayoutEffect(() => {
|
|
127
|
+
const view = viewRef.current;
|
|
128
|
+
if (!view) return;
|
|
129
|
+
const inline = toInline(props.value);
|
|
130
|
+
if (inline === lastValue.current || sameInline(inline, lastValue.current)) return;
|
|
131
|
+
lastValue.current = inline;
|
|
132
|
+
const doc = inlineToDoc(inline, schemaKind(props));
|
|
133
|
+
const { from, to } = view.state.selection;
|
|
134
|
+
const tr = view.state.tr.replaceWith(0, view.state.doc.content.size, doc.content).setMeta("external", true).setMeta("addToHistory", false);
|
|
135
|
+
const size = tr.doc.content.size;
|
|
136
|
+
tr.setSelection(TextSelection.create(tr.doc, Math.min(from, size), Math.min(to, size)));
|
|
137
|
+
view.dispatch(tr);
|
|
138
|
+
}, [props.value, props.plain, props.multiline, props.breakOnEnter]);
|
|
139
|
+
|
|
140
|
+
// Yêu cầu đặt con trỏ (tách/nối khối, điều hướng, hoàn tác) — đồng bộ ngay sau khi vẽ, trước khi phím kế tiếp tới
|
|
141
|
+
const caret = useEditorState((s) => (s.caret && s.caret.id === props.blockId && !props.field ? s.caret : null));
|
|
142
|
+
useLayoutEffect(() => {
|
|
143
|
+
const view = viewRef.current;
|
|
144
|
+
if (!caret || !view) return;
|
|
145
|
+
store.consumeCaret(props.blockId);
|
|
146
|
+
const doc = view.state.doc;
|
|
147
|
+
const from = charToPos(doc, caret.offset);
|
|
148
|
+
const to = caret.to != null ? charToPos(doc, caret.to) : from;
|
|
149
|
+
view.dispatch(view.state.tr.setSelection(TextSelection.create(doc, from, to)).setMeta("external", true));
|
|
150
|
+
// Firefox: đưa focus vào ô trong iframe từ trang ngoài (thanh công cụ, cây khối) phải focus cửa sổ iframe trước
|
|
151
|
+
const win = view.dom.ownerDocument.defaultView;
|
|
152
|
+
if (win && win !== window && !view.dom.ownerDocument.hasFocus()) win.focus();
|
|
153
|
+
view.focus();
|
|
154
|
+
}, [caret, props.blockId, store]);
|
|
155
|
+
|
|
156
|
+
const bp = props.blockProps;
|
|
157
|
+
const ref: Ref<HTMLElement> = (el) => {
|
|
158
|
+
elRef.current = el;
|
|
159
|
+
const r = bp?.ref;
|
|
160
|
+
if (typeof r === "function") r(el);
|
|
161
|
+
else if (r && typeof r === "object") (r as { current: HTMLElement | null }).current = el;
|
|
162
|
+
};
|
|
163
|
+
const className = ["ProseMirror", "ecx-rich", bp?.className, props.className].filter(Boolean).join(" ");
|
|
164
|
+
return createElement(props.tagName ?? "p", {
|
|
165
|
+
...bp,
|
|
166
|
+
ref,
|
|
167
|
+
className,
|
|
168
|
+
style: { ...(bp?.style ?? {}), ...props.style },
|
|
169
|
+
"data-placeholder": props.placeholder,
|
|
170
|
+
"data-placeholder-always": props.placeholderAlways ? "" : undefined,
|
|
171
|
+
"aria-label": props["aria-label"] ?? props.placeholder,
|
|
172
|
+
suppressContentEditableWarning: true,
|
|
173
|
+
contentEditable: editable,
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function syncEmpty(view: EditorView) {
|
|
178
|
+
const empty = view.state.doc.content.size === 0;
|
|
179
|
+
if (empty) {
|
|
180
|
+
view.dom.setAttribute("data-empty", "");
|
|
181
|
+
// Ô trống trong khung co theo nội dung (nút, hàng ngang, ô bảng…): giữ đủ rộng cho chữ gợi ý, không bị cắt / xuống dòng từng chữ
|
|
182
|
+
(view.dom as HTMLElement).style.setProperty("--ecx-ph", String(view.dom.getAttribute("data-placeholder")?.length ?? 0));
|
|
183
|
+
} else view.dom.removeAttribute("data-empty");
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// ---------------------------------------------------------------------------
|
|
187
|
+
// Phím
|
|
188
|
+
// ---------------------------------------------------------------------------
|
|
189
|
+
type PropsRef = { current: RichTextProps };
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Đọc lại vùng chọn từ DOM trước khi xử lý phím: phím di chuyển (End, Home, chuột) đổi vùng chọn của DOM nhưng
|
|
193
|
+
* ProseMirror chỉ biết khi sự kiện selectionchange tới (bất đồng bộ) — gõ nhanh "End rồi Enter" sẽ dùng vùng chọn cũ.
|
|
194
|
+
*/
|
|
195
|
+
function syncSelection(view: EditorView | undefined): EditorState | null {
|
|
196
|
+
if (!view) return null;
|
|
197
|
+
(view as unknown as { domObserver?: { flush?(): void } }).domObserver?.flush?.();
|
|
198
|
+
return view.state;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function atStart(view: EditorView) { const s = view.state.selection; return s.empty && s.from === 0; }
|
|
202
|
+
function atEnd(view: EditorView) { const s = view.state.selection; return s.empty && s.from === view.state.doc.content.size; }
|
|
203
|
+
|
|
204
|
+
/** Mục danh sách chứa khối chữ (khối chữ là con đầu của listItem/taskItem). */
|
|
205
|
+
function listItemOf(store: EditorStore, blockId: string): BNode | null {
|
|
206
|
+
const loc = store.locate(blockId);
|
|
207
|
+
return loc?.parent && (loc.parent.type === "listItem" || loc.parent.type === "taskItem") && loc.index === 0 ? loc.parent : null;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Ô gõ kế bên theo thứ tự trên khung soạn (đi xuyên qua header/footer lồng nhau). */
|
|
211
|
+
export function neighborRich(ui: EditorUi, el: HTMLElement, dir: -1 | 1): HTMLElement | null {
|
|
212
|
+
const doc = el.ownerDocument;
|
|
213
|
+
const all = Array.from(doc.querySelectorAll<HTMLElement>("[data-ecx-rich]")).filter((e) => e.isContentEditable);
|
|
214
|
+
const i = all.indexOf(el);
|
|
215
|
+
void ui;
|
|
216
|
+
return i < 0 ? null : all[i + dir] ?? null;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function focusNeighbor(store: EditorStore, ui: EditorUi, view: EditorView, dir: -1 | 1): boolean {
|
|
220
|
+
const next = neighborRich(ui, view.dom as HTMLElement, dir);
|
|
221
|
+
if (!next) return false;
|
|
222
|
+
const id = next.closest<HTMLElement>("[data-ecx-block]")?.dataset.ecxBlock;
|
|
223
|
+
const field = next.dataset.ecxField;
|
|
224
|
+
if (id && !field) { now(() => store.focusText(id, dir < 0 ? -1 : 0)); return true; }
|
|
225
|
+
const v = [...richViews.entries()].find(([, x]) => x.dom === next)?.[1];
|
|
226
|
+
if (!v) return false;
|
|
227
|
+
v.focus();
|
|
228
|
+
const pos = dir < 0 ? v.state.doc.content.size : 0;
|
|
229
|
+
v.dispatch(v.state.tr.setSelection(TextSelection.create(v.state.doc, pos)));
|
|
230
|
+
return true;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Chạy thao tác của store rồi vẽ lại NGAY (không đợi React gom): khối mới có mặt và nhận con trỏ trước khi phím kế tiếp tới
|
|
235
|
+
* — gõ nhanh sau Enter không lọt chữ vào khối cũ.
|
|
236
|
+
*/
|
|
237
|
+
export function now<T>(fn: () => T): T {
|
|
238
|
+
let out!: T;
|
|
239
|
+
flushSync(() => { out = fn(); });
|
|
240
|
+
return out;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function richKeymap(store: EditorStore, ui: EditorUi, pr: PropsRef, keepCaret: () => boolean = () => false): Plugin {
|
|
244
|
+
// Tuỳ chọn "Giữ con trỏ trong khối": mũi tên ở đầu/cuối khối không nhảy sang khối khác
|
|
245
|
+
const nav = (view: EditorView, dir: -1 | 1) => !keepCaret() && focusNeighbor(store, ui, view, dir);
|
|
246
|
+
const textMode = () => !pr.current.onChange;
|
|
247
|
+
const mark = (name: string) => (state: EditorState, dispatch?: EditorView["dispatch"]) => (state.schema.marks[name] ? toggleMark(state.schema.marks[name])(state, dispatch) : false);
|
|
248
|
+
const slashKey = (key: string) => () => (ui.inserter?.mode === "slash" && ui.inserter.blockId === pr.current.blockId && ui.inserterKey ? ui.inserterKey(key) : false);
|
|
249
|
+
/** Lệnh dùng vùng chọn mới nhất (đọc lại từ DOM). */
|
|
250
|
+
const fresh = (cmd: (state: EditorState, dispatch: EditorView["dispatch"] | undefined, view: EditorView | undefined) => boolean) =>
|
|
251
|
+
(state: EditorState, dispatch?: EditorView["dispatch"], view?: EditorView) => {
|
|
252
|
+
const s = syncSelection(view) ?? state;
|
|
253
|
+
return cmd(s, view ? view.dispatch.bind(view) : dispatch, view);
|
|
254
|
+
};
|
|
255
|
+
return keymap({
|
|
256
|
+
ArrowDown: (_s, _d, view) => slashKey("ArrowDown")() || (!!view && view.endOfTextblock("down") && nav(view, 1)),
|
|
257
|
+
ArrowUp: (_s, _d, view) => slashKey("ArrowUp")() || (!!view && view.endOfTextblock("up") && nav(view, -1)),
|
|
258
|
+
// Shift+mũi tên ra ngoài khối: chọn chữ sang khối kế
|
|
259
|
+
"Shift-ArrowDown": (_s, _d, view) => !!view && textMode() && !pr.current.field && view.endOfTextblock("down") && startRange(store, view, pr.current.blockId, 1),
|
|
260
|
+
"Shift-ArrowUp": (_s, _d, view) => !!view && textMode() && !pr.current.field && view.endOfTextblock("up") && startRange(store, view, pr.current.blockId, -1),
|
|
261
|
+
ArrowLeft: fresh((_s, _d, view) => !!view && atStart(view) && nav(view, -1)),
|
|
262
|
+
ArrowRight: fresh((_s, _d, view) => !!view && atEnd(view) && nav(view, 1)),
|
|
263
|
+
Escape: (_s, _d, view) => {
|
|
264
|
+
if (slashKey("Escape")()) return true;
|
|
265
|
+
store.select([pr.current.blockId]);
|
|
266
|
+
(view?.dom as HTMLElement | undefined)?.blur();
|
|
267
|
+
return true;
|
|
268
|
+
},
|
|
269
|
+
Tab: () => {
|
|
270
|
+
if (slashKey("Enter")()) return true;
|
|
271
|
+
const item = textMode() ? listItemOf(store, pr.current.blockId) : null;
|
|
272
|
+
if (!item) return false;
|
|
273
|
+
now(() => store.indentItem(item.id));
|
|
274
|
+
return true;
|
|
275
|
+
},
|
|
276
|
+
"Shift-Tab": () => {
|
|
277
|
+
const item = textMode() ? listItemOf(store, pr.current.blockId) : null;
|
|
278
|
+
if (!item) return false;
|
|
279
|
+
now(() => store.outdentItem(item.id, true));
|
|
280
|
+
return true;
|
|
281
|
+
},
|
|
282
|
+
Enter: fresh((state, dispatch, view) => {
|
|
283
|
+
if (slashKey("Enter")()) return true;
|
|
284
|
+
const p = pr.current;
|
|
285
|
+
if (!textMode()) return true;
|
|
286
|
+
if (p.breakOnEnter) {
|
|
287
|
+
dispatch?.(state.tr.replaceSelectionWith(state.schema.nodes.hardBreak.create()).scrollIntoView());
|
|
288
|
+
return true;
|
|
289
|
+
}
|
|
290
|
+
if (p.multiline) {
|
|
291
|
+
const text = state.doc.textContent;
|
|
292
|
+
// Mã nguồn: Enter ở dòng trống cuối cùng → thoát ra đoạn văn mới (bỏ dòng trống)
|
|
293
|
+
if (atEnd(view!) && text.endsWith("\n")) {
|
|
294
|
+
const trimmed = text.replace(/\n+$/, "");
|
|
295
|
+
now(() => store.batch(() => {
|
|
296
|
+
store.setInline(p.blockId, trimmed ? [{ type: "text", text: trimmed }] : []);
|
|
297
|
+
store.splitText(p.blockId, trimmed.length);
|
|
298
|
+
}));
|
|
299
|
+
return true;
|
|
300
|
+
}
|
|
301
|
+
dispatch?.(state.tr.insertText("\n"));
|
|
302
|
+
return true;
|
|
303
|
+
}
|
|
304
|
+
// "---" + Enter → đường kẻ
|
|
305
|
+
const blk = store.block(p.blockId);
|
|
306
|
+
if (blk?.type === "paragraph" && state.doc.textContent === "---") {
|
|
307
|
+
const hr = makeBlock("horizontalRule");
|
|
308
|
+
const para = makeBlock("paragraph");
|
|
309
|
+
now(() => store.replace(p.blockId, [hr, para], { select: { ids: [], editing: para.id }, caret: { id: para.id, offset: 0 } }));
|
|
310
|
+
return true;
|
|
311
|
+
}
|
|
312
|
+
now(() => store.splitText(p.blockId, state.selection.from, state.selection.to));
|
|
313
|
+
return true;
|
|
314
|
+
}),
|
|
315
|
+
"Shift-Enter": fresh((state, dispatch) => {
|
|
316
|
+
if (!state.schema.nodes.hardBreak) dispatch?.(state.tr.insertText("\n"));
|
|
317
|
+
else dispatch?.(state.tr.replaceSelectionWith(state.schema.nodes.hardBreak.create()).scrollIntoView());
|
|
318
|
+
return true;
|
|
319
|
+
}),
|
|
320
|
+
Backspace: fresh((_s, _d, view) => {
|
|
321
|
+
if (!view || !atStart(view) || !textMode()) return false;
|
|
322
|
+
now(() => store.mergeBackward(pr.current.blockId));
|
|
323
|
+
return true;
|
|
324
|
+
}),
|
|
325
|
+
Delete: fresh((_s, _d, view) => {
|
|
326
|
+
if (!view || !atEnd(view) || !textMode()) return false;
|
|
327
|
+
now(() => store.mergeForward(pr.current.blockId));
|
|
328
|
+
return true;
|
|
329
|
+
}),
|
|
330
|
+
"Mod-a": fresh((state) => {
|
|
331
|
+
// Đã chọn hết chữ trong khối → chọn mọi khối của tài liệu
|
|
332
|
+
if (!textMode() || state.selection.from > 0 || state.selection.to < state.doc.content.size) return false;
|
|
333
|
+
const loc = store.locate(pr.current.blockId);
|
|
334
|
+
if (!loc) return false;
|
|
335
|
+
store.select(store.getState().docs[loc.docId].blocks.map((b) => b.id), { editing: null });
|
|
336
|
+
return true;
|
|
337
|
+
}),
|
|
338
|
+
"Alt-F10": () => { ui.focusToolbar(); return true; },
|
|
339
|
+
"Mod-z": () => { now(() => store.undo()); return true; },
|
|
340
|
+
"Mod-Shift-z": () => { now(() => store.redo()); return true; },
|
|
341
|
+
"Mod-y": () => { now(() => store.redo()); return true; },
|
|
342
|
+
"Mod-b": mark("bold"),
|
|
343
|
+
"Mod-i": mark("italic"),
|
|
344
|
+
"Mod-u": mark("underline"),
|
|
345
|
+
"Mod-Shift-x": mark("strike"),
|
|
346
|
+
"Mod-e": mark("code"),
|
|
347
|
+
"Mod-k": () => { if (pr.current.plain || pr.current.multiline) return false; ui.openLink?.(viewKey(pr.current.blockId, pr.current.field)); return true; },
|
|
348
|
+
"Mod-Shift-d": () => { if (!textMode()) return false; store.duplicate([pr.current.blockId]); return true; },
|
|
349
|
+
"Shift-Alt-z": () => { if (!textMode()) return false; store.remove([pr.current.blockId]); return true; },
|
|
350
|
+
"Mod-Alt-t": () => { insertSibling(store, pr.current.blockId, 0); return true; },
|
|
351
|
+
"Mod-Alt-y": () => { insertSibling(store, pr.current.blockId, 1); return true; },
|
|
352
|
+
"Mod-Shift-Alt-t": () => { store.moveBy([pr.current.blockId], -1); return true; },
|
|
353
|
+
"Mod-Shift-Alt-y": () => { store.moveBy([pr.current.blockId], 1); return true; },
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** Thêm đoạn văn trống trước (0) / sau (1) khối. */
|
|
358
|
+
export function insertSibling(store: EditorStore, blockId: string, after: 0 | 1) {
|
|
359
|
+
const loc = store.locate(blockId);
|
|
360
|
+
if (!loc) return;
|
|
361
|
+
const p = makeBlock("paragraph");
|
|
362
|
+
store.insert(loc.docId, loc.parent?.id ?? null, loc.index + after, [p]);
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/** Báo vị trí con trỏ cho store (hoàn tác trả con trỏ về đúng chỗ) và cho thanh công cụ (định dạng đang bật). */
|
|
366
|
+
function selectionReporter(store: EditorStore, ui: EditorUi, pr: PropsRef): Plugin {
|
|
367
|
+
return new Plugin({
|
|
368
|
+
view: () => ({
|
|
369
|
+
update(view, prev) {
|
|
370
|
+
if (view.state.selection.eq(prev.selection) && view.state.doc.eq(prev.doc)) return;
|
|
371
|
+
if (!view.hasFocus()) return;
|
|
372
|
+
const s = view.state.selection;
|
|
373
|
+
if (!pr.current.onChange) store.reportCaret({ id: pr.current.blockId, offset: s.from, to: s.to });
|
|
374
|
+
if (!view.state.doc.eq(prev.doc)) return ui.bump();
|
|
375
|
+
// Di chuyển con trỏ: lần gõ sau là một bước hoàn tác mới
|
|
376
|
+
store.breakMerge();
|
|
377
|
+
ui.bump();
|
|
378
|
+
},
|
|
379
|
+
}),
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
// ---------------------------------------------------------------------------
|
|
384
|
+
// Gõ tắt kiểu Markdown + slash
|
|
385
|
+
// ---------------------------------------------------------------------------
|
|
386
|
+
const PREFIX_RULES: Array<{ re: RegExp; make(rest: RichNode[]): { blocks: BNode[]; focus: BNode } }> = [
|
|
387
|
+
...[1, 2, 3, 4, 5, 6].map((level) => ({
|
|
388
|
+
re: new RegExp(`^#{${level}}$`),
|
|
389
|
+
make: (rest: RichNode[]) => { const h = makeBlock("heading", { level }, rest); return { blocks: [h], focus: h }; },
|
|
390
|
+
})),
|
|
391
|
+
{ re: /^[-*+]$/, make: (rest) => { const p = makeBlock("paragraph", {}, rest); return { blocks: [makeBlock("bulletList", {}, [makeBlock("listItem", {}, [p])])], focus: p }; } },
|
|
392
|
+
{ re: /^1[.)]$/, make: (rest) => { const p = makeBlock("paragraph", {}, rest); return { blocks: [makeBlock("orderedList", {}, [makeBlock("listItem", {}, [p])])], focus: p }; } },
|
|
393
|
+
{ re: /^\[ ?\]$/, make: (rest) => { const p = makeBlock("paragraph", {}, rest); return { blocks: [makeBlock("taskList", {}, [makeBlock("taskItem", { checked: false }, [p])])], focus: p }; } },
|
|
394
|
+
{ re: /^>$/, make: (rest) => { const p = makeBlock("paragraph", {}, rest); return { blocks: [makeBlock("blockquote", {}, [p])], focus: p }; } },
|
|
395
|
+
];
|
|
396
|
+
|
|
397
|
+
function inputRule(view: EditorView, store: EditorStore, p: RichTextProps, from: number, to: number, text: string): boolean {
|
|
398
|
+
if (p.onChange || p.plain) return false;
|
|
399
|
+
const blk = store.block(p.blockId);
|
|
400
|
+
if (!blk || blk.type !== "paragraph") return false;
|
|
401
|
+
const before = view.state.doc.textBetween(0, from, "\n", "");
|
|
402
|
+
if (text === " " && from === to) {
|
|
403
|
+
const rule = PREFIX_RULES.find((r) => r.re.test(before));
|
|
404
|
+
if (!rule) return false;
|
|
405
|
+
// Nằm trong mục danh sách thì không đổi thành danh sách lồng (tránh "- " trong danh sách)
|
|
406
|
+
if (listItemOf(store, p.blockId) && !rule.re.test("#")) return false;
|
|
407
|
+
const rest = docToInline(view.state.doc.cut(to));
|
|
408
|
+
const { blocks, focus } = rule.make(rest);
|
|
409
|
+
now(() => store.replace(p.blockId, blocks, { select: { ids: [], editing: focus.id }, caret: { id: focus.id, offset: 0 } }));
|
|
410
|
+
return true;
|
|
411
|
+
}
|
|
412
|
+
if (text === "`" && before === "``" && from === to && from === 2) {
|
|
413
|
+
const code = makeBlock("codeBlock", {}, docToInline(view.state.doc.cut(to)).filter((n) => n.type === "text").map((n) => ({ type: "text", text: n.text })));
|
|
414
|
+
now(() => store.replace(p.blockId, [code], { select: { ids: [], editing: code.id }, caret: { id: code.id, offset: 0 } }));
|
|
415
|
+
return true;
|
|
416
|
+
}
|
|
417
|
+
// **đậm** / *nghiêng* / `mã`: gõ dấu đóng → áp định dạng, bỏ dấu
|
|
418
|
+
if (from !== to) return false;
|
|
419
|
+
const rules: Array<[RegExp, string, string, number]> = [[/\*\*([^*\s][^*]*)\*$/, "*", "bold", 2], [/(?:^|[^*])\*([^*\s][^*]*)$/, "*", "italic", 1], [/`([^`]+)$/, "`", "code", 1]];
|
|
420
|
+
for (const [re, ch, markName, open] of rules) {
|
|
421
|
+
if (text !== ch) continue;
|
|
422
|
+
const m = re.exec(before);
|
|
423
|
+
if (!m) continue;
|
|
424
|
+
const inner = m[1];
|
|
425
|
+
// bold: "**chữ*" + "*" — dấu đóng đầu tiên đã nằm trong chữ
|
|
426
|
+
const closeTyped = markName === "bold" ? 1 : 0;
|
|
427
|
+
const openStart = from - inner.length - open - closeTyped;
|
|
428
|
+
const mk = view.state.schema.marks[markName].create();
|
|
429
|
+
const tr = view.state.tr;
|
|
430
|
+
if (closeTyped) tr.delete(from - 1, from);
|
|
431
|
+
tr.delete(openStart, openStart + open).addMark(openStart, openStart + inner.length, mk).removeStoredMark(mk);
|
|
432
|
+
view.dispatch(tr);
|
|
433
|
+
return true;
|
|
434
|
+
}
|
|
435
|
+
return false;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
function detectSlash(view: EditorView, store: EditorStore, ui: EditorUi, p: RichTextProps) {
|
|
439
|
+
const text = view.state.doc.textContent;
|
|
440
|
+
const blk = store.block(p.blockId);
|
|
441
|
+
// "/" + từ khoá (cho phép nhiều từ: "/tieu de"), tối đa 40 ký tự
|
|
442
|
+
const m = /^\/((?:[^\s/][^/]{0,39})?)$/.exec(text);
|
|
443
|
+
const open = ui.inserter?.mode === "slash" && ui.inserter.blockId === p.blockId;
|
|
444
|
+
if (m && blk?.type === "paragraph" && view.state.selection.from === view.state.doc.content.size && store.canRemove(p.blockId)) {
|
|
445
|
+
const loc = store.locate(p.blockId)!;
|
|
446
|
+
const r = caretRect(view, ui);
|
|
447
|
+
ui.openInserter({ mode: "slash", docId: loc.docId, parentId: loc.parent?.id ?? null, index: loc.index, blockId: p.blockId, query: m[1], rect: r });
|
|
448
|
+
} else if (open) ui.openInserter(null);
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/** Toạ độ con trỏ theo trang ngoài (popover neo vào đây). */
|
|
452
|
+
export function caretRect(view: EditorView, ui: EditorUi) {
|
|
453
|
+
const c = view.coordsAtPos(view.state.selection.from);
|
|
454
|
+
const f = ui.canvasFrame?.getBoundingClientRect();
|
|
455
|
+
const scale = f && ui.canvasFrame ? f.width / (ui.canvasFrame.offsetWidth || f.width) || 1 : 1;
|
|
456
|
+
const ox = f?.left ?? 0, oy = f?.top ?? 0;
|
|
457
|
+
return { left: ox + c.left * scale, top: oy + c.top * scale, bottom: oy + c.bottom * scale };
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
export const isEmptyInline = (inline: RichNode[] | undefined) => !inlineLength(inline);
|
|
461
|
+
|
|
462
|
+
// ---------------------------------------------------------------------------
|
|
463
|
+
// Chọn chữ qua nhiều khối
|
|
464
|
+
// ---------------------------------------------------------------------------
|
|
465
|
+
/** Rời ô gõ, focus về khung soạn (phím của dải chữ do khung soạn xử lý), bỏ vùng chọn của trình duyệt. */
|
|
466
|
+
function leaveForRange(view: EditorView) {
|
|
467
|
+
const doc = view.dom.ownerDocument;
|
|
468
|
+
(view.dom as HTMLElement).blur();
|
|
469
|
+
doc.getSelection()?.removeAllRanges();
|
|
470
|
+
doc.querySelector<HTMLElement>(".ecx-canvas-root")?.focus({ preventScroll: true });
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
function startRange(store: EditorStore, view: EditorView, id: string, dir: -1 | 1): boolean {
|
|
474
|
+
const loc = store.locate(id);
|
|
475
|
+
if (!loc) return false;
|
|
476
|
+
const order = flatten(store.getState().docs[loc.docId].blocks).filter((b) => b.inline);
|
|
477
|
+
const next = order[order.findIndex((b) => b.id === id) + dir];
|
|
478
|
+
if (!next) return false;
|
|
479
|
+
const anchor = { id, offset: (syncSelection(view) ?? view.state).selection.anchor };
|
|
480
|
+
leaveForRange(view);
|
|
481
|
+
store.selectText(anchor, { id: next.id, offset: dir > 0 ? inlineLength(next.inline) : 0 });
|
|
482
|
+
return true;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/** Theo chuột từ lúc bấm trong ô gõ tới lúc nhả: sang khối chữ khác → dải chữ; quay về ô cũ → chọn chữ trong ô. */
|
|
486
|
+
function trackRangeDrag(store: EditorStore, view: EditorView, id: string) {
|
|
487
|
+
const doc = view.dom.ownerDocument;
|
|
488
|
+
let anchor: number | null = null;
|
|
489
|
+
let crossed = false;
|
|
490
|
+
const move = (e: MouseEvent) => {
|
|
491
|
+
if (!(e.buttons & 1)) return up();
|
|
492
|
+
const rich = (doc.elementFromPoint(e.clientX, e.clientY) as HTMLElement | null)?.closest<HTMLElement>("[data-ecx-rich]:not([data-ecx-field])");
|
|
493
|
+
const bid = rich?.closest<HTMLElement>("[data-ecx-block]")?.dataset.ecxBlock;
|
|
494
|
+
if (!bid) return;
|
|
495
|
+
const target = bid === id ? view : richViews.get(bid);
|
|
496
|
+
if (!target) return;
|
|
497
|
+
if (bid === id && !crossed) return; // trong cùng ô: ProseMirror tự chọn
|
|
498
|
+
if (anchor == null) anchor = view.state.selection.anchor;
|
|
499
|
+
const pos = target.posAtCoords({ left: e.clientX, top: e.clientY })?.pos ?? 0;
|
|
500
|
+
if (!crossed) { crossed = true; leaveForRange(view); }
|
|
501
|
+
e.preventDefault();
|
|
502
|
+
store.selectText({ id, offset: anchor }, { id: bid, offset: pos });
|
|
503
|
+
if (bid === id) crossed = false;
|
|
504
|
+
};
|
|
505
|
+
const up = () => {
|
|
506
|
+
doc.removeEventListener("mousemove", move);
|
|
507
|
+
doc.removeEventListener("mouseup", up);
|
|
508
|
+
if (store.getState().range) { doc.getSelection()?.removeAllRanges(); doc.querySelector<HTMLElement>(".ecx-canvas-root")?.focus({ preventScroll: true }); }
|
|
509
|
+
};
|
|
510
|
+
doc.addEventListener("mousemove", move);
|
|
511
|
+
doc.addEventListener("mouseup", up);
|
|
512
|
+
}
|