@ecomcx/ecomweb-editor 1.25.2 → 1.26.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 +3 -3
- package/src/locales/en/attrs.ts +1 -0
- package/src/locales/en/block-titles.ts +15 -3
- package/src/locales/en/blocks.ts +5 -0
- package/src/locales/en/controls.ts +4 -0
- package/src/locales/en/v2.ts +24 -0
- package/src/locales/vi/attrs.ts +1 -0
- package/src/locales/vi/block-titles.ts +12 -0
- package/src/locales/vi/blocks.ts +5 -0
- package/src/locales/vi/controls.ts +4 -0
- package/src/locales/vi/v2.ts +24 -0
- package/src/shared/color-swatch.tsx +4 -2
- package/src/v2/blocks/compat.tsx +3 -1
- package/src/v2/blocks/layout.tsx +6 -4
- package/src/v2/blocks/media-actions.tsx +2 -1
- package/src/v2/blocks/media.tsx +34 -1
- package/src/v2/blocks/theme.tsx +44 -4
- package/src/v2/canvas/block-list.tsx +7 -1
- package/src/v2/canvas/canvas-css.ts +33 -8
- package/src/v2/canvas/canvas.tsx +49 -4
- package/src/v2/canvas/dnd.ts +20 -0
- package/src/v2/canvas/table-select.ts +74 -0
- package/src/v2/core/host.ts +6 -1
- package/src/v2/core/media.ts +11 -0
- package/src/v2/core/tables.ts +69 -0
- package/src/v2/editor.css +14 -0
- package/src/v2/editor.tsx +1 -1
- package/src/v2/prefs.ts +10 -2
- package/src/v2/text/rich-text.tsx +2 -1
- package/src/v2/ui/ai.tsx +72 -0
- package/src/v2/ui/attr-form.tsx +7 -3
- package/src/v2/ui/color-field.tsx +7 -2
- package/src/v2/ui/inserter.tsx +36 -7
- package/src/v2/ui/list-view.tsx +7 -3
- package/src/v2/ui/options.tsx +1 -1
- package/src/v2/ui/style-tab.tsx +15 -5
- package/src/v2/ui/toolbar.tsx +51 -8
- package/src/v2/ui/unit-controls.tsx +5 -3
package/src/v2/canvas/canvas.tsx
CHANGED
|
@@ -11,6 +11,8 @@ import { applyDocumentAttrs } from "./document-attrs";
|
|
|
11
11
|
import { wrapperNodes } from "./wrapper-props";
|
|
12
12
|
import { makeBlock, type BNode } from "../core/model";
|
|
13
13
|
import { flatten, topLevelOrdered } from "../core/ops";
|
|
14
|
+
import { useTableRangeSelect } from "./table-select";
|
|
15
|
+
import { clearCells, deleteRow, selectedCellRect, tableContext } from "../core/tables";
|
|
14
16
|
import { insertSibling, now, richViews } from "../text/rich-text";
|
|
15
17
|
|
|
16
18
|
export type Device = "desktop" | "tablet" | "mobile";
|
|
@@ -31,11 +33,24 @@ const SRC_DOC = `<!doctype html><html><head><meta charset="utf-8"><meta name="vi
|
|
|
31
33
|
/** Khung soạn: iframe mang CSS của website → soạn thấy đúng phông, màu, khoảng cách; media query theo bề rộng thiết bị. */
|
|
32
34
|
/** Tỉ lệ của chế độ thu nhỏ. */
|
|
33
35
|
export const ZOOM_OUT = 0.5;
|
|
36
|
+
/** Khổ "Máy tính" luôn vẽ rộng ít nhất bằng này (> 1024 để CSS tablet của website không áp lên); chỗ hẹp hơn thì thu nhỏ vừa khung thay vì vẽ hẹp. */
|
|
37
|
+
export const DESKTOP_MIN_WIDTH = 1100;
|
|
38
|
+
/** Thu nhỏ dưới tỉ lệ này thì chữ quá nhỏ để đọc / gõ (máy thật là điện thoại, tablet dọc): vẽ đúng bề rộng khung, không thu. */
|
|
39
|
+
export const MIN_FIT = 0.6;
|
|
34
40
|
|
|
35
41
|
export function Canvas({ device = "desktop", className, contentClassName = "ecx-content", before, after }: CanvasProps) {
|
|
36
42
|
const { ui, labels } = useEditor();
|
|
37
43
|
const frameRef = useRef<HTMLIFrameElement>(null);
|
|
38
44
|
const [doc, setDoc] = useState<Document | null>(null);
|
|
45
|
+
const wrapRef = useRef<HTMLDivElement>(null);
|
|
46
|
+
const [wrapW, setWrapW] = useState(0);
|
|
47
|
+
useEffect(() => {
|
|
48
|
+
const el = wrapRef.current;
|
|
49
|
+
if (!el) return;
|
|
50
|
+
const ro = new ResizeObserver(() => setWrapW(el.clientWidth));
|
|
51
|
+
ro.observe(el); setWrapW(el.clientWidth);
|
|
52
|
+
return () => ro.disconnect();
|
|
53
|
+
}, []);
|
|
39
54
|
|
|
40
55
|
const onLoad = useCallback(() => {
|
|
41
56
|
const f = frameRef.current;
|
|
@@ -58,11 +73,13 @@ export function Canvas({ device = "desktop", className, contentClassName = "ecx-
|
|
|
58
73
|
useUiTick();
|
|
59
74
|
const width = DEVICE_WIDTH[device];
|
|
60
75
|
// Thu nhỏ: khung soạn vẽ ở cỡ gấp đôi rồi thu còn một nửa → thấy cả trang, toạ độ kéo thả / thanh công cụ tự tính theo tỉ lệ
|
|
61
|
-
const
|
|
76
|
+
const ratio = !width && wrapW > 0 && wrapW < DESKTOP_MIN_WIDTH ? wrapW / DESKTOP_MIN_WIDTH : 1;
|
|
77
|
+
const fit = ratio >= MIN_FIT ? ratio : 1;
|
|
78
|
+
const zoom = (ui.zoomOut ? ZOOM_OUT : 1) * fit;
|
|
62
79
|
const style = zoom === 1 ? { width: width ? `${width}px` : "100%" }
|
|
63
80
|
: { width: width ? `${width}px` : `${100 / zoom}%`, height: `${100 / zoom}%`, transform: `scale(${zoom})`, transformOrigin: width ? "top center" : "top left", flex: "none" };
|
|
64
81
|
return (
|
|
65
|
-
<div className={["ecx-canvas-wrap", `is-${device}`, zoom !== 1 && "is-zoomed-out", className].filter(Boolean).join(" ")}>
|
|
82
|
+
<div ref={wrapRef} className={["ecx-canvas-wrap", `is-${device}`, zoom !== 1 && "is-zoomed-out", className].filter(Boolean).join(" ")}>
|
|
66
83
|
<iframe ref={frameRef} className="ecx-canvas-frame" title={labels.canvas} srcDoc={SRC_DOC} onLoad={onLoad}
|
|
67
84
|
style={style} data-ecx-canvas="" />
|
|
68
85
|
{doc && createPortal(<CanvasWrapper><CanvasRoot doc={doc} contentClassName={contentClassName} before={before} after={after} /></CanvasWrapper>, doc.body)}
|
|
@@ -93,6 +110,7 @@ function CanvasRoot({ doc, contentClassName, before, after }: { doc: Document; c
|
|
|
93
110
|
useCanvasStyles(doc);
|
|
94
111
|
useCanvasKeys(doc);
|
|
95
112
|
useCanvasEvents(doc);
|
|
113
|
+
useTableRangeSelect(doc);
|
|
96
114
|
const hasRange = useRangeHighlight(doc);
|
|
97
115
|
return (
|
|
98
116
|
<div className={["ecx-canvas-root", contentClassName, host.canvasContentClass, focus && "is-focus-mode", spotlight && "is-spotlight", ui.zoomOut && "is-zoomed-out", hasRange && "has-text-range"].filter(Boolean).join(" ")} data-ecx-doc={activeId} tabIndex={-1}
|
|
@@ -233,14 +251,20 @@ const typing = (el: Element | null) => !!el && ((el as HTMLElement).isContentEdi
|
|
|
233
251
|
function useCanvasKeys(doc: Document) {
|
|
234
252
|
const { store, ui } = useEditor();
|
|
235
253
|
useEffect(() => {
|
|
254
|
+
// Phím gõ khi focus ở Cây khối (trang ngoài, không phải iframe): cũng chạy như trong khung soạn
|
|
255
|
+
const fromTree = (e: KeyboardEvent) => e.target instanceof Element && e.target.ownerDocument !== doc && !!e.target.closest(".ecx-listview");
|
|
236
256
|
const onKey = (e: KeyboardEvent) => {
|
|
237
257
|
// Ô gõ (ProseMirror) đã xử lý phím này
|
|
238
258
|
if (e.defaultPrevented) return;
|
|
259
|
+
const outer = fromTree(e);
|
|
239
260
|
const mod = e.metaKey || e.ctrlKey;
|
|
240
261
|
const k = e.key.toLowerCase();
|
|
262
|
+
// Vừa bấm nút trên thanh đầu (Lưu, Hoàn tác…): focus ở trang ngoài (nút Lưu tắt sau khi lưu → focus về body) — ⌘Z/⌘Y vẫn là của trình soạn
|
|
263
|
+
const fromTopbar = mod && (k === "z" || k === "y") && e.target instanceof Element && e.target.ownerDocument !== doc && !typing(e.target) && (!!e.target.closest(".ecx-topbar") || e.target === e.target.ownerDocument.body);
|
|
264
|
+
if (e.target instanceof Element && e.target.ownerDocument !== doc && !outer && !fromTopbar) return; // phím của trang ngoài ngoài Cây khối: không phải của khung soạn
|
|
241
265
|
if (mod && k === "z") { e.preventDefault(); if (e.shiftKey) store.redo(); else store.undo(); return; }
|
|
242
266
|
if (mod && k === "y") { e.preventDefault(); store.redo(); return; }
|
|
243
|
-
if (typing(doc.activeElement)) return;
|
|
267
|
+
if (typing(outer ? (e.target as Element) : doc.activeElement)) return;
|
|
244
268
|
// Phím điều hướng của trình duyệt khi không gõ chữ (Safari: ⌘← / ⌘→ = quay lại / tới trang; Backspace ở trình duyệt cũ)
|
|
245
269
|
// → chặn, không thì rời trình soạn và mất bài đang sửa
|
|
246
270
|
if ((e.metaKey || e.altKey) && (e.key === "ArrowLeft" || e.key === "ArrowRight") && !store.getState().range) { e.preventDefault(); return; }
|
|
@@ -285,6 +309,24 @@ function useCanvasKeys(doc: Document) {
|
|
|
285
309
|
}
|
|
286
310
|
if (!ids.length) return;
|
|
287
311
|
if (e.altKey && e.key === "F10") { e.preventDefault(); ui.focusToolbar(); return; }
|
|
312
|
+
// Ô / hàng của bảng: Delete xoá NỘI DUNG ô (xoá khối ô làm bảng lệch), xoá hàng bằng thao tác hàng; Esc chọn cả bảng
|
|
313
|
+
const cells = selectedCellRect(store, ids);
|
|
314
|
+
const rows = !cells && ids.every((id) => store.block(id)?.type === "tableRow") ? ids : null;
|
|
315
|
+
if (cells || rows) {
|
|
316
|
+
if (e.key === "Backspace" || e.key === "Delete") {
|
|
317
|
+
e.preventDefault();
|
|
318
|
+
if (cells) clearCells(store, cells.table, ids);
|
|
319
|
+
else store.batch(() => { for (const id of [...rows!].reverse()) { const first = store.block(id)?.content?.[0]; const ctx = first && tableContext(store, first.id); if (ctx) deleteRow(store, ctx); } });
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
if (e.key === "Escape") { e.preventDefault(); const t = cells?.table.id ?? store.locate(ids[0])?.parent?.id; if (t) store.select([t], { editing: null }); return; }
|
|
323
|
+
}
|
|
324
|
+
// Khối nằm trong ô bảng (đoạn văn trong ô sau khi thôi gõ): Esc chọn cả bảng
|
|
325
|
+
if (e.key === "Escape" && ids.length === 1) {
|
|
326
|
+
const loc = store.locate(ids[0]);
|
|
327
|
+
const table = loc && [...loc.ancestors].reverse().find((a) => store.block(a)?.type === "table");
|
|
328
|
+
if (table) { e.preventDefault(); store.select([table], { editing: null }); return; }
|
|
329
|
+
}
|
|
288
330
|
if (e.key === "Backspace" || e.key === "Delete") { e.preventDefault(); store.remove(ids); return; }
|
|
289
331
|
if (e.key === "Escape") { e.preventDefault(); store.clearSelection(); ui.openInserter(null); return; }
|
|
290
332
|
if (e.key === "Enter" && ids.length === 1) {
|
|
@@ -304,7 +346,8 @@ function useCanvasKeys(doc: Document) {
|
|
|
304
346
|
const next = order[i + dir];
|
|
305
347
|
if (!next) return;
|
|
306
348
|
if (e.shiftKey) store.selectRange(next.id); else store.select([next.id], { editing: null });
|
|
307
|
-
|
|
349
|
+
if (outer) document.querySelector<HTMLElement>(`.ecx-listview [data-block="${next.id}"]`)?.focus(); // đang ở Cây khối: giữ focus ở cây
|
|
350
|
+
else ui.blockEl(next.id)?.focus({ preventScroll: false });
|
|
308
351
|
return;
|
|
309
352
|
}
|
|
310
353
|
if (mod && e.shiftKey && k === "d") { e.preventDefault(); store.duplicate(ids); return; }
|
|
@@ -347,11 +390,13 @@ function useCanvasKeys(doc: Document) {
|
|
|
347
390
|
};
|
|
348
391
|
const cut = (e: ClipboardEvent) => onCopy(e, true);
|
|
349
392
|
doc.addEventListener("keydown", onKey);
|
|
393
|
+
document.addEventListener("keydown", onKey); // Cây khối nằm ở trang ngoài
|
|
350
394
|
doc.addEventListener("copy", onCopy as EventListener);
|
|
351
395
|
doc.addEventListener("cut", cut as EventListener);
|
|
352
396
|
doc.addEventListener("paste", onPaste as EventListener);
|
|
353
397
|
return () => {
|
|
354
398
|
doc.removeEventListener("keydown", onKey);
|
|
399
|
+
document.removeEventListener("keydown", onKey);
|
|
355
400
|
doc.removeEventListener("copy", onCopy as EventListener);
|
|
356
401
|
doc.removeEventListener("cut", cut as EventListener);
|
|
357
402
|
doc.removeEventListener("paste", onPaste as EventListener);
|
package/src/v2/canvas/dnd.ts
CHANGED
|
@@ -55,6 +55,7 @@ function begin(ctx: EditorContextValue, e: ReactPointerEvent, src: Source) {
|
|
|
55
55
|
window.removeEventListener("blur", cancel);
|
|
56
56
|
ui.canvasDoc?.removeEventListener("pointermove", move);
|
|
57
57
|
ui.canvasDoc?.removeEventListener("pointerup", up);
|
|
58
|
+
ui.canvasDoc?.removeEventListener("keydown", key, true);
|
|
58
59
|
document.body.classList.remove("is-dragging");
|
|
59
60
|
ui.canvasDoc?.body.classList.remove("is-dragging");
|
|
60
61
|
for (const id of src.ids) ui.blockEl(id)?.classList.remove("is-dragging-source");
|
|
@@ -87,6 +88,7 @@ function begin(ctx: EditorContextValue, e: ReactPointerEvent, src: Source) {
|
|
|
87
88
|
document.addEventListener("keydown", key, true);
|
|
88
89
|
ui.canvasDoc?.addEventListener("pointermove", move);
|
|
89
90
|
ui.canvasDoc?.addEventListener("pointerup", up);
|
|
91
|
+
ui.canvasDoc?.addEventListener("keydown", key, true); // focus thường nằm trong iframe khung soạn (vừa bấm khối) → Escape bắn ở đó
|
|
90
92
|
|
|
91
93
|
function autoScroll(c: EditorContextValue, y: number) {
|
|
92
94
|
const f = c.ui.canvasFrame?.getBoundingClientRect();
|
|
@@ -112,6 +114,24 @@ function toParent(ctx: EditorContextValue, ev: PointerEvent) {
|
|
|
112
114
|
|
|
113
115
|
function findTarget(ctx: EditorContextValue, x: number, y: number, src: Source): DropTarget | null {
|
|
114
116
|
const { ui, store } = ctx;
|
|
117
|
+
// Thả trên một hàng của Cây khối (trang ngoài): trước / sau khối của hàng đó, leo lên cha nếu chỗ này không nhận
|
|
118
|
+
const row = document.elementFromPoint(x, y)?.closest<HTMLElement>(".ecx-listview .ecx-list-row[data-block]");
|
|
119
|
+
if (row?.dataset.block) {
|
|
120
|
+
let id = row.dataset.block;
|
|
121
|
+
if (src.ids.some((sid) => sid === id || isInside(store, id, sid))) return null;
|
|
122
|
+
const r = row.getBoundingClientRect();
|
|
123
|
+
const after = y > r.top + r.height / 2;
|
|
124
|
+
for (let guard = 0; guard < 12; guard++) {
|
|
125
|
+
const loc = store.locate(id);
|
|
126
|
+
if (!loc) return null;
|
|
127
|
+
if (canContainAll(loc.parent?.type ?? null, src.types)) {
|
|
128
|
+
return { docId: loc.docId, parentId: loc.parent?.id ?? null, index: loc.index + (after ? 1 : 0), rect: { left: r.left, top: (after ? r.bottom : r.top) - 2, width: r.width, height: 4 }, horizontal: false };
|
|
129
|
+
}
|
|
130
|
+
if (!loc.parent) return null;
|
|
131
|
+
id = loc.parent.id;
|
|
132
|
+
}
|
|
133
|
+
return null;
|
|
134
|
+
}
|
|
115
135
|
const frame = ui.canvasFrame, doc = ui.canvasDoc;
|
|
116
136
|
if (!frame || !doc) return null;
|
|
117
137
|
const f = frame.getBoundingClientRect();
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { useEffect } from "react";
|
|
2
|
+
import { useEditor } from "../context";
|
|
3
|
+
import { cellRect, cellTable, cellsInRect } from "../core/tables";
|
|
4
|
+
|
|
5
|
+
const CELL = '[data-type="tableCell"], [data-type="tableHeader"]';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Bôi đen vùng ô của bảng như WordPress / Google Docs: kéo chuột từ ô này sang ô khác, hoặc Shift+bấm ô khác khi đang ở trong
|
|
9
|
+
* một ô của cùng bảng → chọn mọi ô trong hình chữ nhật (ô gộp được nới trọn). Chọn xong: thanh công cụ có Gộp ô / Xoá nội dung.
|
|
10
|
+
*/
|
|
11
|
+
export function useTableRangeSelect(doc: Document) {
|
|
12
|
+
const { store } = useEditor();
|
|
13
|
+
useEffect(() => {
|
|
14
|
+
let anchor: string | null = null;
|
|
15
|
+
let inRange = false;
|
|
16
|
+
const cellOf = (t: EventTarget | null) => (t instanceof (doc.defaultView as unknown as typeof globalThis).Element ? (t as Element).closest<HTMLElement>(CELL) : null);
|
|
17
|
+
const selectRange = (a: string, b: string) => {
|
|
18
|
+
const ta = cellTable(store, a), tb = cellTable(store, b);
|
|
19
|
+
if (!ta || !tb || ta.table.id !== tb.table.id) return false;
|
|
20
|
+
const rect = cellRect(ta.table, a, b);
|
|
21
|
+
if (!rect) return false;
|
|
22
|
+
(doc.activeElement as HTMLElement | null)?.blur?.();
|
|
23
|
+
doc.getSelection()?.removeAllRanges();
|
|
24
|
+
store.select(cellsInRect(ta.table, rect).map((c) => c.id), { editing: null });
|
|
25
|
+
doc.querySelector<HTMLElement>(".ecx-canvas-root")?.focus({ preventScroll: true });
|
|
26
|
+
return true;
|
|
27
|
+
};
|
|
28
|
+
/** Ô của chỗ đang gõ / đang chọn (mốc cho Shift+bấm). */
|
|
29
|
+
const currentCell = () => {
|
|
30
|
+
const s = store.getState().selection;
|
|
31
|
+
const id = s.editing ?? s.ids[0];
|
|
32
|
+
if (!id) return null;
|
|
33
|
+
const loc = store.locate(id);
|
|
34
|
+
if (!loc) return null;
|
|
35
|
+
for (const x of [id, ...[...loc.ancestors].reverse()]) if (cellTable(store, x)) return x;
|
|
36
|
+
return null;
|
|
37
|
+
};
|
|
38
|
+
const down = (e: MouseEvent) => {
|
|
39
|
+
if (e.button !== 0) return;
|
|
40
|
+
const cell = cellOf(e.target);
|
|
41
|
+
anchor = cell?.dataset.ecxBlock ?? null;
|
|
42
|
+
inRange = false;
|
|
43
|
+
head = null;
|
|
44
|
+
if (!cell || !e.shiftKey) return;
|
|
45
|
+
const from = currentCell();
|
|
46
|
+
if (from && from !== anchor && selectRange(from, anchor!)) { e.preventDefault(); e.stopPropagation(); anchor = from; }
|
|
47
|
+
};
|
|
48
|
+
let head: string | null = null;
|
|
49
|
+
const move = (e: MouseEvent) => {
|
|
50
|
+
if (!anchor) return;
|
|
51
|
+
// Lúc kéo bôi chữ, e.target vẫn là phần tử bắt đầu kéo → lấy ô dưới con trỏ
|
|
52
|
+
const cell = cellOf(doc.elementFromPoint(e.clientX, e.clientY))?.dataset.ecxBlock;
|
|
53
|
+
if (cell && (cell !== anchor || inRange) && cell !== head && selectRange(anchor, cell)) {
|
|
54
|
+
head = cell;
|
|
55
|
+
if (!inRange) { inRange = true; doc.documentElement.classList.add("ecx-cell-selecting"); }
|
|
56
|
+
}
|
|
57
|
+
if (inRange) {
|
|
58
|
+
// Đang bôi theo ô: trình duyệt không được bôi chữ song song (vệt bôi chữ nhảy qua các ô), ô gõ không đổi thành dải chữ
|
|
59
|
+
e.preventDefault();
|
|
60
|
+
e.stopPropagation();
|
|
61
|
+
doc.getSelection()?.removeAllRanges();
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
const up = (e: MouseEvent) => {
|
|
65
|
+
if (inRange) { e.stopPropagation(); doc.getSelection()?.removeAllRanges(); }
|
|
66
|
+
doc.documentElement.classList.remove("ecx-cell-selecting");
|
|
67
|
+
anchor = null; head = null; inRange = false;
|
|
68
|
+
};
|
|
69
|
+
doc.addEventListener("mousedown", down, true);
|
|
70
|
+
doc.addEventListener("mousemove", move, true);
|
|
71
|
+
doc.addEventListener("mouseup", up, true);
|
|
72
|
+
return () => { doc.removeEventListener("mousedown", down, true); doc.removeEventListener("mousemove", move, true); doc.removeEventListener("mouseup", up, true); };
|
|
73
|
+
}, [doc, store]);
|
|
74
|
+
}
|
package/src/v2/core/host.ts
CHANGED
|
@@ -52,6 +52,11 @@ export interface EditorHost {
|
|
|
52
52
|
/** Bài thật cho "Danh sách bài" theo thiết lập của khối (soạn thấy đúng bài sẽ hiện). Không có → dynamic.posts. */
|
|
53
53
|
queryPosts?(query: QueryArgs): Promise<DynamicPost[]>;
|
|
54
54
|
createPattern?(content: SavedContent): Promise<{ ref: number; synced: boolean } | null>;
|
|
55
|
+
/**
|
|
56
|
+
* Trợ lý AI (ứng dụng gọi nhà cung cấp, trình soạn chỉ gửi chữ và nhận chữ). Không có → không hiện menu AI.
|
|
57
|
+
* `task`: rewrite | shorten | expand | fix | summarize | translate | custom. Lỗi: ném Error có thông báo cho người dùng.
|
|
58
|
+
*/
|
|
59
|
+
ai?: { run(task: string, text: string, opts?: { language?: string; instruction?: string }): Promise<string> };
|
|
55
60
|
}
|
|
56
61
|
|
|
57
62
|
/** Nội dung lưu (ContentDoc của @ecomcx/ecomweb-content). */
|
|
@@ -76,7 +81,7 @@ export interface DocumentHost {
|
|
|
76
81
|
save?(ref: NestedDocRef, blocks: BNode[], content: SavedContent): Promise<void>;
|
|
77
82
|
}
|
|
78
83
|
|
|
79
|
-
export type DynamicPost = { title?: string; date?: string; author?: string; excerpt?: string; image?: string | null; terms?: string[]; comments?: number; link?: string; /** Nội dung đã lưu của bài (ContentDoc) — khối "Nội dung bài" trong template vẽ nội dung thật thay vì khung giữ chỗ. */ content?: unknown };
|
|
84
|
+
export type DynamicPost = { title?: string; date?: string; author?: string; excerpt?: string; image?: string | null; terms?: string[]; /** Chuyên mục đầu tiên (breadcrumb như website); không có = bài/trang không thuộc chuyên mục nào. */ category?: string; comments?: number; link?: string; /** Nội dung đã lưu của bài (ContentDoc) — khối "Nội dung bài" trong template vẽ nội dung thật thay vì khung giữ chỗ. */ content?: unknown };
|
|
80
85
|
|
|
81
86
|
/** Thiết lập của khối "Danh sách bài" (attrs của query). */
|
|
82
87
|
export interface QueryArgs { inherit: boolean; postType: string; perPage: number; category?: string; tag?: string; orderBy: string; order: "asc" | "desc" }
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { MediaItem } from "../../shared/types";
|
|
2
|
+
|
|
3
|
+
/** srcset (gốc + các cỡ đã tạo) và bản WebP của ảnh thư viện → trình duyệt chọn file vừa khung (điện thoại không tải ảnh gốc). Dưới 2 cỡ thì không cần. */
|
|
4
|
+
export function mediaSrcsets(m: MediaItem): { srcset?: string; webpSrcset?: string } {
|
|
5
|
+
const cands = Object.values(m.sizes ?? {}).filter((s) => s?.url && s.width > 0).map((s) => ({ w: s.width, url: s.url, webp: s.webpUrl }));
|
|
6
|
+
if (m.width && m.width > 0) cands.push({ w: m.width, url: m.url, webp: m.webpUrl });
|
|
7
|
+
const uniq = [...new Map(cands.map((c) => [c.w, c])).values()].sort((a, b) => a.w - b.w);
|
|
8
|
+
if (uniq.length < 2) return {};
|
|
9
|
+
const webp = uniq.filter((c) => c.webp);
|
|
10
|
+
return { srcset: uniq.map((c) => `${c.url} ${c.w}w`).join(", "), webpSrcset: webp.length > 1 ? webp.map((c) => `${c.webp} ${c.w}w`).join(", ") : undefined };
|
|
11
|
+
}
|
package/src/v2/core/tables.ts
CHANGED
|
@@ -192,3 +192,72 @@ export function normalizeTable(table: BNode): BNode {
|
|
|
192
192
|
for (const x of g.cells) filled += x.rs * x.cs;
|
|
193
193
|
return (table.content ?? []).length === h && filled === h * w ? table : fromGrid(table, g);
|
|
194
194
|
}
|
|
195
|
+
|
|
196
|
+
// ---------------------------------------------------------------------------
|
|
197
|
+
// Vùng ô (bôi đen nhiều ô: kéo chuột / Shift+bấm) — như chọn ô của WordPress / Google Docs
|
|
198
|
+
// ---------------------------------------------------------------------------
|
|
199
|
+
export interface CellRect { r0: number; c0: number; r1: number; c1: number }
|
|
200
|
+
|
|
201
|
+
/** Bảng chứa ô (khối tableCell / tableHeader) + id ô. */
|
|
202
|
+
export function cellTable(store: EditorStore, cellId: string): { table: BNode; docId: string } | null {
|
|
203
|
+
const cell = store.locate(cellId);
|
|
204
|
+
if (!cell || (cell.block.type !== "tableCell" && cell.block.type !== "tableHeader")) return null;
|
|
205
|
+
const row = cell.parent && store.locate(cell.parent.id);
|
|
206
|
+
return row?.parent?.type === "table" ? { table: row.parent, docId: cell.docId } : null;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** Hình chữ nhật nhỏ nhất phủ hai ô, nới ra cho tới khi không cắt ngang ô gộp nào. */
|
|
210
|
+
export function cellRect(table: BNode, aId: string, bId: string): CellRect | null {
|
|
211
|
+
const g = toGrid(table);
|
|
212
|
+
const a = g.cells.find((x) => x.node.id === aId), b = g.cells.find((x) => x.node.id === bId);
|
|
213
|
+
if (!a || !b) return null;
|
|
214
|
+
const r: CellRect = { r0: Math.min(a.r, b.r), c0: Math.min(a.c, b.c), r1: Math.max(a.r + a.rs, b.r + b.rs) - 1, c1: Math.max(a.c + a.cs, b.c + b.cs) - 1 };
|
|
215
|
+
for (let changed = true; changed;) {
|
|
216
|
+
changed = false;
|
|
217
|
+
for (const x of g.cells) {
|
|
218
|
+
const inter = x.r <= r.r1 && x.r + x.rs - 1 >= r.r0 && x.c <= r.c1 && x.c + x.cs - 1 >= r.c0;
|
|
219
|
+
if (!inter) continue;
|
|
220
|
+
const n = { r0: Math.min(r.r0, x.r), c0: Math.min(r.c0, x.c), r1: Math.max(r.r1, x.r + x.rs - 1), c1: Math.max(r.c1, x.c + x.cs - 1) };
|
|
221
|
+
if (n.r0 !== r.r0 || n.c0 !== r.c0 || n.r1 !== r.r1 || n.c1 !== r.c1) { Object.assign(r, n); changed = true; }
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
return r;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** Ô nằm trong vùng (theo thứ tự hàng rồi cột). */
|
|
228
|
+
export function cellsInRect(table: BNode, rect: CellRect): BNode[] {
|
|
229
|
+
return toGrid(table).cells.filter((x) => x.r >= rect.r0 && x.r <= rect.r1 && x.c >= rect.c0 && x.c <= rect.c1)
|
|
230
|
+
.sort((a, b) => a.r - b.r || a.c - b.c).map((x) => x.node);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** Vùng của các ô đang chọn (cùng một bảng) — null nếu không phải. */
|
|
234
|
+
export function selectedCellRect(store: EditorStore, ids: string[]): { table: BNode; docId: string; rect: CellRect } | null {
|
|
235
|
+
if (!ids.length) return null;
|
|
236
|
+
const t = cellTable(store, ids[0]);
|
|
237
|
+
if (!t || ids.some((id) => cellTable(store, id)?.table.id !== t.table.id)) return null;
|
|
238
|
+
let rect: CellRect | null = null;
|
|
239
|
+
for (const id of ids) {
|
|
240
|
+
const r = cellRect(t.table, ids[0], id);
|
|
241
|
+
if (!r) return null;
|
|
242
|
+
rect = rect ? { r0: Math.min(rect.r0, r.r0), c0: Math.min(rect.c0, r.c0), r1: Math.max(rect.r1, r.r1), c1: Math.max(rect.c1, r.c1) } : r;
|
|
243
|
+
}
|
|
244
|
+
return { ...t, rect: rect! };
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** Gộp cả vùng thành một ô (ô trên-trái giữ lại, nội dung các ô khác nối vào theo thứ tự). */
|
|
248
|
+
export function mergeRange(store: EditorStore, table: BNode, docId: string, rect: CellRect) {
|
|
249
|
+
const g = toGrid(table);
|
|
250
|
+
const inside = g.cells.filter((x) => x.r >= rect.r0 && x.r <= rect.r1 && x.c >= rect.c0 && x.c <= rect.c1).sort((a, b) => a.r - b.r || a.c - b.c);
|
|
251
|
+
if (inside.length < 2) return;
|
|
252
|
+
const [keep, ...rest] = inside;
|
|
253
|
+
const merged: GridCell = { ...keep, node: rest.reduce((n, x) => absorb(n, x.node), keep.node), rs: rect.r1 - rect.r0 + 1, cs: rect.c1 - rect.c0 + 1 };
|
|
254
|
+
g.cells = g.cells.filter((x) => !inside.includes(x)).concat(merged);
|
|
255
|
+
replaceTable(store, { table, row: 0, col: 0, docId }, fromGrid(table, g), merged.node);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** Xoá chữ trong các ô (giữ ô, mỗi ô còn một đoạn trống). */
|
|
259
|
+
export function clearCells(store: EditorStore, table: BNode, ids: string[]) {
|
|
260
|
+
const set = new Set(ids);
|
|
261
|
+
const next = { ...table, content: (table.content ?? []).map((row) => ({ ...row, content: (row.content ?? []).map((c) => (set.has(c.id) ? { ...c, content: [makeBlock("paragraph")] } : c)) })) };
|
|
262
|
+
store.replace(table.id, [next], { select: { ids: [], editing: null } });
|
|
263
|
+
}
|
package/src/v2/editor.css
CHANGED
|
@@ -302,6 +302,10 @@ body.is-dragging, body.is-dragging * { cursor: grabbing !important; user-select:
|
|
|
302
302
|
.ecx-side-icon.is-all { border-style: solid; border-color: var(--ecx-ed-muted); }
|
|
303
303
|
.ecx-side-icon.is-vertical { border-top: 2px solid var(--ecx-ed-fg); border-bottom: 2px solid var(--ecx-ed-fg); }
|
|
304
304
|
.ecx-side-icon.is-horizontal { border-left: 2px solid var(--ecx-ed-fg); border-right: 2px solid var(--ecx-ed-fg); }
|
|
305
|
+
.ecx-side-icon.is-top { border-top: 2px solid var(--ecx-ed-fg); }
|
|
306
|
+
.ecx-side-icon.is-right { border-right: 2px solid var(--ecx-ed-fg); }
|
|
307
|
+
.ecx-side-icon.is-bottom { border-bottom: 2px solid var(--ecx-ed-fg); }
|
|
308
|
+
.ecx-side-icon.is-left { border-left: 2px solid var(--ecx-ed-fg); }
|
|
305
309
|
.ecx-spacing { display: flex; flex-direction: column; gap: 8px; }
|
|
306
310
|
.ecx-spacing-head { display: flex; align-items: center; justify-content: space-between; }
|
|
307
311
|
.ecx-inherit { margin-left: 6px; font-style: normal; font-weight: 400; color: var(--ecx-ed-muted); font-size: 11px; }
|
|
@@ -322,3 +326,13 @@ body.is-dragging, body.is-dragging * { cursor: grabbing !important; user-select:
|
|
|
322
326
|
.ecx-toolbar .ecx-tool { height: 40px; min-width: 38px; }
|
|
323
327
|
.ecx-movers .ecx-tool { height: 20px; min-width: 30px; }
|
|
324
328
|
}
|
|
329
|
+
|
|
330
|
+
/* Hộp kết quả AI */
|
|
331
|
+
.ecx-ai-body { padding: 12px 16px 16px; display: flex; flex-direction: column; gap: 10px; }
|
|
332
|
+
.ecx-ai-text { max-height: 50vh; overflow: auto; padding: 10px 12px; border: 1px solid var(--ecx-ed-line); border-radius: 8px; background: var(--ecx-ed-subtle, rgba(127,127,127,.06)); font-size: 14px; line-height: 1.6; }
|
|
333
|
+
.ecx-ai-text p { margin: 0 0 .6em; } .ecx-ai-text p:last-child { margin: 0; }
|
|
334
|
+
.ecx-ai-wait { margin: 0; color: var(--ecx-ed-muted, #667085); animation: ecx-ai-pulse 1.2s ease-in-out infinite; }
|
|
335
|
+
.ecx-ai-error { margin: 0; color: #b42318; }
|
|
336
|
+
.ecx-ai-note { margin: 0; font-size: 12px; color: var(--ecx-ed-muted, #667085); }
|
|
337
|
+
@keyframes ecx-ai-pulse { 50% { opacity: .45; } }
|
|
338
|
+
@media (prefers-reduced-motion: reduce) { .ecx-ai-wait { animation: none; } }
|
package/src/v2/editor.tsx
CHANGED
|
@@ -250,7 +250,7 @@ function EditorShell({ className, onSave, header, actions, menuExtra, canvasBefo
|
|
|
250
250
|
{error && <div className="ecx-notice is-error" role="alert">{error}</div>}
|
|
251
251
|
{p.fixedToolbar && p.mode === "visual" && <div className="ecx-fixed-toolbar"><BlockToolbar placement="fixed" /></div>}
|
|
252
252
|
<div className="ecx-body">
|
|
253
|
-
{left && !p.distractionFree && <aside className="ecx-left">{left === "inserter" ? <InserterPanel /> : <ListView />}</aside>}
|
|
253
|
+
{left && !p.distractionFree && <aside className="ecx-left">{left === "inserter" ? <InserterPanel onClose={() => setLeft(null)} /> : <ListView />}</aside>}
|
|
254
254
|
<main className="ecx-main">{p.mode === "code" ? <CodeEditor /> : <Canvas device={device} before={canvasBefore} />}</main>
|
|
255
255
|
{right && !p.distractionFree && <aside className="ecx-right"><Inspector blockStyles={blockStyles} /></aside>}
|
|
256
256
|
</div>
|
package/src/v2/prefs.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { useSyncExternalStore } from "react";
|
|
1
|
+
import { useMemo, useSyncExternalStore } from "react";
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Tuỳ chọn của trình soạn — cách trình soạn hiển thị cho người đang dùng (không đổi nội dung, không đổi website).
|
|
@@ -64,6 +64,14 @@ export class PrefsStore {
|
|
|
64
64
|
countInsert(type: string) { this.set({ insertCounts: { ...this.prefs.insertCounts, [type]: (this.prefs.insertCounts[type] ?? 0) + 1 } }); }
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
+
/** Màn hình hẹp (điện thoại): thanh công cụ nổi đè lên dòng đang gõ và tràn mép → luôn ghim trên cùng (như WordPress trên điện thoại). */
|
|
68
|
+
export const NARROW_QUERY = "(max-width: 640px)";
|
|
69
|
+
const narrowMq = typeof matchMedia === "function" ? matchMedia(NARROW_QUERY) : null;
|
|
70
|
+
const subscribeNarrow = (l: () => void) => { narrowMq?.addEventListener("change", l); return () => narrowMq?.removeEventListener("change", l); };
|
|
71
|
+
const isNarrow = () => !!narrowMq?.matches;
|
|
72
|
+
|
|
67
73
|
export function usePrefs(store: PrefsStore): EditorPrefs {
|
|
68
|
-
|
|
74
|
+
const prefs = useSyncExternalStore(store.subscribe, store.get, store.get);
|
|
75
|
+
const narrow = useSyncExternalStore(subscribeNarrow, isNarrow, () => false);
|
|
76
|
+
return useMemo(() => (narrow && !prefs.fixedToolbar ? { ...prefs, fixedToolbar: true } : prefs), [prefs, narrow]);
|
|
69
77
|
}
|
|
@@ -244,7 +244,6 @@ function richKeymap(store: EditorStore, ui: EditorUi, pr: PropsRef, keepCaret: (
|
|
|
244
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
245
|
const nav = (view: EditorView, dir: -1 | 1) => !keepCaret() && focusNeighbor(store, ui, view, dir);
|
|
246
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
247
|
const slashKey = (key: string) => () => (ui.inserter?.mode === "slash" && ui.inserter.blockId === pr.current.blockId && ui.inserterKey ? ui.inserterKey(key) : false);
|
|
249
248
|
/** Lệnh dùng vùng chọn mới nhất (đọc lại từ DOM). */
|
|
250
249
|
const fresh = (cmd: (state: EditorState, dispatch: EditorView["dispatch"] | undefined, view: EditorView | undefined) => boolean) =>
|
|
@@ -252,6 +251,8 @@ function richKeymap(store: EditorStore, ui: EditorUi, pr: PropsRef, keepCaret: (
|
|
|
252
251
|
const s = syncSelection(view) ?? state;
|
|
253
252
|
return cmd(s, view ? view.dispatch.bind(view) : dispatch, view);
|
|
254
253
|
};
|
|
254
|
+
// Đọc lại vùng chọn từ DOM trước khi đổi định dạng: Shift+End rồi ⌘B ngay (<50ms) thì ProseMirror chưa kịp nhận vùng chọn → chỉ đặt storedMarks
|
|
255
|
+
const mark = (name: string) => fresh((state, dispatch) => (state.schema.marks[name] ? toggleMark(state.schema.marks[name])(state, dispatch) : false));
|
|
255
256
|
return keymap({
|
|
256
257
|
ArrowDown: (_s, _d, view) => slashKey("ArrowDown")() || (!!view && view.endOfTextblock("down") && nav(view, 1)),
|
|
257
258
|
ArrowUp: (_s, _d, view) => slashKey("ArrowUp")() || (!!view && view.endOfTextblock("up") && nav(view, -1)),
|
package/src/v2/ui/ai.tsx
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { Sparkles } from "lucide-react";
|
|
2
|
+
import { useState } from "react";
|
|
3
|
+
import { useEditor } from "../context";
|
|
4
|
+
import { inlineText, makeBlock, type BNode } from "../core/model";
|
|
5
|
+
import { Modal } from "./options";
|
|
6
|
+
import { Dropdown, MenuItem } from "./toolbar";
|
|
7
|
+
|
|
8
|
+
type Job = { task: string; label: string; language?: string; instruction?: string };
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Menu AI trên thanh công cụ của khối chữ: viết lại, rút gọn, mở rộng, sửa chính tả, tóm tắt, dịch, yêu cầu khác.
|
|
12
|
+
* Kết quả hiện trong hộp xem trước — người dùng chọn Thay thế / Chèn bên dưới / Huỷ (một bước hoàn tác).
|
|
13
|
+
*/
|
|
14
|
+
export function AiTools({ block }: { block: BNode }) {
|
|
15
|
+
const { host, labels, store } = useEditor();
|
|
16
|
+
const [job, setJob] = useState<Job | null>(null);
|
|
17
|
+
const [state, setState] = useState<{ loading: boolean; text?: string; error?: string }>({ loading: false });
|
|
18
|
+
if (!host.ai || !block.inline) return null;
|
|
19
|
+
const source = inlineText(block.inline);
|
|
20
|
+
const run = async (j: Job) => {
|
|
21
|
+
setJob(j); setState({ loading: true });
|
|
22
|
+
try { setState({ loading: false, text: await host.ai!.run(j.task, source, { language: j.language, instruction: j.instruction }) }); }
|
|
23
|
+
catch (e) { setState({ loading: false, error: (e as Error).message }); }
|
|
24
|
+
};
|
|
25
|
+
const ask = () => { const instruction = window.prompt(labels.aiCustomPrompt)?.trim(); if (instruction) void run({ task: "custom", label: labels.aiCustom, instruction }); };
|
|
26
|
+
const paragraphs = (text: string) => text.split(/\n{2,}/).map((p) => p.trim()).filter(Boolean);
|
|
27
|
+
const apply = (mode: "replace" | "below") => {
|
|
28
|
+
const parts = paragraphs(state.text ?? "");
|
|
29
|
+
if (!parts.length) return;
|
|
30
|
+
const loc = store.locate(block.id);
|
|
31
|
+
if (!loc) return;
|
|
32
|
+
store.batch(() => {
|
|
33
|
+
if (mode === "replace") {
|
|
34
|
+
store.replace(block.id, [{ ...block, inline: [{ type: "text", text: parts[0] }] }, ...parts.slice(1).map((p) => makeBlock("paragraph", {}, p))]);
|
|
35
|
+
} else {
|
|
36
|
+
store.insert(loc.docId, loc.parent?.id ?? null, loc.index + 1, parts.map((p) => makeBlock("paragraph", {}, p)));
|
|
37
|
+
}
|
|
38
|
+
});
|
|
39
|
+
setJob(null);
|
|
40
|
+
};
|
|
41
|
+
const items: Job[] = [
|
|
42
|
+
{ task: "rewrite", label: labels.aiRewrite }, { task: "shorten", label: labels.aiShorten }, { task: "expand", label: labels.aiExpand },
|
|
43
|
+
{ task: "fix", label: labels.aiFix }, { task: "summarize", label: labels.aiSummarize },
|
|
44
|
+
{ task: "translate", label: labels.aiTranslateEn, language: "English" }, { task: "translate", label: labels.aiTranslateVi, language: "Vietnamese" },
|
|
45
|
+
];
|
|
46
|
+
return (
|
|
47
|
+
<>
|
|
48
|
+
<Dropdown label={labels.ai} trigger={<Sparkles className="ecx-icon" />}>
|
|
49
|
+
{(close) => <>
|
|
50
|
+
{items.map((j) => <MenuItem key={j.label} label={j.label} onClick={() => { close(); void run(j); }} />)}
|
|
51
|
+
<MenuItem label={labels.aiCustom} onClick={() => { close(); ask(); }} />
|
|
52
|
+
</>}
|
|
53
|
+
</Dropdown>
|
|
54
|
+
{job && (
|
|
55
|
+
<Modal title={`${labels.ai}: ${job.label}`} onClose={() => setJob(null)} wide>
|
|
56
|
+
<div className="ecx-ai-body" data-ecx-ai-result>
|
|
57
|
+
{state.loading && <p className="ecx-ai-wait" role="status">{labels.aiWorking}</p>}
|
|
58
|
+
{state.error && <p className="ecx-ai-error" role="alert">{state.error}</p>}
|
|
59
|
+
{state.text && <div className="ecx-ai-text">{paragraphs(state.text).map((p, i) => <p key={i}>{p}</p>)}</div>}
|
|
60
|
+
<p className="ecx-ai-note">{labels.aiNote}</p>
|
|
61
|
+
<div className="ecx-popover-actions">
|
|
62
|
+
<button type="button" className="ecx-btn" onClick={() => setJob(null)}>{labels.cancel}</button>
|
|
63
|
+
{state.text && <button type="button" className="ecx-btn" onClick={() => apply("below")} data-ai-apply="below">{labels.aiInsertBelow}</button>}
|
|
64
|
+
{state.text && <button type="button" className="ecx-btn ecx-btn-primary" onClick={() => apply("replace")} data-ai-apply="replace">{labels.aiReplace}</button>}
|
|
65
|
+
{state.error && <button type="button" className="ecx-btn ecx-btn-primary" onClick={() => void run(job)}>{labels.aiRetry}</button>}
|
|
66
|
+
</div>
|
|
67
|
+
</div>
|
|
68
|
+
</Modal>
|
|
69
|
+
)}
|
|
70
|
+
</>
|
|
71
|
+
);
|
|
72
|
+
}
|
package/src/v2/ui/attr-form.tsx
CHANGED
|
@@ -4,8 +4,10 @@ import { useEditor } from "../context";
|
|
|
4
4
|
import type { Choice, ChoiceKind } from "../core/host";
|
|
5
5
|
import type { BlockType } from "../core/registry";
|
|
6
6
|
import { messages } from "../../i18n";
|
|
7
|
+
import { blockOptions } from "../../shared/block-defs";
|
|
7
8
|
import { DEFAULT_IMAGE_SIZES, hintOf, hintText, imageSizeLabel, optionLabel, type AttrHint } from "./attr-hints";
|
|
8
9
|
import { ColorInput } from "./color-field";
|
|
10
|
+
import { mediaSrcsets } from "../core/media";
|
|
9
11
|
|
|
10
12
|
export const cx = (...c: unknown[]) => c.filter((x): x is string => typeof x === "string" && x !== "").join(" ");
|
|
11
13
|
|
|
@@ -81,6 +83,8 @@ function ChoiceField({ hint, attrs, value, set, label }: { hint: AttrHint; attrs
|
|
|
81
83
|
export function AttrForm({ type, attrs, onChange }: { type: BlockType; attrs: Record<string, any>; onChange(a: Record<string, unknown>): void }) {
|
|
82
84
|
const { host, labels } = useEditor();
|
|
83
85
|
const lang = labels.lang;
|
|
86
|
+
// Khối plugin: nhãn "%khoá%" dịch bằng hàm dịch đăng ký cùng khối (namespace của plugin); không có thì dịch của host
|
|
87
|
+
const translate = blockOptions(type.name).translate ?? host.translate;
|
|
84
88
|
const entries = Object.entries(type.attributes ?? {})
|
|
85
89
|
.map(([k, s]) => [k, s, hintOf(type.name, k)] as const)
|
|
86
90
|
.filter(([k, s, h]) => !HIDDEN_ATTRS.has(k) && controlOf(s) !== "hidden" && h.control !== "hidden" && (!h.when || h.when(attrs)));
|
|
@@ -88,7 +92,7 @@ export function AttrForm({ type, attrs, onChange }: { type: BlockType; attrs: Re
|
|
|
88
92
|
return (
|
|
89
93
|
<div className="ecx-form">
|
|
90
94
|
{entries.map(([k, spec, hint]) => {
|
|
91
|
-
const label = hintText(hint, "label", lang) ?? attrLabel(k, spec, lang,
|
|
95
|
+
const label = hintText(hint, "label", lang) ?? attrLabel(k, spec, lang, translate);
|
|
92
96
|
const value = attrs[k] ?? spec.default;
|
|
93
97
|
const set = (v: unknown) => onChange({ [k]: v === "" || v === spec.default ? undefined : v });
|
|
94
98
|
const helpText = hintText(hint, "help", lang);
|
|
@@ -96,7 +100,7 @@ export function AttrForm({ type, attrs, onChange }: { type: BlockType; attrs: Re
|
|
|
96
100
|
const num = spec.type === "integer" || spec.type === "number";
|
|
97
101
|
const opts = (): Array<[string, string]> => hint.options
|
|
98
102
|
? hint.options.map((v) => [String(v), optionLabel(hint, v, lang)])
|
|
99
|
-
: (spec.enum ?? []).map((v, i) => [String(v), spec.enumLabels?.[i] ? (
|
|
103
|
+
: (spec.enum ?? []).map((v, i) => [String(v), spec.enumLabels?.[i] ? (translate?.(spec.enumLabels[i]) ?? spec.enumLabels[i]) : optionLabel(hint, v, lang)]);
|
|
100
104
|
const parse = (v: string) => (v === "" ? undefined : num ? Number(v) : v);
|
|
101
105
|
switch (hint.control ?? controlOf(spec)) {
|
|
102
106
|
case "checkbox":
|
|
@@ -153,7 +157,7 @@ export function AttrForm({ type, attrs, onChange }: { type: BlockType; attrs: Re
|
|
|
153
157
|
<Field key={k} label={label}>
|
|
154
158
|
<span className="ecx-color-row">
|
|
155
159
|
<input className="ecx-input" type="url" value={value == null ? "" : String(value)} onChange={(e) => set(e.target.value)} placeholder="https://…" />
|
|
156
|
-
{host.media && <button type="button" className="ecx-btn" onClick={async () => { const [m] = await host.media!.pick({ kind: "image", multiple: false }); if (m) onChange({ [k]: m.url, ...(k === "src" ? { mediaId: m.id, alt: attrs.alt ?? (m.alt || undefined) } : {}) }); }}>{labels.chooseImage}</button>}
|
|
160
|
+
{host.media && <button type="button" className="ecx-btn" onClick={async () => { const [m] = await host.media!.pick({ kind: "image", multiple: false }); if (m) onChange({ [k]: m.url, ...(k === "src" ? { mediaId: m.id, alt: attrs.alt ?? (m.alt || undefined), width: m.width ?? undefined, height: m.height ?? undefined, srcset: mediaSrcsets(m).srcset, webpSrcset: mediaSrcsets(m).webpSrcset } : {}) /* đổi ảnh thì kích thước khai báo theo ảnh mới (không giữ cỡ ảnh cũ → méo tỉ lệ / nhảy layout) */ }); }}>{labels.chooseImage}</button>}
|
|
157
161
|
</span>
|
|
158
162
|
{help}
|
|
159
163
|
</Field>
|
|
@@ -3,14 +3,19 @@ import { useEditor } from "../context";
|
|
|
3
3
|
|
|
4
4
|
const cx = (...c: unknown[]) => c.filter((x): x is string => typeof x === "string" && x !== "").join(" ");
|
|
5
5
|
|
|
6
|
+
// Theme không khai màu thì website dùng các màu mặc định này (core CSS) — vẫn cho chọn, như bản soạn cũ (shared/style-panel.tsx COLORS)
|
|
7
|
+
const DEFAULT_COLORS = { primary: "#2563eb", muted: "#6b7280", surface: "#f4f4f5", white: "#ffffff", black: "#111111" };
|
|
8
|
+
|
|
6
9
|
/** Ô màu: preset của theme + bảng chọn màu + bỏ màu. */
|
|
7
10
|
export function ColorInput({ value, onChange, label }: { value?: string; onChange(v: string | undefined): void; label: string }) {
|
|
8
11
|
const { host } = useEditor();
|
|
9
|
-
const
|
|
12
|
+
const declared = host.presets?.colors;
|
|
13
|
+
const colorMap: Record<string, string> = declared && Object.keys(declared).length ? declared : DEFAULT_COLORS;
|
|
14
|
+
const presets = Object.entries(colorMap);
|
|
10
15
|
return (
|
|
11
16
|
<div className="ecx-chip-row">
|
|
12
17
|
{presets.map(([name, c]) => <button key={name} type="button" className={cx("ecx-chip ecx-chip-swatch", value === name && "is-active")} title={name} aria-label={`${label}: ${name}`} style={{ background: c }} onClick={() => onChange(value === name ? undefined : name)} />)}
|
|
13
|
-
<ColorSwatchInput value={value} onChange={onChange} label={label} size={28} />
|
|
18
|
+
<ColorSwatchInput value={value && (colorMap[value] ?? value)} onChange={onChange} label={label} size={28} />
|
|
14
19
|
{value && <button type="button" className="ecx-chip" onClick={() => onChange(undefined)}>×</button>}
|
|
15
20
|
</div>
|
|
16
21
|
);
|