@ecomcx/ecomweb-editor 1.18.0 → 1.19.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 +149 -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 +310 -0
- package/src/v2/editor.tsx +288 -0
- package/src/v2/index.ts +28 -0
- package/src/v2/labels.ts +341 -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 +109 -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 +397 -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,804 @@
|
|
|
1
|
+
import type { RichNode } from "@ecomcx/ecomweb-content";
|
|
2
|
+
import { cloneBlock, inlineLength, joinInline, kindOf, makeBlock, splitInline, type BNode } from "./model";
|
|
3
|
+
import { findBlock, flatten, insertBlocks, mapBlock, moveBlocks, removeBlocks, setAttrs, sibling, topLevelOrdered, type Location } from "./ops";
|
|
4
|
+
import { canContain, fixTree } from "./structure";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Store của trình soạn: nhiều tài liệu cùng lúc (bài/template đang mở + header, footer, mẫu đồng bộ lồng bên trong),
|
|
8
|
+
* một lịch sử hoàn tác chung xuyên tài liệu, vùng chọn khối, yêu cầu đặt con trỏ cho khối chữ.
|
|
9
|
+
* Không phụ thuộc React — React đọc qua useSyncExternalStore (hooks.ts).
|
|
10
|
+
*/
|
|
11
|
+
export type EditingMode = "default" | "contentOnly" | "disabled";
|
|
12
|
+
|
|
13
|
+
export interface DocRecord {
|
|
14
|
+
id: string;
|
|
15
|
+
/** Loại tài liệu của ứng dụng: post, template, part, pattern… */
|
|
16
|
+
kind: string;
|
|
17
|
+
/** Tham chiếu của ứng dụng (slug phần dùng chung, id mẫu…). */
|
|
18
|
+
ref?: unknown;
|
|
19
|
+
title?: string;
|
|
20
|
+
blocks: BNode[];
|
|
21
|
+
/** Bản đã lưu — `blocks !== saved` là có thay đổi chưa lưu. */
|
|
22
|
+
saved: BNode[];
|
|
23
|
+
status: "loading" | "ready" | "error";
|
|
24
|
+
error?: string;
|
|
25
|
+
mode: EditingMode;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Yêu cầu đặt con trỏ: khối chữ đọc rồi xoá (consumeCaret). */
|
|
29
|
+
export interface Caret {
|
|
30
|
+
id: string;
|
|
31
|
+
/** Vị trí ký tự; -1 = cuối. `to` có = chọn đoạn [offset, to]. */
|
|
32
|
+
offset: number;
|
|
33
|
+
to?: number;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface Selection {
|
|
37
|
+
/** Các khối đang chọn (chọn khối, không phải chọn chữ). Rỗng = không chọn. */
|
|
38
|
+
ids: string[];
|
|
39
|
+
/** Khối đang gõ chữ (chọn ngầm) — thanh công cụ, bảng cài đặt dùng khối này khi ids rỗng. */
|
|
40
|
+
editing: string | null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface EditorState {
|
|
44
|
+
docs: Record<string, DocRecord>;
|
|
45
|
+
rootId: string;
|
|
46
|
+
/** Chế độ tập trung: tài liệu đang sửa riêng (đỉnh ngăn xếp), rỗng = tài liệu gốc. */
|
|
47
|
+
focus: string[];
|
|
48
|
+
selection: Selection;
|
|
49
|
+
caret: Caret | null;
|
|
50
|
+
/** Tăng mỗi lần thay đổi nội dung (để UI biết cần đo lại vị trí). */
|
|
51
|
+
revision: number;
|
|
52
|
+
/**
|
|
53
|
+
* Template bao quanh tài liệu gốc (chế độ "sửa trang trong template"): template hiện nhưng khoá,
|
|
54
|
+
* khối "Nội dung bài" trong template là chỗ sửa tài liệu gốc. null = chỉ hiện tài liệu gốc.
|
|
55
|
+
*/
|
|
56
|
+
frameId: string | null;
|
|
57
|
+
/** Chọn chữ qua nhiều khối (kéo chuột / Shift+mũi tên ra ngoài khối): điểm neo → điểm đầu, cùng một tài liệu. null = không. */
|
|
58
|
+
range: TextRange | null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface TextPoint { id: string; offset: number }
|
|
62
|
+
export interface TextRange { anchor: TextPoint; head: TextPoint }
|
|
63
|
+
|
|
64
|
+
interface Change { docId: string; before: BNode[]; after: BNode[] }
|
|
65
|
+
interface HistoryEntry {
|
|
66
|
+
changes: Change[];
|
|
67
|
+
selBefore: Selection;
|
|
68
|
+
selAfter: Selection;
|
|
69
|
+
caretBefore: Caret | null;
|
|
70
|
+
caretAfter: Caret | null;
|
|
71
|
+
key?: string;
|
|
72
|
+
time: number;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface CommitOptions {
|
|
76
|
+
/** Gộp với lần sửa trước cùng khoá trong 1 giây (gõ chữ liên tục = một lần hoàn tác). */
|
|
77
|
+
merge?: string;
|
|
78
|
+
/** Không ghi lịch sử (nạp tài liệu, đồng bộ từ ngoài). */
|
|
79
|
+
history?: false;
|
|
80
|
+
/** Chỉ đổi chữ / thuộc tính, không đổi cấu trúc → bỏ qua kiểm tra cấu trúc cả cây (gõ phím trong tài liệu dài). */
|
|
81
|
+
structural?: false;
|
|
82
|
+
select?: Partial<Selection>;
|
|
83
|
+
caret?: Caret | null;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const MERGE_MS = 1000;
|
|
87
|
+
const HISTORY_LIMIT = 300;
|
|
88
|
+
const emptySel: Selection = { ids: [], editing: null };
|
|
89
|
+
|
|
90
|
+
export class EditorStore {
|
|
91
|
+
private state: EditorState;
|
|
92
|
+
private listeners = new Set<() => void>();
|
|
93
|
+
private undoStack: HistoryEntry[] = [];
|
|
94
|
+
private redoStack: HistoryEntry[] = [];
|
|
95
|
+
private batchDepth = 0;
|
|
96
|
+
private pending: HistoryEntry | null = null;
|
|
97
|
+
|
|
98
|
+
constructor(root: { id?: string; kind?: string; ref?: unknown; title?: string; blocks: BNode[] }) {
|
|
99
|
+
const id = root.id ?? "root";
|
|
100
|
+
const blocks = fixTree(root.blocks);
|
|
101
|
+
this.state = {
|
|
102
|
+
docs: { [id]: { id, kind: root.kind ?? "post", ref: root.ref, title: root.title, blocks, saved: blocks, status: "ready", mode: "default" } },
|
|
103
|
+
rootId: id,
|
|
104
|
+
focus: [],
|
|
105
|
+
selection: emptySel,
|
|
106
|
+
caret: null,
|
|
107
|
+
range: null,
|
|
108
|
+
revision: 0,
|
|
109
|
+
frameId: null,
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Đặt / bỏ template bao quanh (tài liệu đã có trong store, thường ở chế độ disabled). */
|
|
114
|
+
setFrame(docId: string | null) { if (this.state.frameId !== docId) this.set({ frameId: docId, selection: emptySel, caret: null }); }
|
|
115
|
+
|
|
116
|
+
// -------------------------------------------------------------------------
|
|
117
|
+
// Đọc / theo dõi
|
|
118
|
+
// -------------------------------------------------------------------------
|
|
119
|
+
getState = (): EditorState => this.state;
|
|
120
|
+
subscribe = (l: () => void) => { this.listeners.add(l); return () => { this.listeners.delete(l); }; };
|
|
121
|
+
private emit() { this.listeners.forEach((l) => l()); }
|
|
122
|
+
// Đổi vùng chọn / con trỏ mà không nói gì về dải chữ → bỏ dải chữ
|
|
123
|
+
private set(next: Partial<EditorState>) { this.state = { ...this.state, ...(("selection" in next || "caret" in next) && !("range" in next) ? { range: null } : {}), ...next }; this.emit(); }
|
|
124
|
+
|
|
125
|
+
get canUndo() { return this.undoStack.length > 0; }
|
|
126
|
+
get canRedo() { return this.redoStack.length > 0; }
|
|
127
|
+
|
|
128
|
+
doc(id: string): DocRecord | undefined { return this.state.docs[id]; }
|
|
129
|
+
/** Tài liệu đang hiện trên khung soạn (chế độ tập trung hoặc gốc). */
|
|
130
|
+
get activeDocId() { return this.state.focus[this.state.focus.length - 1] ?? this.state.rootId; }
|
|
131
|
+
|
|
132
|
+
/** Tìm khối trong mọi tài liệu. */
|
|
133
|
+
locate(id: string): (Location & { docId: string }) | null {
|
|
134
|
+
for (const d of Object.values(this.state.docs)) {
|
|
135
|
+
const loc = findBlock(d.blocks, id);
|
|
136
|
+
if (loc) return { ...loc, docId: d.id };
|
|
137
|
+
}
|
|
138
|
+
return null;
|
|
139
|
+
}
|
|
140
|
+
block(id: string): BNode | null { return this.locate(id)?.block ?? null; }
|
|
141
|
+
|
|
142
|
+
/** Khối đang thao tác: chọn khối hoặc khối đang gõ chữ. */
|
|
143
|
+
get currentIds(): string[] {
|
|
144
|
+
const s = this.state.selection;
|
|
145
|
+
return s.ids.length ? s.ids : s.editing ? [s.editing] : [];
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
isDirty(docId?: string) {
|
|
149
|
+
const docs = docId ? [this.state.docs[docId]].filter(Boolean) : Object.values(this.state.docs);
|
|
150
|
+
return docs.some((d) => d.blocks !== d.saved);
|
|
151
|
+
}
|
|
152
|
+
dirtyDocs(): DocRecord[] { return Object.values(this.state.docs).filter((d) => d.blocks !== d.saved); }
|
|
153
|
+
|
|
154
|
+
/** Khối có sửa được không (theo chế độ của tài liệu chứa nó). */
|
|
155
|
+
modeOf(blockId: string): EditingMode {
|
|
156
|
+
const loc = this.locate(blockId);
|
|
157
|
+
return loc ? this.state.docs[loc.docId].mode : "disabled";
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// -------------------------------------------------------------------------
|
|
161
|
+
// Khoá khối: attrs.lock { move, remove } trên khối; attrs.templateLock trên khối chứa (all | insert | contentOnly),
|
|
162
|
+
// áp cho mọi khối bên trong tới khi gặp khối chứa khác có templateLock riêng.
|
|
163
|
+
// -------------------------------------------------------------------------
|
|
164
|
+
/** templateLock có hiệu lực với khối con của `parentId` (null = cấp cao nhất của tài liệu). */
|
|
165
|
+
templateLockOf(parentId: string | null): "all" | "insert" | "contentOnly" | undefined {
|
|
166
|
+
let id = parentId;
|
|
167
|
+
while (id) {
|
|
168
|
+
const loc = this.locate(id);
|
|
169
|
+
if (!loc) return undefined;
|
|
170
|
+
const tl = loc.block.attrs.templateLock;
|
|
171
|
+
if (tl === "all" || tl === "insert" || tl === "contentOnly") return tl;
|
|
172
|
+
if (tl === false || tl === "none") return undefined;
|
|
173
|
+
id = loc.parent?.id ?? null;
|
|
174
|
+
}
|
|
175
|
+
return undefined;
|
|
176
|
+
}
|
|
177
|
+
private parentOf(id: string): string | null | undefined { const loc = this.locate(id); return loc ? loc.parent?.id ?? null : undefined; }
|
|
178
|
+
canRemove(id: string): boolean {
|
|
179
|
+
const loc = this.locate(id);
|
|
180
|
+
if (!loc || (loc.block.attrs.lock as { remove?: boolean } | undefined)?.remove) return false;
|
|
181
|
+
return !this.templateLockOf(loc.parent?.id ?? null);
|
|
182
|
+
}
|
|
183
|
+
canMove(id: string): boolean {
|
|
184
|
+
const loc = this.locate(id);
|
|
185
|
+
if (!loc || (loc.block.attrs.lock as { move?: boolean } | undefined)?.move) return false;
|
|
186
|
+
const tl = this.templateLockOf(loc.parent?.id ?? null);
|
|
187
|
+
return tl !== "all" && tl !== "contentOnly";
|
|
188
|
+
}
|
|
189
|
+
canInsertInto(parentId: string | null): boolean { return !this.templateLockOf(parentId); }
|
|
190
|
+
/** Khối nằm trong vùng "chỉ sửa nội dung": sửa chữ được, không đổi cấu trúc / kiểu dáng. */
|
|
191
|
+
isContentOnly(id: string): boolean { return this.templateLockOf(this.parentOf(id) ?? null) === "contentOnly" || this.locate(id)?.block.attrs.templateLock === "contentOnly"; }
|
|
192
|
+
|
|
193
|
+
// -------------------------------------------------------------------------
|
|
194
|
+
// Tài liệu lồng nhau
|
|
195
|
+
// -------------------------------------------------------------------------
|
|
196
|
+
/** Thêm / thay tài liệu (vd ứng dụng vừa tải xong header). Không ghi lịch sử. */
|
|
197
|
+
putDoc(doc: Partial<DocRecord> & { id: string; kind: string }) {
|
|
198
|
+
const prev = this.state.docs[doc.id];
|
|
199
|
+
const blocks = doc.blocks ? fixTree(doc.blocks) : prev?.blocks ?? [];
|
|
200
|
+
const rec: DocRecord = {
|
|
201
|
+
id: doc.id, kind: doc.kind, ref: doc.ref ?? prev?.ref, title: doc.title ?? prev?.title,
|
|
202
|
+
blocks, saved: doc.blocks ? blocks : prev?.saved ?? blocks,
|
|
203
|
+
status: doc.status ?? "ready", error: doc.error, mode: doc.mode ?? prev?.mode ?? "default",
|
|
204
|
+
};
|
|
205
|
+
this.set({ docs: { ...this.state.docs, [doc.id]: rec }, revision: this.state.revision + 1 });
|
|
206
|
+
}
|
|
207
|
+
setDocMode(docId: string, mode: EditingMode) {
|
|
208
|
+
const d = this.state.docs[docId];
|
|
209
|
+
if (d && d.mode !== mode) this.set({ docs: { ...this.state.docs, [docId]: { ...d, mode } } });
|
|
210
|
+
}
|
|
211
|
+
/** Đánh dấu đã lưu (sau khi ứng dụng lưu xong). `blocks` = bản đã gửi đi — sửa tiếp trong lúc lưu vẫn tính là chưa lưu. */
|
|
212
|
+
markSaved(docId: string, blocks?: BNode[]) {
|
|
213
|
+
const d = this.state.docs[docId];
|
|
214
|
+
if (d) this.set({ docs: { ...this.state.docs, [docId]: { ...d, saved: blocks ?? d.blocks } } });
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
enterFocus(docId: string) {
|
|
218
|
+
if (!this.state.docs[docId] || this.activeDocId === docId) return;
|
|
219
|
+
this.set({ focus: [...this.state.focus, docId], selection: emptySel, caret: null });
|
|
220
|
+
}
|
|
221
|
+
exitFocus() {
|
|
222
|
+
if (this.state.focus.length) this.set({ focus: this.state.focus.slice(0, -1), selection: emptySel, caret: null });
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// -------------------------------------------------------------------------
|
|
226
|
+
// Ghi thay đổi + lịch sử
|
|
227
|
+
// -------------------------------------------------------------------------
|
|
228
|
+
/** Gom nhiều thao tác thành một lần hoàn tác. */
|
|
229
|
+
batch<T>(fn: () => T): T {
|
|
230
|
+
this.batchDepth++;
|
|
231
|
+
try { return fn(); } finally {
|
|
232
|
+
if (--this.batchDepth === 0 && this.pending) { this.pushHistory(this.pending); this.pending = null; }
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** Thay toàn bộ khối của một tài liệu. */
|
|
237
|
+
commit(docId: string, blocks: BNode[], opts: CommitOptions = {}) {
|
|
238
|
+
const d = this.state.docs[docId];
|
|
239
|
+
if (!d || d.mode === "disabled") return;
|
|
240
|
+
const fixed = opts.structural === false ? blocks : fixTree(blocks);
|
|
241
|
+
const selection = opts.select ? { ...this.state.selection, ...opts.select } : this.state.selection;
|
|
242
|
+
const caret = opts.caret !== undefined ? opts.caret : this.state.caret;
|
|
243
|
+
if (fixed === d.blocks) {
|
|
244
|
+
if (selection !== this.state.selection || caret !== this.state.caret) this.set({ selection, caret });
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
if (opts.history !== false) {
|
|
248
|
+
const entry: HistoryEntry = {
|
|
249
|
+
changes: [{ docId, before: d.blocks, after: fixed }], selBefore: this.state.selection, selAfter: selection,
|
|
250
|
+
caretBefore: this.caretFor(this.state.selection), caretAfter: caret, key: opts.merge, time: Date.now(),
|
|
251
|
+
};
|
|
252
|
+
if (this.batchDepth) {
|
|
253
|
+
if (!this.pending) this.pending = entry;
|
|
254
|
+
else this.mergeInto(this.pending, entry);
|
|
255
|
+
} else this.pushHistory(entry);
|
|
256
|
+
}
|
|
257
|
+
const docs = { ...this.state.docs, [docId]: { ...d, blocks: fixed } };
|
|
258
|
+
this.set({ docs, selection: pruneSelection(docs, selection), caret, revision: this.state.revision + 1 });
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
private caretFor(sel: Selection): Caret | null {
|
|
262
|
+
return sel.editing ? (this.lastCaret?.id === sel.editing ? this.lastCaret : { id: sel.editing, offset: -1 }) : null;
|
|
263
|
+
}
|
|
264
|
+
/** Vị trí con trỏ gần nhất do khối chữ báo lên (để hoàn tác trả con trỏ về đúng chỗ). */
|
|
265
|
+
private lastCaret: Caret | null = null;
|
|
266
|
+
reportCaret(c: Caret | null) { this.lastCaret = c; }
|
|
267
|
+
|
|
268
|
+
private mergeInto(into: HistoryEntry, e: HistoryEntry) {
|
|
269
|
+
for (const c of e.changes) {
|
|
270
|
+
const same = into.changes.find((x) => x.docId === c.docId);
|
|
271
|
+
if (same) same.after = c.after;
|
|
272
|
+
else into.changes.push(c);
|
|
273
|
+
}
|
|
274
|
+
into.selAfter = e.selAfter;
|
|
275
|
+
into.caretAfter = e.caretAfter;
|
|
276
|
+
into.time = e.time;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
private pushHistory(e: HistoryEntry) {
|
|
280
|
+
const last = this.undoStack[this.undoStack.length - 1];
|
|
281
|
+
if (e.key && last && last.key === e.key && e.time - last.time < MERGE_MS) this.mergeInto(last, e);
|
|
282
|
+
else {
|
|
283
|
+
this.undoStack.push(e);
|
|
284
|
+
if (this.undoStack.length > HISTORY_LIMIT) this.undoStack.shift();
|
|
285
|
+
}
|
|
286
|
+
this.redoStack = [];
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** Ngắt gộp: lần sửa sau thành một bước hoàn tác mới (vd sau khi di chuyển con trỏ). */
|
|
290
|
+
breakMerge() { const last = this.undoStack[this.undoStack.length - 1]; if (last) last.key = undefined; }
|
|
291
|
+
|
|
292
|
+
undo() { this.travel(this.undoStack, this.redoStack, "before"); }
|
|
293
|
+
redo() { this.travel(this.redoStack, this.undoStack, "after"); }
|
|
294
|
+
private travel(from: HistoryEntry[], to: HistoryEntry[], side: "before" | "after") {
|
|
295
|
+
const e = from.pop();
|
|
296
|
+
if (!e) return;
|
|
297
|
+
to.push(e);
|
|
298
|
+
const docs = { ...this.state.docs };
|
|
299
|
+
for (const c of e.changes) if (docs[c.docId]) docs[c.docId] = { ...docs[c.docId], blocks: side === "before" ? c.before : c.after };
|
|
300
|
+
this.state = {
|
|
301
|
+
...this.state, docs,
|
|
302
|
+
selection: pruneSelection(docs, side === "before" ? e.selBefore : e.selAfter),
|
|
303
|
+
caret: side === "before" ? e.caretBefore : e.caretAfter,
|
|
304
|
+
revision: this.state.revision + 1,
|
|
305
|
+
};
|
|
306
|
+
this.emit();
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// -------------------------------------------------------------------------
|
|
310
|
+
// Vùng chọn + con trỏ
|
|
311
|
+
// -------------------------------------------------------------------------
|
|
312
|
+
select(ids: string[], opts: { editing?: string | null } = {}) {
|
|
313
|
+
const selection: Selection = { ids, editing: opts.editing !== undefined ? opts.editing : ids.length ? null : this.state.selection.editing };
|
|
314
|
+
if (sameSel(selection, this.state.selection)) return;
|
|
315
|
+
this.set({ selection });
|
|
316
|
+
}
|
|
317
|
+
/** Khối chữ báo đang được gõ (focus). */
|
|
318
|
+
setEditing(id: string | null) {
|
|
319
|
+
const s = this.state.selection;
|
|
320
|
+
if (s.editing === id && !s.ids.length) return;
|
|
321
|
+
this.set({ selection: { ids: [], editing: id } });
|
|
322
|
+
}
|
|
323
|
+
clearSelection() { if (this.state.selection.ids.length || this.state.selection.editing || this.state.range) this.set({ selection: emptySel }); }
|
|
324
|
+
/** Shift+bấm: chọn dải khối cùng cha từ khối đang chọn tới `id`. */
|
|
325
|
+
selectRange(id: string) {
|
|
326
|
+
const anchor = this.currentIds[0];
|
|
327
|
+
if (!anchor) return this.select([id]);
|
|
328
|
+
const a = this.locate(anchor), b = this.locate(id);
|
|
329
|
+
if (!a || !b || a.docId !== b.docId) return this.select([id]);
|
|
330
|
+
// Đưa về cùng cấp: leo lên tổ tiên chung
|
|
331
|
+
const pa = [...a.ancestors, a.block.id], pb = [...b.ancestors, b.block.id];
|
|
332
|
+
let i = 0;
|
|
333
|
+
while (i < pa.length && i < pb.length && pa[i] === pb[i]) i++;
|
|
334
|
+
if (i >= pa.length || i >= pb.length) return this.select([pa[Math.min(i, pa.length) - 1] ?? id]);
|
|
335
|
+
const ia = this.locate(pa[i])!, ib = this.locate(pb[i])!;
|
|
336
|
+
const list = ia.parent ? ia.parent.content! : this.state.docs[a.docId].blocks;
|
|
337
|
+
const [lo, hi] = ia.index <= ib.index ? [ia.index, ib.index] : [ib.index, ia.index];
|
|
338
|
+
this.select(list.slice(lo, hi + 1).map((x) => x.id));
|
|
339
|
+
}
|
|
340
|
+
// -------------------------------------------------------------------------
|
|
341
|
+
// Chọn chữ qua nhiều khối
|
|
342
|
+
// -------------------------------------------------------------------------
|
|
343
|
+
/** Chọn chữ từ `anchor` tới `head` (khối chữ cùng tài liệu). Cùng một khối → chọn chữ trong khối đó. */
|
|
344
|
+
selectText(anchor: TextPoint, head: TextPoint) {
|
|
345
|
+
const a = this.locate(anchor.id), h = this.locate(head.id);
|
|
346
|
+
if (!a || !h || a.docId !== h.docId || !a.block.inline || !h.block.inline) return;
|
|
347
|
+
if (anchor.id === head.id) return this.focusText(anchor.id, Math.min(anchor.offset, head.offset), Math.max(anchor.offset, head.offset));
|
|
348
|
+
const r = this.state.range;
|
|
349
|
+
if (r && r.anchor.id === anchor.id && r.anchor.offset === anchor.offset && r.head.id === head.id && r.head.offset === head.offset) return;
|
|
350
|
+
this.set({ range: { anchor, head }, selection: emptySel, caret: null });
|
|
351
|
+
}
|
|
352
|
+
/** Dải chữ theo thứ tự tài liệu: điểm đầu / cuối, khối chữ nằm trong, khối bị bỏ trọn (giữa hai đầu). */
|
|
353
|
+
rangeInfo() {
|
|
354
|
+
const r = this.state.range;
|
|
355
|
+
if (!r) return null;
|
|
356
|
+
const loc = this.locate(r.anchor.id);
|
|
357
|
+
if (!loc) return null;
|
|
358
|
+
const blocks = this.state.docs[loc.docId].blocks;
|
|
359
|
+
const all = flatten(blocks);
|
|
360
|
+
const ia = all.findIndex((b) => b.id === r.anchor.id), ih = all.findIndex((b) => b.id === r.head.id);
|
|
361
|
+
if (ia < 0 || ih < 0) return null;
|
|
362
|
+
const [from, to] = ia <= ih ? [r.anchor, r.head] : [r.head, r.anchor];
|
|
363
|
+
const fi = Math.min(ia, ih), li = Math.max(ia, ih);
|
|
364
|
+
const first = all[fi], last = all[li];
|
|
365
|
+
const lastLoc = this.locate(last.id)!;
|
|
366
|
+
const between = all.slice(fi + 1, li).filter((b) => !lastLoc.ancestors.includes(b.id));
|
|
367
|
+
const whole = topLevelOrdered(blocks, between.map((b) => b.id));
|
|
368
|
+
const texts = all.slice(fi, li + 1).filter((b) => b.inline);
|
|
369
|
+
return { docId: loc.docId, from, to, first, last, whole, texts };
|
|
370
|
+
}
|
|
371
|
+
/** Bản sao phần đã chọn (chép / cắt): đầu, khối giữa nguyên vẹn, cuối. */
|
|
372
|
+
rangeContent(): BNode[] {
|
|
373
|
+
const info = this.rangeInfo();
|
|
374
|
+
if (!info) return [];
|
|
375
|
+
const blocks = this.state.docs[info.docId].blocks;
|
|
376
|
+
const head = { ...cloneBlock(info.first), inline: splitInline(info.first.inline!, info.from.offset)[1] };
|
|
377
|
+
const tail = { ...cloneBlock(info.last), inline: splitInline(info.last.inline!, info.to.offset)[0] };
|
|
378
|
+
return [head, ...info.whole.map((id) => cloneBlock(findBlock(blocks, id)!.block)), tail];
|
|
379
|
+
}
|
|
380
|
+
/** Xoá phần đã chọn (thay bằng `text` nếu có): nối phần còn lại của khối cuối vào khối đầu. Khối bị khoá → không làm gì. */
|
|
381
|
+
deleteRange(text = ""): boolean {
|
|
382
|
+
const info = this.rangeInfo();
|
|
383
|
+
if (!info) return false;
|
|
384
|
+
const { docId, from, to, first, last, whole } = info;
|
|
385
|
+
if (![...whole, last.id].every((id) => this.canRemove(id))) return false;
|
|
386
|
+
const blocks = this.state.docs[docId].blocks;
|
|
387
|
+
const lastLoc = this.locate(last.id)!, firstLoc = this.locate(first.id)!;
|
|
388
|
+
const keep = splitInline(first.inline!, from.offset)[0];
|
|
389
|
+
const rest = splitInline(last.inline!, to.offset)[1];
|
|
390
|
+
const typed: RichNode[] = text ? [{ type: "text", text }] : [];
|
|
391
|
+
let next = mapBlock(blocks, first.id, (b) => ({ ...b, inline: joinInline(joinInline(keep, typed), rest) }));
|
|
392
|
+
next = removeBlocks(next, [...whole, last.id]);
|
|
393
|
+
// Khối chứa khối cuối (mục danh sách, trích dẫn…) trống sau khi xoá → bỏ luôn
|
|
394
|
+
for (const anc of [...lastLoc.ancestors].reverse()) {
|
|
395
|
+
if (firstLoc.ancestors.includes(anc)) break;
|
|
396
|
+
const n = findBlock(next, anc)?.block;
|
|
397
|
+
if (!n?.content || n.content.length) break;
|
|
398
|
+
next = removeBlocks(next, [anc]);
|
|
399
|
+
}
|
|
400
|
+
const at = inlineLength(keep) + text.length;
|
|
401
|
+
this.commit(docId, next, { select: { ids: [], editing: first.id }, caret: { id: first.id, offset: at } });
|
|
402
|
+
return true;
|
|
403
|
+
}
|
|
404
|
+
/** Shift+mũi tên khi đang chọn qua nhiều khối: kéo đầu dải sang khối chữ kế (xuống: tới cuối khối, lên: tới đầu khối). */
|
|
405
|
+
extendRange(dir: -1 | 1) {
|
|
406
|
+
const r = this.state.range;
|
|
407
|
+
const loc = r && this.locate(r.head.id);
|
|
408
|
+
if (!r || !loc) return;
|
|
409
|
+
const order = flatten(this.state.docs[loc.docId].blocks).filter((b) => b.inline);
|
|
410
|
+
const i = order.findIndex((b) => b.id === r.head.id);
|
|
411
|
+
const next = order[i + dir];
|
|
412
|
+
if (!next) return this.selectText(r.anchor, { id: r.head.id, offset: dir > 0 ? inlineLength(loc.block.inline) : 0 });
|
|
413
|
+
this.selectText(r.anchor, { id: next.id, offset: dir > 0 ? inlineLength(next.inline) : 0 });
|
|
414
|
+
}
|
|
415
|
+
focusText(id: string, offset = -1, to?: number) { this.set({ caret: { id, offset, to }, selection: { ids: [], editing: id } }); }
|
|
416
|
+
consumeCaret(id: string): Caret | null {
|
|
417
|
+
const c = this.state.caret;
|
|
418
|
+
if (!c || c.id !== id) return null;
|
|
419
|
+
this.state = { ...this.state, caret: null };
|
|
420
|
+
return c;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
// -------------------------------------------------------------------------
|
|
424
|
+
// Thao tác khối
|
|
425
|
+
// -------------------------------------------------------------------------
|
|
426
|
+
private edit(blockId: string, fn: (blocks: BNode[], loc: Location) => BNode[] | null, opts: CommitOptions = {}) {
|
|
427
|
+
const loc = this.locate(blockId);
|
|
428
|
+
if (!loc || this.state.docs[loc.docId].mode === "disabled") return false;
|
|
429
|
+
const next = fn(this.state.docs[loc.docId].blocks, loc);
|
|
430
|
+
if (!next) return false;
|
|
431
|
+
this.commit(loc.docId, next, opts);
|
|
432
|
+
return true;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
setInline(id: string, inline: RichNode[], caret?: Caret) {
|
|
436
|
+
if (caret) this.lastCaret = caret;
|
|
437
|
+
this.edit(id, (blocks) => mapBlock(blocks, id, (b) => ({ ...b, inline })), { merge: `text:${id}`, structural: false });
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
setAttrs(ids: string[], attrs: Record<string, unknown>) {
|
|
441
|
+
this.batch(() => { for (const id of ids) this.edit(id, (blocks) => setAttrs(blocks, id, attrs), { merge: `attrs:${id}:${Object.keys(attrs).join(",")}`, structural: false }); });
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/** Đổi loại khối (đoạn ↔ tiêu đề…), giữ nội dung. */
|
|
445
|
+
setType(ids: string[], type: string, attrs: Record<string, unknown> = {}) {
|
|
446
|
+
ids = ids.filter((id) => !this.isContentOnly(id));
|
|
447
|
+
this.batch(() => {
|
|
448
|
+
for (const id of ids) this.edit(id, (blocks) => mapBlock(blocks, id, (b) => ({ ...b, type, attrs: { ...keepCommon(b.attrs), ...attrs } })));
|
|
449
|
+
});
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
replace(id: string, nodes: BNode[], opts: CommitOptions = {}) {
|
|
453
|
+
if (!this.canRemove(id)) return false;
|
|
454
|
+
return this.edit(id, (blocks) => mapBlock(blocks, id, () => nodes), opts);
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
insert(docId: string, parentId: string | null, index: number, nodes: BNode[], opts: { select?: boolean; focus?: boolean } = {}) {
|
|
458
|
+
const d = this.state.docs[docId];
|
|
459
|
+
if (!d || d.mode === "disabled" || !nodes.length || !this.canInsertInto(parentId)) return;
|
|
460
|
+
const first = nodes[0];
|
|
461
|
+
const focusId = opts.focus !== false ? firstText(first) : null;
|
|
462
|
+
this.commit(docId, insertBlocks(d.blocks, parentId, index, nodes), {
|
|
463
|
+
select: focusId ? { ids: [], editing: focusId } : opts.select !== false ? { ids: nodes.map((n) => n.id), editing: null } : undefined,
|
|
464
|
+
caret: focusId ? { id: focusId, offset: 0 } : null,
|
|
465
|
+
});
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/** Chèn sau khối `afterId` (cùng cha); khối rỗng là đoạn văn trống thì thay luôn đoạn đó. */
|
|
469
|
+
insertAfter(afterId: string, nodes: BNode[], opts: { replaceEmpty?: boolean; select?: boolean; focus?: boolean } = {}) {
|
|
470
|
+
const loc = this.locate(afterId);
|
|
471
|
+
if (!loc) return;
|
|
472
|
+
const target = loc.block;
|
|
473
|
+
if (opts.replaceEmpty !== false && target.type === "paragraph" && !inlineLength(target.inline) && canContain(loc.parent?.type ?? null, nodes[0].type) && this.canRemove(afterId)) {
|
|
474
|
+
const focusId = opts.focus !== false ? firstText(nodes[0]) : null;
|
|
475
|
+
this.commit(loc.docId, mapBlock(this.state.docs[loc.docId].blocks, afterId, () => nodes), {
|
|
476
|
+
select: focusId ? { ids: [], editing: focusId } : { ids: nodes.map((n) => n.id), editing: null },
|
|
477
|
+
caret: focusId ? { id: focusId, offset: 0 } : null,
|
|
478
|
+
});
|
|
479
|
+
return;
|
|
480
|
+
}
|
|
481
|
+
// Khối không đặt được ở cấp này (vd chèn nhóm sau một listItem): leo lên tới cấp đặt được
|
|
482
|
+
let at: Location & { docId: string } = loc;
|
|
483
|
+
while (at.parent && !canContain(at.parent.type, nodes[0].type)) {
|
|
484
|
+
const up = this.locate(at.parent.id);
|
|
485
|
+
if (!up) break;
|
|
486
|
+
at = up;
|
|
487
|
+
}
|
|
488
|
+
this.insert(loc.docId, at.parent?.id ?? null, at.index + 1, nodes, opts);
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
remove(ids: string[], opts: { focusNeighbor?: boolean } = {}) {
|
|
492
|
+
ids = ids.filter((id) => this.canRemove(id));
|
|
493
|
+
if (!ids.length) return;
|
|
494
|
+
const loc = this.locate(ids[0]);
|
|
495
|
+
if (!loc) return;
|
|
496
|
+
const doc = this.state.docs[loc.docId];
|
|
497
|
+
if (doc.mode === "disabled") return;
|
|
498
|
+
const ordered = topLevelOrdered(doc.blocks, ids);
|
|
499
|
+
// Sau khi xoá: con trỏ về cuối khối chữ ngay trước (hoặc đầu khối sau)
|
|
500
|
+
const order = flatten(doc.blocks).filter((b) => b.inline && !ordered.some((id) => id === b.id || this.locate(b.id)?.ancestors.includes(id)));
|
|
501
|
+
const firstIdx = flatten(doc.blocks).findIndex((b) => b.id === ordered[0]);
|
|
502
|
+
const all = flatten(doc.blocks);
|
|
503
|
+
const before = order.filter((b) => all.indexOf(b) < firstIdx).pop();
|
|
504
|
+
const after = order.find((b) => all.indexOf(b) > firstIdx);
|
|
505
|
+
const target = before ?? after;
|
|
506
|
+
const next = removeBlocks(doc.blocks, ordered);
|
|
507
|
+
this.commit(loc.docId, next, opts.focusNeighbor !== false && target
|
|
508
|
+
? { select: { ids: [], editing: target.id }, caret: { id: target.id, offset: before ? -1 : 0 } }
|
|
509
|
+
: { select: emptySel, caret: null });
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
duplicate(ids: string[]) {
|
|
513
|
+
const loc = this.locate(ids[0]);
|
|
514
|
+
if (!loc) return;
|
|
515
|
+
const doc = this.state.docs[loc.docId];
|
|
516
|
+
const ordered = topLevelOrdered(doc.blocks, ids);
|
|
517
|
+
const last = this.locate(ordered[ordered.length - 1])!;
|
|
518
|
+
if (!this.canInsertInto(last.parent?.id ?? null)) return;
|
|
519
|
+
const copies = ordered.map((id) => cloneBlock(this.locate(id)!.block));
|
|
520
|
+
this.commit(loc.docId, insertBlocks(doc.blocks, last.parent?.id ?? null, last.index + 1, copies), { select: { ids: copies.map((c) => c.id), editing: null }, caret: null });
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
/** Lên / xuống một bậc trong cùng cha. */
|
|
524
|
+
moveBy(ids: string[], dir: -1 | 1) {
|
|
525
|
+
const loc = this.locate(ids[0]);
|
|
526
|
+
if (!loc) return false;
|
|
527
|
+
const doc = this.state.docs[loc.docId];
|
|
528
|
+
const ordered = topLevelOrdered(doc.blocks, ids);
|
|
529
|
+
if (!ordered.every((id) => this.canMove(id))) return false;
|
|
530
|
+
const locs = ordered.map((id) => this.locate(id)!);
|
|
531
|
+
const parentId = locs[0].parent?.id ?? null;
|
|
532
|
+
if (locs.some((l) => (l.parent?.id ?? null) !== parentId)) return false;
|
|
533
|
+
const list = locs[0].parent ? locs[0].parent.content! : doc.blocks;
|
|
534
|
+
const lo = Math.min(...locs.map((l) => l.index)), hi = Math.max(...locs.map((l) => l.index));
|
|
535
|
+
if ((dir < 0 && lo === 0) || (dir > 0 && hi === list.length - 1)) return false;
|
|
536
|
+
const next = moveBlocks(doc.blocks, ordered, parentId, dir < 0 ? lo - 1 : hi + 2);
|
|
537
|
+
this.commit(loc.docId, next, { caret: this.state.selection.editing ? this.lastCaret : null });
|
|
538
|
+
return true;
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/** Kéo thả: di chuyển tới (parentId, index) — có thể sang tài liệu khác. */
|
|
542
|
+
moveTo(ids: string[], docId: string, parentId: string | null, index: number) {
|
|
543
|
+
const src = this.locate(ids[0]);
|
|
544
|
+
if (!src) return;
|
|
545
|
+
const target = this.state.docs[docId];
|
|
546
|
+
if (!target || target.mode === "disabled") return;
|
|
547
|
+
if (!ids.every((id) => this.canMove(id))) return;
|
|
548
|
+
// Sang khối cha khác = bỏ khỏi cha cũ + thêm vào cha mới: cần cả hai bên cho phép
|
|
549
|
+
const leaving = ids.some((id) => (this.locate(id)?.parent?.id ?? null) !== parentId || this.locate(id)?.docId !== docId);
|
|
550
|
+
if (leaving && (!this.canInsertInto(parentId) || !ids.every((id) => this.canRemove(id)))) return;
|
|
551
|
+
if (src.docId === docId) {
|
|
552
|
+
this.commit(docId, moveBlocks(target.blocks, ids, parentId, index), { select: { ids: topLevelOrdered(target.blocks, ids), editing: null }, caret: null });
|
|
553
|
+
return;
|
|
554
|
+
}
|
|
555
|
+
const srcDoc = this.state.docs[src.docId];
|
|
556
|
+
const ordered = topLevelOrdered(srcDoc.blocks, ids);
|
|
557
|
+
const nodes = ordered.map((id) => this.locate(id)!.block);
|
|
558
|
+
this.batch(() => {
|
|
559
|
+
this.commit(src.docId, removeBlocks(srcDoc.blocks, ordered));
|
|
560
|
+
this.commit(docId, insertBlocks(this.state.docs[docId].blocks, parentId, index, nodes), { select: { ids: ordered, editing: null }, caret: null });
|
|
561
|
+
});
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
/** Bọc các khối vào một khối chứa (nhóm, cột…). */
|
|
565
|
+
wrap(ids: string[], type: string, attrs: Record<string, unknown> = {}) {
|
|
566
|
+
const loc = this.locate(ids[0]);
|
|
567
|
+
if (!loc) return;
|
|
568
|
+
const doc = this.state.docs[loc.docId];
|
|
569
|
+
const ordered = topLevelOrdered(doc.blocks, ids);
|
|
570
|
+
const first = this.locate(ordered[0])!;
|
|
571
|
+
if (!ordered.every((id) => this.canRemove(id) && this.canMove(id)) || !this.canInsertInto(first.parent?.id ?? null)) return;
|
|
572
|
+
const nodes = ordered.map((id) => this.locate(id)!.block);
|
|
573
|
+
const wrapper = makeBlock(type, attrs, nodes);
|
|
574
|
+
const next = insertBlocks(removeBlocks(doc.blocks, ordered), first.parent?.id ?? null, first.index, [wrapper]);
|
|
575
|
+
this.commit(loc.docId, next, { select: { ids: [wrapper.id], editing: null }, caret: null });
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/** Bỏ vỏ: đưa con ra thay chỗ khối chứa. */
|
|
579
|
+
unwrap(id: string) {
|
|
580
|
+
if (!this.canRemove(id)) return;
|
|
581
|
+
this.edit(id, (blocks, loc) => (loc.block.content ? mapBlock(blocks, id, (b) => b.content ?? []) : null), {
|
|
582
|
+
select: { ids: this.block(id)?.content?.map((c) => c.id) ?? [], editing: null }, caret: null,
|
|
583
|
+
});
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
// -------------------------------------------------------------------------
|
|
587
|
+
// Gõ chữ: Enter, Backspace, Delete
|
|
588
|
+
// -------------------------------------------------------------------------
|
|
589
|
+
/** Enter trong khối chữ tại vị trí `offset`. */
|
|
590
|
+
splitText(id: string, offset: number, selectionEnd = offset) {
|
|
591
|
+
const loc = this.locate(id);
|
|
592
|
+
if (!loc || !loc.block.inline) return;
|
|
593
|
+
const b = loc.block;
|
|
594
|
+
const docId = loc.docId;
|
|
595
|
+
// Khối chứa bị khoá thêm khối: Enter không tạo khối mới
|
|
596
|
+
const newParent = loc.parent && (loc.parent.type === "listItem" || loc.parent.type === "taskItem") && loc.index === 0 ? this.locate(loc.parent.id)?.parent?.id ?? null : loc.parent?.id ?? null;
|
|
597
|
+
if (!this.canInsertInto(newParent)) return;
|
|
598
|
+
let inline = b.inline!;
|
|
599
|
+
if (selectionEnd > offset) inline = joinInline(splitInline(inline, offset)[0], splitInline(inline, selectionEnd)[1]);
|
|
600
|
+
const len = inlineLength(inline);
|
|
601
|
+
const item = loc.parent && (loc.parent.type === "listItem" || loc.parent.type === "taskItem") && loc.index === 0 ? this.locate(loc.parent.id) : null;
|
|
602
|
+
|
|
603
|
+
if (item) {
|
|
604
|
+
// Mục danh sách trống: thụt ra (lồng) hoặc thoát khỏi danh sách
|
|
605
|
+
if (!len && item.block.content!.length === 1) return this.outdentItem(item.block.id, true);
|
|
606
|
+
const [before, after] = splitInline(inline, offset);
|
|
607
|
+
const para = makeBlock("paragraph", {}, after);
|
|
608
|
+
const newItem = makeBlock(item.block.type, item.block.type === "taskItem" ? { checked: false } : {}, [para]);
|
|
609
|
+
const blocks = this.state.docs[docId].blocks;
|
|
610
|
+
let next = mapBlock(blocks, id, (x) => ({ ...x, inline: before }));
|
|
611
|
+
next = insertBlocks(next, item.parent!.id, item.index + 1, [newItem]);
|
|
612
|
+
this.commit(docId, next, { select: { ids: [], editing: para.id }, caret: { id: para.id, offset: 0 } });
|
|
613
|
+
return;
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
// Đoạn trống trong khối chứa (trích dẫn, nhóm) ở cuối: Enter lần nữa thì thoát ra ngoài khối chứa
|
|
617
|
+
if (!len && loc.parent && ESCAPE_CONTAINERS.has(loc.parent.type) && loc.index === loc.parent.content!.length - 1 && loc.index > 0) {
|
|
618
|
+
const parent = this.locate(loc.parent.id)!;
|
|
619
|
+
const blocks = removeBlocks(this.state.docs[docId].blocks, [id]);
|
|
620
|
+
const p = makeBlock("paragraph");
|
|
621
|
+
this.commit(docId, insertBlocks(blocks, parent.parent?.id ?? null, parent.index + 1, [p]), { select: { ids: [], editing: p.id }, caret: { id: p.id, offset: 0 } });
|
|
622
|
+
return;
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
const [before, after] = splitInline(inline, offset);
|
|
626
|
+
const atEnd = !inlineLength(after);
|
|
627
|
+
const nextType = atEnd ? SPLIT_AS[b.type] ?? "paragraph" : b.type;
|
|
628
|
+
const nextAttrs = nextType === b.type ? keepOnSplit(b.attrs) : {};
|
|
629
|
+
const created = makeBlock(nextType, nextAttrs, after);
|
|
630
|
+
let blocks = mapBlock(this.state.docs[docId].blocks, id, (x) => ({ ...x, inline: before }));
|
|
631
|
+
blocks = insertBlocks(blocks, loc.parent?.id ?? null, loc.index + 1, [created]);
|
|
632
|
+
this.commit(docId, blocks, { select: { ids: [], editing: created.id }, caret: { id: created.id, offset: 0 } });
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
/** Backspace ở đầu khối chữ. */
|
|
636
|
+
mergeBackward(id: string) {
|
|
637
|
+
const loc = this.locate(id);
|
|
638
|
+
if (!loc || !loc.block.inline) return;
|
|
639
|
+
const docId = loc.docId;
|
|
640
|
+
const blocks = this.state.docs[docId].blocks;
|
|
641
|
+
const b = loc.block;
|
|
642
|
+
// Khối không xoá được (khoá): Backspace ở đầu chỉ đưa con trỏ về khối chữ trước
|
|
643
|
+
if (!this.canRemove(id) || (loc.parent && (loc.parent.type === "listItem" || loc.parent.type === "taskItem") && loc.index === 0 && !this.canRemove(loc.parent.id))) {
|
|
644
|
+
const order = flatten(blocks).filter((x) => x.inline);
|
|
645
|
+
const prev = order[order.findIndex((x) => x.id === id) - 1];
|
|
646
|
+
if (prev) this.focusText(prev.id, -1);
|
|
647
|
+
return;
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
// Đầu mục danh sách: nối vào mục trước, hoặc (mục đầu) thụt ra
|
|
651
|
+
if (loc.parent && (loc.parent.type === "listItem" || loc.parent.type === "taskItem") && loc.index === 0) {
|
|
652
|
+
const item = this.locate(loc.parent.id)!;
|
|
653
|
+
const prevItem = item.index > 0 ? item.parent!.content![item.index - 1] : null;
|
|
654
|
+
if (!prevItem) return this.outdentItem(item.block.id, true);
|
|
655
|
+
const target = lastText(prevItem);
|
|
656
|
+
if (!target) return;
|
|
657
|
+
const at = inlineLength(target.inline);
|
|
658
|
+
let next = mapBlock(blocks, target.id, (t) => ({ ...t, inline: joinInline(t.inline ?? [], b.inline!) }));
|
|
659
|
+
const rest = item.block.content!.slice(1);
|
|
660
|
+
next = removeBlocks(next, [item.block.id]);
|
|
661
|
+
if (rest.length) next = mapBlock(next, prevItem.id, (pi) => ({ ...pi, content: [...pi.content!, ...rest] }));
|
|
662
|
+
this.commit(docId, next, { select: { ids: [], editing: target.id }, caret: { id: target.id, offset: at } });
|
|
663
|
+
return;
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
// Khối chữ khác đoạn văn, trống → đổi thành đoạn văn trước (tiêu đề trống + Backspace = đoạn văn)
|
|
667
|
+
if (b.type !== "paragraph" && !inlineLength(b.inline)) {
|
|
668
|
+
this.commit(docId, mapBlock(blocks, id, (x) => ({ ...x, type: "paragraph", attrs: keepCommon(x.attrs) })), { caret: { id, offset: 0 } });
|
|
669
|
+
return;
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
const prev = sibling(blocks, id, -1);
|
|
673
|
+
if (!prev) {
|
|
674
|
+
// Đầu khối chứa: trống và khối chứa còn khối khác → xoá; không thì đưa ra khỏi trích dẫn
|
|
675
|
+
if (loc.parent && !inlineLength(b.inline) && loc.parent.content!.length > 1) return this.remove([id]);
|
|
676
|
+
if (loc.parent && ESCAPE_CONTAINERS.has(loc.parent.type)) {
|
|
677
|
+
const parent = this.locate(loc.parent.id)!;
|
|
678
|
+
let next = removeBlocks(blocks, [id]);
|
|
679
|
+
next = insertBlocks(next, parent.parent?.id ?? null, parent.index, [b]);
|
|
680
|
+
this.commit(docId, next, { caret: { id, offset: 0 } });
|
|
681
|
+
}
|
|
682
|
+
return;
|
|
683
|
+
}
|
|
684
|
+
const target = kindOf(prev.type) === "text" ? prev : prev.content ? lastText(prev) : null;
|
|
685
|
+
if (target && target.inline) {
|
|
686
|
+
const at = inlineLength(target.inline);
|
|
687
|
+
let next = mapBlock(blocks, target.id, (t) => ({ ...t, inline: joinInline(t.inline!, b.inline!) }));
|
|
688
|
+
next = removeBlocks(next, [id]);
|
|
689
|
+
this.commit(docId, next, { select: { ids: [], editing: target.id }, caret: { id: target.id, offset: at } });
|
|
690
|
+
return;
|
|
691
|
+
}
|
|
692
|
+
// Trước là khối nguyên (ảnh…): khối hiện tại trống → xoá; rồi chọn khối nguyên đó
|
|
693
|
+
if (!inlineLength(b.inline)) this.commit(docId, removeBlocks(blocks, [id]), { select: { ids: [prev.id], editing: null }, caret: null });
|
|
694
|
+
else this.select([prev.id], { editing: null });
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
/** Delete ở cuối khối chữ. */
|
|
698
|
+
mergeForward(id: string) {
|
|
699
|
+
const loc = this.locate(id);
|
|
700
|
+
if (!loc || !loc.block.inline) return;
|
|
701
|
+
const docId = loc.docId;
|
|
702
|
+
const blocks = this.state.docs[docId].blocks;
|
|
703
|
+
const b = loc.block;
|
|
704
|
+
const order = flatten(blocks);
|
|
705
|
+
const i = order.findIndex((x) => x.id === id);
|
|
706
|
+
// Khối kế tiếp theo thứ tự tài liệu không nằm trong khối hiện tại
|
|
707
|
+
const next = order.slice(i + 1).find((x) => !this.locate(x.id)?.ancestors.includes(id));
|
|
708
|
+
if (!next) return;
|
|
709
|
+
const target = next.inline ? next : firstTextDeep(next);
|
|
710
|
+
if (target && !this.canRemove(target.id)) { this.focusText(target.id, 0); return; }
|
|
711
|
+
if (target) {
|
|
712
|
+
const at = inlineLength(b.inline);
|
|
713
|
+
let res = mapBlock(blocks, id, (x) => ({ ...x, inline: joinInline(x.inline!, target.inline!) }));
|
|
714
|
+
res = removeBlocks(res, [target.id]);
|
|
715
|
+
this.commit(docId, res, { caret: { id, offset: at } });
|
|
716
|
+
return;
|
|
717
|
+
}
|
|
718
|
+
if (!inlineLength(b.inline)) this.remove([id], { focusNeighbor: false });
|
|
719
|
+
this.select([next.id], { editing: null });
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
/** Tab trong danh sách: lồng mục vào mục trước. */
|
|
723
|
+
indentItem(itemId: string) {
|
|
724
|
+
const loc = this.locate(itemId);
|
|
725
|
+
if (!loc || !loc.parent || loc.index === 0 || !this.canMove(itemId) || !this.canRemove(itemId)) return false;
|
|
726
|
+
const prev = loc.parent.content![loc.index - 1];
|
|
727
|
+
const listType = loc.parent.type;
|
|
728
|
+
const caret = this.lastCaret;
|
|
729
|
+
let blocks = removeBlocks(this.state.docs[loc.docId].blocks, [itemId]);
|
|
730
|
+
blocks = mapBlock(blocks, prev.id, (pi) => {
|
|
731
|
+
const kids = pi.content ?? [];
|
|
732
|
+
const last = kids[kids.length - 1];
|
|
733
|
+
if (last && (last.type === "bulletList" || last.type === "orderedList" || last.type === "taskList")) {
|
|
734
|
+
return { ...pi, content: [...kids.slice(0, -1), { ...last, content: [...last.content!, loc.block] }] };
|
|
735
|
+
}
|
|
736
|
+
return { ...pi, content: [...kids, makeBlock(listType, {}, [loc.block])] };
|
|
737
|
+
});
|
|
738
|
+
this.commit(loc.docId, blocks, { caret });
|
|
739
|
+
return true;
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
/** Shift+Tab (hoặc Enter ở mục trống): đưa mục ra một cấp; ở cấp ngoài cùng thì thành đoạn văn. */
|
|
743
|
+
outdentItem(itemId: string, toParagraph = false) {
|
|
744
|
+
const loc = this.locate(itemId);
|
|
745
|
+
if (!loc || !loc.parent || !this.canMove(itemId) || !this.canRemove(itemId)) return false;
|
|
746
|
+
const list = this.locate(loc.parent.id)!;
|
|
747
|
+
const outerItem = list.parent && (list.parent.type === "listItem" || list.parent.type === "taskItem") ? this.locate(list.parent.id) : null;
|
|
748
|
+
const docId = loc.docId;
|
|
749
|
+
const firstId = loc.block.content![0].id;
|
|
750
|
+
const caret: Caret = this.lastCaret && this.lastCaret.id === firstId ? this.lastCaret : { id: firstId, offset: 0 };
|
|
751
|
+
let blocks = this.state.docs[docId].blocks;
|
|
752
|
+
// Các mục sau mục này trong cùng danh sách đi theo (thành danh sách con của nó / danh sách mới)
|
|
753
|
+
const siblingsAfter = list.block.content!.slice(loc.index + 1);
|
|
754
|
+
blocks = mapBlock(blocks, list.block.id, (l) => ({ ...l, content: l.content!.slice(0, loc.index) }));
|
|
755
|
+
if (outerItem) {
|
|
756
|
+
const moved: BNode = siblingsAfter.length ? { ...loc.block, content: [...loc.block.content!, { ...makeBlock(list.block.type, list.block.attrs, siblingsAfter) }] } : loc.block;
|
|
757
|
+
blocks = insertBlocks(blocks, outerItem.parent!.id, outerItem.index + 1, [moved]);
|
|
758
|
+
} else if (toParagraph) {
|
|
759
|
+
const tail = siblingsAfter.length ? [makeBlock(list.block.type, list.block.attrs, siblingsAfter)] : [];
|
|
760
|
+
blocks = insertBlocks(blocks, list.parent?.id ?? null, list.index + 1, [...loc.block.content!, ...tail]);
|
|
761
|
+
} else return false;
|
|
762
|
+
this.commit(docId, blocks, { select: { ids: [], editing: caret.id }, caret });
|
|
763
|
+
return true;
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
/** Khối chứa thoát ra được bằng Enter ở đoạn trống cuối / Backspace ở đầu. */
|
|
768
|
+
const ESCAPE_CONTAINERS = new Set(["blockquote", "callout", "pullquote", "details"]);
|
|
769
|
+
/** Enter ở cuối khối này tạo khối gì. */
|
|
770
|
+
const SPLIT_AS: Record<string, string> = { heading: "paragraph", codeBlock: "paragraph", preformatted: "paragraph" };
|
|
771
|
+
|
|
772
|
+
const firstText = (b: BNode): string | null => (b.inline ? b.id : b.content ? (b.content.map(firstText).find(Boolean) ?? null) : null);
|
|
773
|
+
const firstTextDeep = (b: BNode): BNode | null => {
|
|
774
|
+
if (b.inline) return b;
|
|
775
|
+
for (const c of b.content ?? []) { const t = firstTextDeep(c); if (t) return t; }
|
|
776
|
+
return null;
|
|
777
|
+
};
|
|
778
|
+
function lastText(b: BNode): BNode | null {
|
|
779
|
+
if (b.inline) return b;
|
|
780
|
+
for (let i = (b.content?.length ?? 0) - 1; i >= 0; i--) { const t = lastText(b.content![i]); if (t) return t; }
|
|
781
|
+
return null;
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
/** Thuộc tính chung giữ lại khi đổi loại khối. */
|
|
785
|
+
function keepCommon(attrs: Record<string, unknown>) {
|
|
786
|
+
const out: Record<string, unknown> = {};
|
|
787
|
+
// Khoá, gắn dữ liệu đi theo khối khi đổi loại (đổi đoạn → tiêu đề không được làm mất khoá)
|
|
788
|
+
for (const k of ["textAlign", "style", "className", "anchor", "lock", "templateLock", "bindings", "blockStyle"]) if (attrs[k] !== undefined) out[k] = attrs[k];
|
|
789
|
+
return out;
|
|
790
|
+
}
|
|
791
|
+
/** Tách khối: khối mới giữ kiểu dáng, không giữ neo (id phải duy nhất). */
|
|
792
|
+
function keepOnSplit(attrs: Record<string, unknown>) {
|
|
793
|
+
const { id: _id, anchor: _a, ...rest } = attrs;
|
|
794
|
+
return rest;
|
|
795
|
+
}
|
|
796
|
+
/** Bỏ khỏi vùng chọn những khối không còn (vừa bị xoá / gộp) — thanh công cụ, bảng cài đặt không trỏ vào khối ma. */
|
|
797
|
+
function pruneSelection(docs: Record<string, DocRecord>, sel: Selection): Selection {
|
|
798
|
+
if (!sel.ids.length && !sel.editing) return sel;
|
|
799
|
+
const exists = (id: string) => Object.values(docs).some((d) => findBlock(d.blocks, id));
|
|
800
|
+
const ids = sel.ids.filter(exists);
|
|
801
|
+
const editing = sel.editing && exists(sel.editing) ? sel.editing : null;
|
|
802
|
+
return ids.length === sel.ids.length && editing === sel.editing ? sel : { ids, editing };
|
|
803
|
+
}
|
|
804
|
+
const sameSel = (a: Selection, b: Selection) => a.editing === b.editing && a.ids.length === b.ids.length && a.ids.every((x, i) => x === b.ids[i]);
|