@ecomcx/ecomweb-editor 1.26.2 → 1.28.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 +6 -0
- package/src/locales/en/background.ts +22 -0
- package/src/locales/en/block-desc.ts +32 -1
- package/src/locales/en/block-titles.ts +2 -0
- package/src/locales/en/blocks.ts +17 -0
- package/src/locales/en/hints.ts +17 -0
- package/src/locales/en/index.ts +2 -1
- package/src/locales/en/pattern-lib.ts +15 -1
- package/src/locales/en/patterns.ts +6 -1
- package/src/locales/en/v2.ts +5 -0
- package/src/locales/vi/attrs.ts +6 -0
- package/src/locales/vi/background.ts +22 -0
- package/src/locales/vi/block-desc.ts +32 -1
- package/src/locales/vi/block-titles.ts +2 -0
- package/src/locales/vi/blocks.ts +17 -0
- package/src/locales/vi/hints.ts +17 -0
- package/src/locales/vi/index.ts +2 -1
- package/src/locales/vi/pattern-lib.ts +15 -1
- package/src/locales/vi/patterns.ts +6 -1
- package/src/locales/vi/v2.ts +5 -0
- package/src/shared/block-defs.ts +5 -0
- package/src/shared/panel-store.ts +65 -7
- package/src/shared/patterns-library.ts +22 -2
- package/src/shared/patterns.ts +5 -2
- package/src/v2/blocks/compat.tsx +1 -0
- package/src/v2/blocks/form.tsx +129 -0
- package/src/v2/blocks/index.ts +4 -2
- package/src/v2/canvas/block-list.tsx +3 -1
- package/src/v2/canvas/canvas.tsx +80 -7
- package/src/v2/canvas/dnd.ts +15 -2
- package/src/v2/context.tsx +6 -0
- package/src/v2/core/registry.ts +2 -1
- package/src/v2/editor.css +21 -0
- package/src/v2/editor.tsx +20 -6
- package/src/v2/index.ts +3 -3
- package/src/v2/ui/attr-hints.ts +7 -0
- package/src/v2/ui/background-panel.tsx +83 -0
- package/src/v2/ui/block-menu.ts +19 -0
- package/src/v2/ui/inserter.tsx +21 -6
- package/src/v2/ui/inspector.tsx +45 -8
- package/src/v2/ui/layout-panel.tsx +5 -5
- package/src/v2/ui/section-adder.tsx +58 -0
- package/src/v2/ui/style-supports.ts +29 -0
- package/src/v2/ui/style-tab.tsx +24 -15
- package/src/v2/ui/toolbar.tsx +123 -34
- package/src/v2/ui/unit-controls.tsx +2 -2
package/src/v2/ui/inserter.tsx
CHANGED
|
@@ -7,7 +7,7 @@ import { useEditor, useUiTick, type InserterRequest } from "../context";
|
|
|
7
7
|
import { cloneBlock, inlineLength, makeBlock, type BNode } from "../core/model";
|
|
8
8
|
import type { BlockType } from "../core/registry";
|
|
9
9
|
import { canContain } from "../core/structure";
|
|
10
|
-
import { startDragNew } from "../canvas/dnd";
|
|
10
|
+
import { startDragBlocks, startDragNew } from "../canvas/dnd";
|
|
11
11
|
import { usePrefs } from "../prefs";
|
|
12
12
|
import { onPatternsChange, patternBlocks, registeredPatterns, type Pattern } from "../core/patterns";
|
|
13
13
|
import { useSyncExternalStore } from "react";
|
|
@@ -115,6 +115,9 @@ export function InserterPopover() {
|
|
|
115
115
|
const options = useAllowed(req, useInsertOptions());
|
|
116
116
|
const [query, setQuery] = useState("");
|
|
117
117
|
const [active, setActive] = useState(0);
|
|
118
|
+
// Giữa hai section cấp trên cùng (nút "+ Thêm section"): có thêm tab Mẫu để chèn cả section tại chỗ
|
|
119
|
+
const [patternTab, setPatternTab] = useState(false);
|
|
120
|
+
useEffect(() => { setPatternTab(false); }, [req]);
|
|
118
121
|
const inputRef = useRef<HTMLInputElement>(null);
|
|
119
122
|
const listRef = useRef<HTMLDivElement>(null);
|
|
120
123
|
const q = req?.mode === "slash" ? req.query ?? "" : query;
|
|
@@ -168,7 +171,15 @@ export function InserterPopover() {
|
|
|
168
171
|
else if (e.key === "Escape") { e.preventDefault(); ui.openInserter(null); }
|
|
169
172
|
}} />
|
|
170
173
|
)}
|
|
171
|
-
{
|
|
174
|
+
{req.mode === "between" && !req.parentId && (
|
|
175
|
+
<div className="ecx-tabs" role="tablist">
|
|
176
|
+
<button type="button" role="tab" aria-selected={!patternTab} className={!patternTab ? "is-active" : undefined} onClick={() => setPatternTab(false)}>{labels.blocks}</button>
|
|
177
|
+
<button type="button" role="tab" aria-selected={patternTab} className={patternTab ? "is-active" : undefined} onClick={() => setPatternTab(true)}>{labels.patterns}</button>
|
|
178
|
+
</div>
|
|
179
|
+
)}
|
|
180
|
+
{patternTab ? (
|
|
181
|
+
<div className="ecx-inserter-list ecx-inserter-patterns"><PatternList query={query} at={req} onInserted={() => ui.openInserter(null)} /></div>
|
|
182
|
+
) : quick ? (
|
|
172
183
|
<>
|
|
173
184
|
<div className="ecx-quick-grid" role="listbox" aria-label={labels.blocks}>
|
|
174
185
|
{quick.map((o, i) => (
|
|
@@ -312,8 +323,9 @@ export function InserterPanel({ onInserted, onClose }: { onInserted?(): void; on
|
|
|
312
323
|
}
|
|
313
324
|
|
|
314
325
|
/** Mẫu (lõi, theme, plugin, người dùng tạo): bấm chèn sau khối đang chọn; mẫu đồng bộ chèn thành tham chiếu. */
|
|
315
|
-
function PatternList({ query, onInserted }: { query: string; onInserted?(): void }) {
|
|
316
|
-
const
|
|
326
|
+
function PatternList({ query, onInserted, at }: { query: string; onInserted?(): void; at?: { docId: string; parentId: string | null; index: number } }) {
|
|
327
|
+
const ctx = useEditor();
|
|
328
|
+
const { store, labels } = ctx;
|
|
317
329
|
const all = useSyncExternalStore(onPatternsChange, registeredPatterns, registeredPatterns);
|
|
318
330
|
const q = norm(query.trim());
|
|
319
331
|
const list = q ? all.filter((p) => norm(`${p.title} ${p.keywords ?? ""} ${p.category}`).includes(q)) : all;
|
|
@@ -324,8 +336,11 @@ function PatternList({ query, onInserted }: { query: string; onInserted?(): void
|
|
|
324
336
|
const nodes = patternBlocks(p);
|
|
325
337
|
if (!nodes.length) return;
|
|
326
338
|
const cur = store.currentIds[store.currentIds.length - 1];
|
|
327
|
-
if (
|
|
339
|
+
if (at) store.insert(at.docId, at.parentId, at.index, nodes, { focus: false });
|
|
340
|
+
else if (cur && store.locate(cur)) store.insertAfter(cur, nodes, { focus: false });
|
|
328
341
|
else { const docId = store.activeDocId; store.insert(docId, null, store.getState().docs[docId].blocks.length, nodes, { focus: false }); }
|
|
342
|
+
// Mẫu nhiều khối: chọn khối đầu (không chọn cả nhóm → tab Cài đặt có nội dung, không chồng nhãn)
|
|
343
|
+
if (nodes.length > 1) store.select([nodes[0].id]);
|
|
329
344
|
onInserted?.();
|
|
330
345
|
};
|
|
331
346
|
if (!list.length) return <p className="ecx-muted">{labels.noResults}</p>;
|
|
@@ -335,7 +350,7 @@ function PatternList({ query, onInserted }: { query: string; onInserted?(): void
|
|
|
335
350
|
<section key={c}>
|
|
336
351
|
<h3 className="ecx-panel-heading">{catName(c)}</h3>
|
|
337
352
|
{list.filter((p) => p.category === c).map((p) => (
|
|
338
|
-
<button key={p.name} type="button" className="ecx-pattern-card" data-pattern={p.name} onClick={() => insert(p)}>
|
|
353
|
+
<button key={p.name} type="button" className="ecx-pattern-card" data-pattern={p.name} onPointerDown={(e) => startDragBlocks(ctx, e, () => patternBlocks(p))} onClick={() => insert(p)}>
|
|
339
354
|
<strong>{p.title}</strong>{p.description && <span className="ecx-muted">{p.description}</span>}
|
|
340
355
|
</button>
|
|
341
356
|
))}
|
package/src/v2/ui/inspector.tsx
CHANGED
|
@@ -2,22 +2,27 @@ import type { Device } from "@ecomcx/ecomweb-content";
|
|
|
2
2
|
import { CORE_BLOCK_STYLES } from "@ecomcx/ecomweb-content";
|
|
3
3
|
import { Blocks } from "lucide-react";
|
|
4
4
|
import { useState, useSyncExternalStore } from "react";
|
|
5
|
-
import { blockPanelsFor, onBlockPanelsChange } from "../../shared/panel-store";
|
|
6
|
-
import { useEditor, useEditorState } from "../context";
|
|
5
|
+
import { blockPanelsFor, onBlockPanelsChange, type BlockPanel } from "../../shared/panel-store";
|
|
6
|
+
import { useEditor, useEditorState, useUiTick } from "../context";
|
|
7
7
|
import type { BNode } from "../core/model";
|
|
8
8
|
import { AttrForm, Field, attrName, cx } from "./attr-form";
|
|
9
9
|
import { BindingsPanel, CORE_BINDABLE } from "./bindings";
|
|
10
10
|
import { StyleTab } from "./style-tab";
|
|
11
|
+
import { ColorInput } from "./color-field";
|
|
12
|
+
import { UnitInput } from "./unit-controls";
|
|
11
13
|
import { useMsgs } from "../i18n";
|
|
12
14
|
|
|
13
15
|
/** Bảng cài đặt của khối đang chọn: thẻ khối, tab Cài đặt (form + phần riêng của khối), tab Kiểu dáng. */
|
|
14
16
|
export function Inspector({ blockStyles }: { blockStyles?: Record<string, Array<{ name: string; label: string }>> }) {
|
|
15
|
-
const { store, registry, labels } = useEditor();
|
|
17
|
+
const { store, registry, labels, ui } = useEditor();
|
|
18
|
+
useUiTick();
|
|
16
19
|
const t = useMsgs("controls");
|
|
17
20
|
const sel = useEditorState((s) => s.selection);
|
|
18
21
|
useEditorState((s) => s.revision);
|
|
19
22
|
const [tab, setTab] = useState<"settings" | "style">("settings");
|
|
20
|
-
|
|
23
|
+
// Khổ dùng chung với khung soạn: chọn "Điện thoại" ở đây thì khung soạn cũng thu về khổ điện thoại
|
|
24
|
+
const device: Device = ui.device === "desktop" ? "base" : ui.device;
|
|
25
|
+
const setDevice = (d: Device) => ui.setDevice(d === "base" ? "desktop" : d);
|
|
21
26
|
const ids = sel.ids.length ? sel.ids : sel.editing ? [sel.editing] : [];
|
|
22
27
|
const nodes = ids.map((id) => store.block(id)).filter(Boolean) as BNode[];
|
|
23
28
|
if (!nodes.length) return <div className="ecx-inspector is-empty"><p className="ecx-muted">{labels.noSelection}</p></div>;
|
|
@@ -60,6 +65,7 @@ export function Inspector({ blockStyles }: { blockStyles?: Record<string, Array<
|
|
|
60
65
|
<div className="ecx-panel">
|
|
61
66
|
<StyleTab type={first.type} style={first.attrs.style} onChange={(st) => setAttrs({ style: st ?? undefined })} device={device} onDeviceChange={setDevice}
|
|
62
67
|
variants={variants.length ? variants : undefined} variant={(first.attrs.blockStyle as string) ?? null} onVariantChange={(v) => setAttrs({ blockStyle: v ?? undefined })} />
|
|
68
|
+
{same && nodes.length === 1 && <PluginPanels type={first.type} attrs={first.attrs} setAttrs={setAttrs} tab="style" />}
|
|
63
69
|
</div>
|
|
64
70
|
)}
|
|
65
71
|
</>
|
|
@@ -69,19 +75,50 @@ export function Inspector({ blockStyles }: { blockStyles?: Record<string, Array<
|
|
|
69
75
|
}
|
|
70
76
|
|
|
71
77
|
/** Panel của plugin (registerBlockPanel) cho loại khối đang chọn. */
|
|
72
|
-
function PluginPanels({ type, attrs, setAttrs }: { type: string; attrs: Record<string, any>; setAttrs(a: Record<string, unknown>): void }) {
|
|
78
|
+
function PluginPanels({ type, attrs, setAttrs, tab = "block" }: { type: string; attrs: Record<string, any>; setAttrs(a: Record<string, unknown>): void; tab?: "block" | "style" }) {
|
|
73
79
|
const { host } = useEditor();
|
|
74
|
-
useSyncExternalStore(onBlockPanelsChange, () => blockPanelsFor(type).length, () => 0);
|
|
75
|
-
const panels = blockPanelsFor(type);
|
|
80
|
+
useSyncExternalStore(onBlockPanelsChange, () => blockPanelsFor(type, tab).length, () => 0);
|
|
81
|
+
const panels = blockPanelsFor(type, tab);
|
|
76
82
|
if (!panels.length) return null;
|
|
77
83
|
return (
|
|
78
84
|
<>
|
|
79
85
|
{panels.map((p) => (
|
|
80
86
|
<details key={p.id} className="ecx-advanced" open>
|
|
81
87
|
<summary>{host.translate ? host.translate(p.title) : p.title}</summary>
|
|
82
|
-
<p.component type={type} attrs={attrs} setAttrs={setAttrs} />
|
|
88
|
+
{p.component ? <p.component type={type} attrs={attrs} setAttrs={setAttrs} /> : <ControlFields panel={p} attrs={attrs} setAttrs={setAttrs} />}
|
|
83
89
|
</details>
|
|
84
90
|
))}
|
|
85
91
|
</>
|
|
86
92
|
);
|
|
87
93
|
}
|
|
94
|
+
|
|
95
|
+
/** Ô tự vẽ cho thuộc tính khai `type` của panel không có component riêng. */
|
|
96
|
+
function ControlFields({ panel, attrs, setAttrs }: { panel: BlockPanel; attrs: Record<string, any>; setAttrs(a: Record<string, unknown>): void }) {
|
|
97
|
+
const { host } = useEditor();
|
|
98
|
+
const tr = (s?: string) => (s && host.translate ? host.translate(s) : s);
|
|
99
|
+
return (
|
|
100
|
+
<>
|
|
101
|
+
{Object.entries(panel.attributes ?? {}).map(([name, spec]) => {
|
|
102
|
+
if (!("type" in spec)) return null;
|
|
103
|
+
const label = tr(spec.label) ?? name;
|
|
104
|
+
const v = attrs[name];
|
|
105
|
+
const set = (x: unknown) => setAttrs({ [name]: x === "" ? undefined : x });
|
|
106
|
+
if (spec.type === "color") return <ColorInput key={name} label={label} value={v} onChange={set} />;
|
|
107
|
+
if (spec.type === "length") return <UnitInput key={name} label={label} value={v} onChange={set} />;
|
|
108
|
+
if (spec.type === "enum") return (
|
|
109
|
+
<Field key={name} label={label}>
|
|
110
|
+
<select className="ecx-input" value={v ?? ""} onChange={(e) => set(e.target.value)}>
|
|
111
|
+
<option value="">—</option>
|
|
112
|
+
{spec.options?.map((o) => <option key={o} value={o}>{o}</option>)}
|
|
113
|
+
</select>
|
|
114
|
+
</Field>
|
|
115
|
+
);
|
|
116
|
+
return (
|
|
117
|
+
<Field key={name} label={label}>
|
|
118
|
+
<input className="ecx-input" type="number" min={spec.min} max={spec.max} value={v ?? ""} onChange={(e) => set(e.target.value === "" ? undefined : Number(e.target.value))} />
|
|
119
|
+
</Field>
|
|
120
|
+
);
|
|
121
|
+
})}
|
|
122
|
+
</>
|
|
123
|
+
);
|
|
124
|
+
}
|
|
@@ -21,7 +21,7 @@ export function layoutFor(kind: Kind, prev?: BlockLayout): BlockLayout | undefin
|
|
|
21
21
|
return { type: "flex", direction: { base: kind === "stack" ? "column" : "row" }, ...(prev?.justify ? { justify: prev.justify } : {}), ...(prev?.align ? { align: prev.align } : {}) };
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
-
export function LayoutEffectsPanel({ type, style: raw, onChange, device }: { type: string; style: unknown; onChange(style: BlockStyle | null): void; device: Device }) {
|
|
24
|
+
export function LayoutEffectsPanel({ type, style: raw, onChange, device, effects = true, hover = true }: { type: string; style: unknown; onChange(style: BlockStyle | null): void; device: Device; effects?: boolean; hover?: boolean }) {
|
|
25
25
|
const { labels, host } = useEditor();
|
|
26
26
|
const t = useMsgs("layout");
|
|
27
27
|
const style: BlockStyle = normalizeStyle(raw) ?? {};
|
|
@@ -92,7 +92,7 @@ export function LayoutEffectsPanel({ type, style: raw, onChange, device }: { typ
|
|
|
92
92
|
</Section>
|
|
93
93
|
)}
|
|
94
94
|
|
|
95
|
-
<Section title={t.effects} defaultOpen={!!(style.gradient || style.shadow || style.aspectRatio || style.position)}>
|
|
95
|
+
{effects && <Section title={t.effects} defaultOpen={!!(style.gradient || style.shadow || style.aspectRatio || style.position)}>
|
|
96
96
|
<Row label={t.gradient}>
|
|
97
97
|
<div className="ecx-chip-row">
|
|
98
98
|
<button type="button" className={cx("ecx-chip", !style.gradient && "is-active")} onClick={() => set({ gradient: undefined })}>{t.none}</button>
|
|
@@ -124,9 +124,9 @@ export function LayoutEffectsPanel({ type, style: raw, onChange, device }: { typ
|
|
|
124
124
|
</select>
|
|
125
125
|
</Row>
|
|
126
126
|
<label className="ecx-check"><input type="checkbox" checked={!!style.position} onChange={(e) => set({ position: e.target.checked ? { type: "sticky" } : undefined })} /> {t.sticky}</label>
|
|
127
|
-
</Section>
|
|
127
|
+
</Section>}
|
|
128
128
|
|
|
129
|
-
<Section title={t.hover} defaultOpen={!!style.hover}>
|
|
129
|
+
{hover && <Section title={t.hover} defaultOpen={!!style.hover}>
|
|
130
130
|
{(["text", "background"] as const).map((k) => (
|
|
131
131
|
<Row key={k} label={t[k]}>
|
|
132
132
|
<ColorInput label={t[k]} value={style.hover?.color?.[k]} onChange={(v) => set({ hover: { ...style.hover, color: { ...style.hover?.color, [k]: v } } })} />
|
|
@@ -141,7 +141,7 @@ export function LayoutEffectsPanel({ type, style: raw, onChange, device }: { typ
|
|
|
141
141
|
</select>
|
|
142
142
|
</Row>
|
|
143
143
|
<label className="ecx-check"><input type="checkbox" checked={!!style.hover?.lift} onChange={(e) => set({ hover: { ...style.hover, lift: e.target.checked || undefined } })} /> {t.lift}</label>
|
|
144
|
-
</Section>
|
|
144
|
+
</Section>}
|
|
145
145
|
</div>
|
|
146
146
|
);
|
|
147
147
|
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { Plus } from "lucide-react";
|
|
2
|
+
import { useEffect, useState } from "react";
|
|
3
|
+
import { useEditor, useUiTick } from "../context";
|
|
4
|
+
|
|
5
|
+
/** Khoảng (px) quanh ranh giới hai section mà rê chuột vào thì hiện nút. */
|
|
6
|
+
const ZONE = 14;
|
|
7
|
+
|
|
8
|
+
/** Chỉ số chèn khi con trỏ ở gần ranh giới giữa các khối cấp trên cùng (trên khối đầu, giữa hai khối, dưới khối cuối); xa ranh giới → null. */
|
|
9
|
+
export function boundaryAt(rects: Array<{ top: number; bottom: number }>, y: number, zone = ZONE): { index: number; y: number } | null {
|
|
10
|
+
for (let i = 0; i <= rects.length; i++) {
|
|
11
|
+
const edge = i === 0 ? rects[0]?.top : i === rects.length ? rects[i - 1].bottom : (rects[i - 1].bottom + rects[i].top) / 2;
|
|
12
|
+
if (edge !== undefined && Math.abs(y - edge) <= zone) return { index: i, y: edge };
|
|
13
|
+
}
|
|
14
|
+
return null;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Nút "+ Thêm section" (như Elementor): rê chuột tới ranh giới giữa hai section cấp trên cùng của tài liệu đang soạn → hiện nút giữa khung;
|
|
19
|
+
* bấm mở popover chèn tại đúng chỗ đó (tab Khối / Mẫu).
|
|
20
|
+
*/
|
|
21
|
+
export function SectionAdder() {
|
|
22
|
+
const { ui, store, labels } = useEditor();
|
|
23
|
+
useUiTick();
|
|
24
|
+
const [spot, setSpot] = useState<{ index: number; x: number; y: number; left: number } | null>(null);
|
|
25
|
+
const doc = ui.canvasDoc;
|
|
26
|
+
useEffect(() => {
|
|
27
|
+
if (!doc) return;
|
|
28
|
+
const move = (e: MouseEvent) => {
|
|
29
|
+
if (ui.drag || ui.zoomOut || ui.inserter) return setSpot(null);
|
|
30
|
+
const docId = store.activeDocId;
|
|
31
|
+
const d = store.getState().docs[docId];
|
|
32
|
+
if (!d || d.mode !== "default" || !d.blocks.length) return setSpot(null);
|
|
33
|
+
const rects = d.blocks.map((b) => ui.blockRect(b.id)).filter((r): r is DOMRect => !!r);
|
|
34
|
+
const f = ui.canvasFrame?.getBoundingClientRect();
|
|
35
|
+
if (!f || rects.length !== d.blocks.length) return setSpot(null);
|
|
36
|
+
const scale = f.width / (ui.canvasFrame!.offsetWidth || f.width) || 1;
|
|
37
|
+
const y = f.top + e.clientY * scale;
|
|
38
|
+
const hit = boundaryAt(rects, y);
|
|
39
|
+
setSpot(hit ? { index: hit.index, y: hit.y, x: f.left + f.width / 2, left: f.left } : null);
|
|
40
|
+
};
|
|
41
|
+
// Không ẩn khi chuột rời khung soạn: nút nằm ở trang ngoài, rời khung để bấm nút là chuyện bình thường
|
|
42
|
+
const leave = () => setSpot(null);
|
|
43
|
+
doc.addEventListener("mousemove", move);
|
|
44
|
+
doc.addEventListener("scroll", leave);
|
|
45
|
+
return () => { doc.removeEventListener("mousemove", move); doc.removeEventListener("scroll", leave); };
|
|
46
|
+
}, [doc, ui, store]);
|
|
47
|
+
if (!spot || ui.drag || ui.inserter) return null;
|
|
48
|
+
return (
|
|
49
|
+
<button type="button" className="ecx-section-adder" style={{ top: Math.round(spot.y - 14), left: Math.round(spot.x - 14) }} aria-label={labels.addSection} title={labels.addSection}
|
|
50
|
+
onMouseDown={(e) => e.preventDefault()}
|
|
51
|
+
onClick={() => {
|
|
52
|
+
ui.openInserter({ mode: "between", docId: store.activeDocId, parentId: null, index: spot.index, rect: { left: Math.max(spot.left + 8, spot.x - 160), top: spot.y, bottom: spot.y + 14 } });
|
|
53
|
+
setSpot(null);
|
|
54
|
+
}}>
|
|
55
|
+
<Plus className="ecx-icon" />
|
|
56
|
+
</button>
|
|
57
|
+
);
|
|
58
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { BlockType } from "../core/registry";
|
|
2
|
+
|
|
3
|
+
/** Nhóm của tab Kiểu dáng. Khối chỉ hiện nhóm nó hỗ trợ (như `supports` trong block.json của WordPress). */
|
|
4
|
+
export type StyleGroup = "typography" | "color" | "background" | "spacing" | "border" | "effects" | "hover" | "motion" | "visibility";
|
|
5
|
+
|
|
6
|
+
export const STYLE_GROUPS: readonly StyleGroup[] = ["typography", "color", "background", "spacing", "border", "effects", "hover", "motion", "visibility"];
|
|
7
|
+
const NO_BACKGROUND = STYLE_GROUPS.filter((g) => g !== "background");
|
|
8
|
+
const MEDIA: StyleGroup[] = ["spacing", "border", "effects", "hover", "motion", "visibility"];
|
|
9
|
+
const MINIMAL: StyleGroup[] = ["spacing", "visibility"];
|
|
10
|
+
|
|
11
|
+
/** Khối lõi có bộ nhóm riêng; khối khác: khối chứa có đủ (kể cả ảnh nền), khối còn lại có mọi nhóm trừ ảnh nền. */
|
|
12
|
+
const CORE: Record<string, StyleGroup[]> = {
|
|
13
|
+
spacer: MINIMAL, pageBreak: ["visibility"], customHtml: MINIMAL, shortcode: MINIMAL, audio: MINIMAL,
|
|
14
|
+
horizontalRule: ["color", "spacing", "border", "visibility"],
|
|
15
|
+
image: MEDIA, gallery: MEDIA, video: MEDIA, youtube: MEDIA, embed: MEDIA, featuredImage: MEDIA, siteLogo: MEDIA, avatar: MEDIA,
|
|
16
|
+
icon: ["color", "spacing", "motion", "visibility"],
|
|
17
|
+
socialLinks: ["color", "spacing", "motion", "visibility"],
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Nhóm kiểu dáng của một loại khối. Khối plugin khai `supports.style` là mảng nhóm để chọn; `true` / không khai = mặc định như trên.
|
|
22
|
+
* Nhóm khối đã có giá trị vẫn hiện (để sửa / xoá) dù không nằm trong danh sách — xem StyleTab.
|
|
23
|
+
*/
|
|
24
|
+
export function styleGroups(name: string, type?: BlockType): Set<StyleGroup> {
|
|
25
|
+
const s = type?.supports?.style;
|
|
26
|
+
if (Array.isArray(s)) return new Set(s.filter((g): g is StyleGroup => STYLE_GROUPS.includes(g as StyleGroup)));
|
|
27
|
+
if (CORE[name]) return new Set(CORE[name]);
|
|
28
|
+
return new Set(type?.kind === "container" ? STYLE_GROUPS : NO_BACKGROUND);
|
|
29
|
+
}
|
package/src/v2/ui/style-tab.tsx
CHANGED
|
@@ -3,10 +3,12 @@ import { AlignCenter, AlignJustify, AlignLeft, AlignRight, Monitor, Smartphone,
|
|
|
3
3
|
import { useEffect, useState, type ReactNode } from "react";
|
|
4
4
|
import { labelsLegacy, type EditorLabels } from "../../shared/labels";
|
|
5
5
|
import { useEditor } from "../context";
|
|
6
|
+
import { BackgroundPanel } from "./background-panel";
|
|
6
7
|
import { ColorInput } from "./color-field";
|
|
7
8
|
import { LayoutEffectsPanel } from "./layout-panel";
|
|
8
9
|
import { MotionPanel } from "./motion-panel";
|
|
9
10
|
import { Section, Seg, cx } from "./style-controls";
|
|
11
|
+
import { styleGroups, type StyleGroup } from "./style-supports";
|
|
10
12
|
import { SpacingControl, UnitInput } from "./unit-controls";
|
|
11
13
|
import { useMsgs } from "../i18n";
|
|
12
14
|
|
|
@@ -43,7 +45,7 @@ export function StyleTab({ type, style: raw, onChange, device, onDeviceChange, v
|
|
|
43
45
|
type: string; style: unknown; onChange(style: BlockStyle | null): void; device: Device; onDeviceChange(d: Device): void;
|
|
44
46
|
variants?: Array<{ name: string; label: string }>; variant?: string | null; onVariantChange?(v: string | null): void;
|
|
45
47
|
}) {
|
|
46
|
-
const { host, labels } = useEditor();
|
|
48
|
+
const { host, labels, registry } = useEditor();
|
|
47
49
|
const t = labelsLegacy(labels.lang);
|
|
48
50
|
const ct = useMsgs("controls");
|
|
49
51
|
const presets = host.presets;
|
|
@@ -86,6 +88,9 @@ export function StyleTab({ type, style: raw, onChange, device, onDeviceChange, v
|
|
|
86
88
|
const row = (k: string, label: string, control: ReactNode) => (
|
|
87
89
|
<div className="ecx-style-row" key={k}><span className="ecx-field-label">{label}{tag(k)}</span>{control}</div>
|
|
88
90
|
);
|
|
91
|
+
// Nhóm khối hỗ trợ; nhóm đã có giá trị vẫn hiện để sửa / xoá (dữ liệu cũ, khối dán từ nơi khác)
|
|
92
|
+
const groups = styleGroups(type, registry.get(type));
|
|
93
|
+
const show = (g: StyleGroup, keys: string[]) => groups.has(g) || keys.some((k) => style[k] !== undefined);
|
|
89
94
|
const appearance = `${style.fontWeight ?? ""}${style.fontStyle === "italic" ? "i" : ""}`;
|
|
90
95
|
|
|
91
96
|
return (
|
|
@@ -108,7 +113,7 @@ export function StyleTab({ type, style: raw, onChange, device, onDeviceChange, v
|
|
|
108
113
|
</div>
|
|
109
114
|
)}
|
|
110
115
|
|
|
111
|
-
<Section title={t.style_typography} modified={has(TYPO)} onReset={() => reset(TYPO)} moreOpen={has(["fontFamily", "letterSpacing", "textDecoration", "textTransform"])}
|
|
116
|
+
{show("typography", TYPO) && <Section title={t.style_typography} modified={has(TYPO)} onReset={() => reset(TYPO)} moreOpen={has(["fontFamily", "letterSpacing", "textDecoration", "textTransform"])}
|
|
112
117
|
more={<>
|
|
113
118
|
{row("fontFamily", t.style_fontFamily,
|
|
114
119
|
<select className="ecx-input" value={style.fontFamily ?? ""} aria-label={t.style_fontFamily} onChange={(e) => set("fontFamily", e.target.value || undefined)}>
|
|
@@ -122,8 +127,9 @@ export function StyleTab({ type, style: raw, onChange, device, onDeviceChange, v
|
|
|
122
127
|
options={[["none", "—", t.none], ["uppercase", "AB", t.upper], ["lowercase", "ab", t.lower], ["capitalize", "Ab", t.capitalize]]} />)}
|
|
123
128
|
</>}>
|
|
124
129
|
{row("fontSize", t.style_fontSize, <>
|
|
125
|
-
<Seg label={t.style_fontSize} value={get("fontSize")} onChange={(v) => set("fontSize", v)} options={sizes.map((v) => [v, v.toUpperCase(), v] as [string, string, string])} />
|
|
126
|
-
|
|
130
|
+
<Seg label={t.style_fontSize} value={get("fontSize")} onChange={(v) => set("fontSize", v)} options={sizes.map((v) => [v, v.toUpperCase(), presets?.fontSizes?.[v] ? `${v} · ${presets.fontSizes[v]}` : v] as [string, string, string])} />
|
|
131
|
+
{/* Cỡ tuỳ chỉnh: ô số + đơn vị + thanh kéo (preset chọn ở hàng trên; giá trị clamp() cũ hiện làm gợi ý) */}
|
|
132
|
+
<UnitInput label={`${t.style_fontSize}: ${t.custom}`} value={sizes.includes(get("fontSize")) ? undefined : get("fontSize")} placeholder={inherited("fontSize") ?? "18px"} units={["px", "rem", "em"]} max={96} onChange={(v) => set("fontSize", v)} />
|
|
127
133
|
</>)}
|
|
128
134
|
{row("appearance", t.style_appearance,
|
|
129
135
|
<select className="ecx-input" value={appearance} aria-label={t.style_appearance} onChange={(e) => {
|
|
@@ -136,38 +142,41 @@ export function StyleTab({ type, style: raw, onChange, device, onDeviceChange, v
|
|
|
136
142
|
{row("lineHeight", t.style_lineHeight, <ValueInput label={t.style_lineHeight} value={get("lineHeight")} inherited={inherited("lineHeight")} check={ok("lineHeight")} placeholder="1.5" onCommit={(v) => set("lineHeight", v == null ? undefined : Number(v))} />)}
|
|
137
143
|
{row("textAlign", t.textAlign, <Seg label={t.textAlign} value={get("textAlign")} onChange={(v) => set("textAlign", v)}
|
|
138
144
|
options={[["left", AlignLeft, t.alignLeft], ["center", AlignCenter, t.alignCenter], ["right", AlignRight, t.alignRight], ["justify", AlignJustify, t.alignJustify]]} />)}
|
|
139
|
-
</Section>
|
|
145
|
+
</Section>}
|
|
140
146
|
|
|
141
|
-
<Section title={t.style_color} modified={has(["color"])} onReset={() => reset(["color"])}>
|
|
147
|
+
{show("color", ["color"]) && <Section title={t.style_color} modified={has(["color"])} onReset={() => reset(["color"])}>
|
|
142
148
|
{row("text", t.style_text, <ColorInput label={t.style_text} value={style.color?.text} onChange={(v) => setGroup("color", "text", v)} />)}
|
|
143
149
|
{row("background", t.style_background, <ColorInput label={t.style_background} value={style.color?.background} onChange={(v) => setGroup("color", "background", v)} />)}
|
|
144
|
-
</Section>
|
|
150
|
+
</Section>}
|
|
145
151
|
|
|
146
|
-
<
|
|
152
|
+
{show("background", ["background"]) && <BackgroundPanel style={raw} onChange={onChange} device={device} />}
|
|
153
|
+
|
|
154
|
+
{show("spacing", SPACING) && <Section title={t.style_spacing} modified={has(SPACING)} onReset={() => reset(SPACING)} moreOpen={has(["gap", "width", "maxWidth", "minHeight"])}
|
|
147
155
|
more={<>{(["gap", "width", "maxWidth", "minHeight"] as const).map((k) =>
|
|
148
156
|
row(k, t[`style_${k}`], <ValueInput label={t[`style_${k}`]} value={get(k)} inherited={inherited(k)} check={ok(k)} placeholder={k === "gap" ? "md, 24px" : "100%, 640px, 60vh"} onCommit={(v) => set(k, v)} />))}</>}>
|
|
149
157
|
<SpacingControl label={t.style_padding} steps={spaces} value={get("padding")} inherited={inherited("padding")} onChange={(v) => set("padding", v)} labels={{ vertical: ct.vertical, horizontal: ct.horizontal, top: ct.sideTop, right: ct.sideRight, bottom: ct.sideBottom, left: ct.sideLeft, link: t.linkSides, unlink: t.unlinkSides }} />
|
|
150
158
|
<SpacingControl label={t.style_margin} steps={spaces} value={get("margin")} inherited={inherited("margin")} onChange={(v) => set("margin", v)} labels={{ vertical: ct.vertical, horizontal: ct.horizontal, top: ct.sideTop, right: ct.sideRight, bottom: ct.sideBottom, left: ct.sideLeft, link: t.linkSides, unlink: t.unlinkSides }} />
|
|
151
|
-
</Section>
|
|
159
|
+
</Section>}
|
|
152
160
|
|
|
153
|
-
<Section title={t.style_border} modified={has(["border", "radius"])} onReset={() => reset(["border", "radius"])} defaultOpen={has(["border", "radius"])}>
|
|
161
|
+
{show("border", ["border", "radius"]) && <Section title={t.style_border} modified={has(["border", "radius"])} onReset={() => reset(["border", "radius"])} defaultOpen={has(["border", "radius"])}>
|
|
154
162
|
{row("borderWidth", t.style_borderWidth, <UnitInput label={t.style_borderWidth} value={style.border?.width} max={20} units={["px", "em", "rem"]} onChange={(v) => setGroup("border", "width", v)} />)}
|
|
155
163
|
{row("borderStyle", t.style_borderStyle, <Seg label={t.style_borderStyle} value={style.border?.style} onChange={(v) => setGroup("border", "style", v)}
|
|
156
164
|
options={[["solid", "—", t.border_solid], ["dashed", "- -", t.border_dashed], ["dotted", "···", t.border_dotted]]} />)}
|
|
157
165
|
{row("borderColor", t.style_borderColor, <ColorInput label={t.style_borderColor} value={style.border?.color} onChange={(v) => setGroup("border", "color", v)} />)}
|
|
158
166
|
{row("radius", t.style_radius, <UnitInput label={t.style_radius} value={typeof style.radius === "string" ? style.radius : undefined} max={60} units={["px", "%", "em", "rem"]} onChange={(v) => set("radius", v)} />)}
|
|
159
|
-
</Section>
|
|
167
|
+
</Section>}
|
|
160
168
|
|
|
161
|
-
<LayoutEffectsPanel type={type} style={raw} onChange={onChange} device={device}
|
|
169
|
+
<LayoutEffectsPanel type={type} style={raw} onChange={onChange} device={device}
|
|
170
|
+
effects={show("effects", ["gradient", "shadow", "aspectRatio", "position"])} hover={show("hover", ["hover"])} />
|
|
162
171
|
|
|
163
|
-
<MotionPanel type={type} style={raw} onChange={onChange} />
|
|
172
|
+
{show("motion", ["motion"]) && <MotionPanel type={type} style={raw} onChange={onChange} />}
|
|
164
173
|
|
|
165
|
-
<Section title={t.style_visibility} modified={has(["hide"])} onReset={() => reset(["hide"])} defaultOpen={has(["hide"])}>
|
|
174
|
+
{show("visibility", ["hide"]) && <Section title={t.style_visibility} modified={has(["hide"])} onReset={() => reset(["hide"])} defaultOpen={has(["hide"])}>
|
|
166
175
|
{(["desktop", "tablet", "mobile"] as const).map((d) => (
|
|
167
176
|
<label key={d} className="ecx-check"><input type="checkbox" checked={!!style.hide?.includes(d)}
|
|
168
177
|
onChange={(e) => set("hide", e.target.checked ? [...(style.hide ?? []), d] : (style.hide ?? []).filter((x) => x !== d))} /> {t[`hide_${d}`]}</label>
|
|
169
178
|
))}
|
|
170
|
-
</Section>
|
|
179
|
+
</Section>}
|
|
171
180
|
</div>
|
|
172
181
|
);
|
|
173
182
|
}
|
package/src/v2/ui/toolbar.tsx
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { WIDE_BLOCKS } from "@ecomcx/ecomweb-content";
|
|
2
2
|
import { clearCells, mergeRange, selectedCellRect } from "../core/tables";
|
|
3
3
|
import { AiTools } from "./ai";
|
|
4
|
-
import { Eraser, TableCellsMerge, StickyNote, Keyboard, MoveHorizontal, Maximize2, RectangleHorizontal, AlignCenter, AlignLeft, AlignRight, ArrowUpLeft, Bold, ChevronDown, ChevronUp, Code, Copy, CopyPlus, GripVertical, IndentDecrease, IndentIncrease, Italic, Link2, Link2Off, MoreVertical, PanelTop, Strikethrough, Trash2, Underline, Ungroup, Group as GroupIcon, Blocks, ArrowUpToLine, ArrowDownToLine, Shapes, Lock, Subscript, Superscript, Highlighter } from "lucide-react";
|
|
4
|
+
import { Eraser, TableCellsMerge, StickyNote, Keyboard, MoveHorizontal, Maximize2, RectangleHorizontal, AlignCenter, AlignLeft, AlignRight, ArrowUpLeft, Bold, ChevronDown, ChevronUp, Code, Copy, CopyPlus, GripVertical, IndentDecrease, IndentIncrease, Italic, Link2, Link2Off, MoreVertical, PanelTop, Strikethrough, Trash2, Underline, Ungroup, Group as GroupIcon, Blocks, ArrowUpToLine, ArrowDownToLine, Shapes, Lock, Subscript, Superscript, Highlighter, Paintbrush, ClipboardPaste } from "lucide-react";
|
|
5
5
|
import { TextSelection } from "prosemirror-state";
|
|
6
6
|
import type { EditorView } from "prosemirror-view";
|
|
7
7
|
import { useEffect, useLayoutEffect, useRef, useState, type ComponentType, type KeyboardEvent as ReactKeyboardEvent, type ReactNode } from "react";
|
|
@@ -18,6 +18,8 @@ import { topLevelOrdered } from "../core/ops";
|
|
|
18
18
|
import type { BlockTransform } from "../core/registry";
|
|
19
19
|
import { insertSibling, richViews } from "../text/rich-text";
|
|
20
20
|
import { canContain } from "../core/structure";
|
|
21
|
+
import { blockActionsFor } from "../../shared/panel-store";
|
|
22
|
+
import { copyStyle, hasCopiedStyle, menuPosition, pastedStyle } from "./block-menu";
|
|
21
23
|
|
|
22
24
|
const cx = (...c: unknown[]) => c.filter((x): x is string => typeof x === "string" && x !== "").join(" ");
|
|
23
25
|
|
|
@@ -150,12 +152,6 @@ export function BlockToolbar({ placement = "floating" }: { placement?: "floating
|
|
|
150
152
|
const text = firstText(res[0]);
|
|
151
153
|
if (text) store.focusText(text, -1);
|
|
152
154
|
};
|
|
153
|
-
const copy = async () => {
|
|
154
|
-
const s = serializeBlocks(ordered.map((id) => store.block(id)!));
|
|
155
|
-
try {
|
|
156
|
-
await navigator.clipboard.write([new ClipboardItem({ "text/plain": new Blob([s.text], { type: "text/plain" }), "text/html": new Blob([s.html], { type: "text/html" }) })]);
|
|
157
|
-
} catch { /* trình duyệt chặn ghi clipboard: người dùng vẫn chép được bằng Ctrl+C */ }
|
|
158
|
-
};
|
|
159
155
|
/** Công cụ của các khối bao ngoài (bảng, bộ cột, nhóm nút) — mỗi loại một lần, gần nhất trước. */
|
|
160
156
|
const contextTools = (ancestors: string[], currentId: string) => {
|
|
161
157
|
const seen = new Set<string>();
|
|
@@ -167,24 +163,12 @@ export function BlockToolbar({ placement = "floating" }: { placement?: "floating
|
|
|
167
163
|
return <div className="ecx-tool-group" key={`ctx-${id}`}><T ancestor={anc} currentId={currentId} /></div>;
|
|
168
164
|
});
|
|
169
165
|
};
|
|
170
|
-
/** Tạo mẫu từ các khối đang chọn; mẫu đồng bộ → thay khối bằng tham chiếu tới mẫu. */
|
|
171
|
-
const createPattern = async () => {
|
|
172
|
-
const picked = ordered.map((id) => store.block(id)!).filter(Boolean);
|
|
173
|
-
const res = await ctx.host.createPattern!(contentFromBlocks(picked));
|
|
174
|
-
if (!res?.synced) return;
|
|
175
|
-
const ref = makeBlock("syncedPattern", { ref: res.ref });
|
|
176
|
-
store.batch(() => {
|
|
177
|
-
store.replace(ordered[0], [ref], { select: { ids: [ref.id], editing: null }, caret: null });
|
|
178
|
-
if (ordered.length > 1) store.remove(ordered.slice(1), { focusNeighbor: false });
|
|
179
|
-
});
|
|
180
|
-
};
|
|
181
166
|
// Khoá khối: ẩn thao tác không được phép
|
|
182
167
|
const movable = ordered.every((id) => store.canMove(id));
|
|
183
168
|
const removable = ordered.every((id) => store.canRemove(id));
|
|
184
169
|
const insertable = store.canInsertInto(parent?.id ?? null);
|
|
185
170
|
const isLocked = nodes.length === 1 && !!(first.attrs.lock || first.attrs.templateLock);
|
|
186
171
|
const nested = first.type === "templatePart" || first.type === "syncedPattern" ? ui.blockEl(first.id)?.dataset.ecxNested : undefined;
|
|
187
|
-
const canGroup = canContain(parent?.type ?? null, "group");
|
|
188
172
|
|
|
189
173
|
return (
|
|
190
174
|
<>
|
|
@@ -264,21 +248,7 @@ export function BlockToolbar({ placement = "floating" }: { placement?: "floating
|
|
|
264
248
|
{nested && <div className="ecx-tool-group"><ToolButton label={labels.editOriginal} className="ecx-tool-wide" onClick={() => store.enterFocus(nested)}><PanelTop className="ecx-icon" /><span className="ecx-tool-text">{labels.editOriginal}</span></ToolButton></div>}
|
|
265
249
|
<div className="ecx-tool-group">
|
|
266
250
|
<Dropdown label={labels.more} trigger={<MoreVertical className="ecx-icon" />}>
|
|
267
|
-
{(close) => (
|
|
268
|
-
<>
|
|
269
|
-
{insertable && <>
|
|
270
|
-
<MenuItem icon={CopyPlus} label={labels.duplicate} shortcut={`${mod}⇧D`} onClick={() => { close(); store.duplicate(ordered); }} />
|
|
271
|
-
<MenuItem icon={ArrowUpToLine} label={labels.insertBefore} shortcut={`${mod}⌥T`} onClick={() => { close(); insertSibling(store, ordered[0], 0); }} />
|
|
272
|
-
<MenuItem icon={ArrowDownToLine} label={labels.insertAfter} shortcut={`${mod}⌥Y`} onClick={() => { close(); insertSibling(store, ordered[ordered.length - 1], 1); }} />
|
|
273
|
-
</>}
|
|
274
|
-
<MenuItem icon={Copy} label={labels.copy} onClick={() => { close(); void copy(); }} />
|
|
275
|
-
{ctx.host.createPattern && <MenuItem icon={Shapes} label={labels.createPattern} onClick={() => { close(); void createPattern(); }} />}
|
|
276
|
-
{canGroup && removable && movable && insertable && <MenuItem icon={GroupIcon} label={labels.group} onClick={() => { close(); store.wrap(ordered, "group"); }} />}
|
|
277
|
-
{nodes.length === 1 && first.content && first.type === "group" && removable && <MenuItem icon={Ungroup} label={labels.ungroup} onClick={() => { close(); store.unwrap(first.id); }} />}
|
|
278
|
-
{nodes.length === 1 && !store.isContentOnly(first.id) && <MenuItem icon={Lock} label={labels.lock} onClick={() => { close(); setLockOpen(true); }} />}
|
|
279
|
-
{removable && <MenuItem icon={Trash2} label={labels.remove} shortcut="⇧⌥Z" danger onClick={() => { close(); store.remove(ordered); }} />}
|
|
280
|
-
</>
|
|
281
|
-
)}
|
|
251
|
+
{(close) => <BlockMenuItems ids={ids} close={close} onLock={() => setLockOpen(true)} />}
|
|
282
252
|
</Dropdown>
|
|
283
253
|
</div>
|
|
284
254
|
</div>
|
|
@@ -333,6 +303,125 @@ function MarkTools({ view, onLink }: { view: EditorView; onLink(): void }) {
|
|
|
333
303
|
);
|
|
334
304
|
}
|
|
335
305
|
|
|
306
|
+
/** Mục của menu ⋮ trên thanh công cụ khối — dùng chung với menu chuột phải (BlockContextMenu). */
|
|
307
|
+
function BlockMenuItems({ ids, close, onLock }: { ids: string[]; close(): void; onLock(): void }) {
|
|
308
|
+
const ctx = useEditor();
|
|
309
|
+
const { store, ui, labels } = ctx;
|
|
310
|
+
const nodes = ids.map((id) => store.block(id)).filter(Boolean) as BNode[];
|
|
311
|
+
const loc = nodes[0] ? store.locate(nodes[0].id) : null;
|
|
312
|
+
if (!loc) return null;
|
|
313
|
+
const first = nodes[0];
|
|
314
|
+
const parent = loc.parent;
|
|
315
|
+
const ordered = topLevelOrdered(store.getState().docs[loc.docId].blocks, ids);
|
|
316
|
+
const movable = ordered.every((id) => store.canMove(id));
|
|
317
|
+
const removable = ordered.every((id) => store.canRemove(id));
|
|
318
|
+
const insertable = store.canInsertInto(parent?.id ?? null);
|
|
319
|
+
const canGroup = canContain(parent?.type ?? null, "group");
|
|
320
|
+
const styleEditable = ordered.every((id) => !store.isContentOnly(id) && store.modeOf(id) !== "disabled");
|
|
321
|
+
const copy = async () => {
|
|
322
|
+
const s = serializeBlocks(ordered.map((id) => store.block(id)!));
|
|
323
|
+
try {
|
|
324
|
+
await navigator.clipboard.write([new ClipboardItem({ "text/plain": new Blob([s.text], { type: "text/plain" }), "text/html": new Blob([s.html], { type: "text/html" }) })]);
|
|
325
|
+
} catch { /* trình duyệt chặn ghi clipboard: người dùng vẫn chép được bằng Ctrl+C */ }
|
|
326
|
+
};
|
|
327
|
+
/** Tạo mẫu từ các khối đang chọn; mẫu đồng bộ → thay khối bằng tham chiếu tới mẫu. */
|
|
328
|
+
const createPattern = async () => {
|
|
329
|
+
const picked = ordered.map((id) => store.block(id)!).filter(Boolean);
|
|
330
|
+
const res = await ctx.host.createPattern!(contentFromBlocks(picked));
|
|
331
|
+
if (!res?.synced) return;
|
|
332
|
+
const ref = makeBlock("syncedPattern", { ref: res.ref });
|
|
333
|
+
store.batch(() => {
|
|
334
|
+
store.replace(ordered[0], [ref], { select: { ids: [ref.id], editing: null }, caret: null });
|
|
335
|
+
if (ordered.length > 1) store.remove(ordered.slice(1), { focusNeighbor: false });
|
|
336
|
+
});
|
|
337
|
+
};
|
|
338
|
+
return (
|
|
339
|
+
<>
|
|
340
|
+
{insertable && <>
|
|
341
|
+
<MenuItem icon={CopyPlus} label={labels.duplicate} shortcut={`${mod}⇧D`} onClick={() => { close(); store.duplicate(ordered); }} />
|
|
342
|
+
<MenuItem icon={ArrowUpToLine} label={labels.insertBefore} shortcut={`${mod}⌥T`} onClick={() => { close(); insertSibling(store, ordered[0], 0); }} />
|
|
343
|
+
<MenuItem icon={ArrowDownToLine} label={labels.insertAfter} shortcut={`${mod}⌥Y`} onClick={() => { close(); insertSibling(store, ordered[ordered.length - 1], 1); }} />
|
|
344
|
+
</>}
|
|
345
|
+
<MenuItem icon={Copy} label={labels.copy} onClick={() => { close(); void copy(); }} />
|
|
346
|
+
<MenuItem icon={Paintbrush} label={labels.copyStyle} onClick={() => { close(); copyStyle(first.attrs); ui.announce(labels.styleCopied); }} />
|
|
347
|
+
{hasCopiedStyle() && styleEditable && <MenuItem icon={ClipboardPaste} label={labels.pasteStyle} onClick={() => { close(); store.setAttrs(ordered, pastedStyle()!); }} />}
|
|
348
|
+
{ctx.host.createPattern && <MenuItem icon={Shapes} label={labels.createPattern} onClick={() => { close(); void createPattern(); }} />}
|
|
349
|
+
{blockActionsFor(nodes.map((n) => n.type)).map((a) => (
|
|
350
|
+
<MenuItem key={a.id} icon={a.icon} label={ctx.host.translate ? ctx.host.translate(a.label) : a.label} onClick={() => {
|
|
351
|
+
close();
|
|
352
|
+
Promise.resolve(a.run({ blocks: nodes.map((b) => ({ id: b.id, type: b.type, attrs: b.attrs })), setAttrs: (x) => store.setAttrs(ordered, x) }))
|
|
353
|
+
.catch((e) => console.warn("[ecomweb-editor] block action", a.id, e));
|
|
354
|
+
}} />
|
|
355
|
+
))}
|
|
356
|
+
{canGroup && removable && movable && insertable && <MenuItem icon={GroupIcon} label={labels.group} onClick={() => { close(); store.wrap(ordered, "group"); }} />}
|
|
357
|
+
{nodes.length === 1 && first.content && first.type === "group" && removable && <MenuItem icon={Ungroup} label={labels.ungroup} onClick={() => { close(); store.unwrap(first.id); }} />}
|
|
358
|
+
{nodes.length === 1 && !store.isContentOnly(first.id) && <MenuItem icon={Lock} label={labels.lock} onClick={() => { close(); onLock(); }} />}
|
|
359
|
+
{removable && <MenuItem icon={Trash2} label={labels.remove} shortcut="⇧⌥Z" danger onClick={() => { close(); store.remove(ordered); }} />}
|
|
360
|
+
</>
|
|
361
|
+
);
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/**
|
|
365
|
+
* Menu chuột phải trên khối: cùng mục với menu ⋮ (BlockMenuItems). Mở bằng chuột phải, Shift+F10 hoặc phím Menu (khung soạn gọi ui.openContextMenu);
|
|
366
|
+
* ↑/↓/Home/End đi giữa các mục, Esc / Tab / bấm ra ngoài / cuộn thì đóng.
|
|
367
|
+
*/
|
|
368
|
+
export function BlockContextMenu() {
|
|
369
|
+
const { ui, store, labels } = useEditor();
|
|
370
|
+
useUiTick();
|
|
371
|
+
const at = ui.contextMenu;
|
|
372
|
+
const ref = useRef<HTMLDivElement>(null);
|
|
373
|
+
const [pos, setPos] = useState<{ top: number; left: number } | null>(null);
|
|
374
|
+
const [lock, setLock] = useState<BNode | null>(null);
|
|
375
|
+
// refocus: bàn phím quay về khối (Esc / Tab) hoặc khung soạn (chọn mục xong — khối có thể đã bị xoá / thay)
|
|
376
|
+
const close = (refocus?: "block" | "canvas") => {
|
|
377
|
+
const id = ui.contextMenu?.ids[0];
|
|
378
|
+
ui.openContextMenu(null);
|
|
379
|
+
const root = ui.canvasDoc?.querySelector<HTMLElement>(".ecx-canvas-root");
|
|
380
|
+
if (refocus) ((refocus === "block" && id && ui.blockEl(id)) || root)?.focus({ preventScroll: true });
|
|
381
|
+
};
|
|
382
|
+
useLayoutEffect(() => {
|
|
383
|
+
const m = ref.current;
|
|
384
|
+
if (!at || !m) { setPos(null); return; }
|
|
385
|
+
// Gốc toạ độ của "fixed" có thể là khối cha có transform (như Dropdown): đo rồi trừ ra
|
|
386
|
+
const origin = m.getBoundingClientRect();
|
|
387
|
+
const p = menuPosition(at.x, at.y, m.offsetWidth, m.offsetHeight, window.innerWidth, window.innerHeight);
|
|
388
|
+
setPos({ top: p.top - Math.round(origin.top), left: p.left - Math.round(origin.left) });
|
|
389
|
+
}, [at]);
|
|
390
|
+
useEffect(() => { if (pos) ref.current?.querySelector<HTMLElement>("[role=menuitem]")?.focus(); }, [pos]);
|
|
391
|
+
useEffect(() => {
|
|
392
|
+
if (!at) return;
|
|
393
|
+
const docs = [document, ui.canvasDoc].filter(Boolean) as Document[];
|
|
394
|
+
const outside = (e: Event) => { if (!ref.current?.contains(e.target as Node)) close(); };
|
|
395
|
+
const resize = () => close();
|
|
396
|
+
for (const d of docs) { d.addEventListener("mousedown", outside, true); d.addEventListener("scroll", outside, true); }
|
|
397
|
+
window.addEventListener("resize", resize);
|
|
398
|
+
return () => { for (const d of docs) { d.removeEventListener("mousedown", outside, true); d.removeEventListener("scroll", outside, true); } window.removeEventListener("resize", resize); };
|
|
399
|
+
}, [at, ui]);
|
|
400
|
+
return (
|
|
401
|
+
<>
|
|
402
|
+
{at && (
|
|
403
|
+
<div ref={ref} className="ecx-menu is-floating ecx-context-menu" role="menu" aria-label={labels.blockMenu}
|
|
404
|
+
style={pos ? { top: pos.top, left: pos.left } : { visibility: "hidden", top: 0, left: 0 }}
|
|
405
|
+
onContextMenu={(e) => e.preventDefault()}
|
|
406
|
+
onKeyDown={(e) => {
|
|
407
|
+
const items = Array.from(e.currentTarget.querySelectorAll<HTMLElement>("[role=menuitem]"));
|
|
408
|
+
const i = items.indexOf(document.activeElement as HTMLElement);
|
|
409
|
+
const go = (n: number) => { e.preventDefault(); items[(n + items.length) % items.length]?.focus(); };
|
|
410
|
+
if (e.key === "ArrowDown") go(i + 1);
|
|
411
|
+
else if (e.key === "ArrowUp") go(i < 0 ? -1 : i - 1);
|
|
412
|
+
else if (e.key === "Home") go(0);
|
|
413
|
+
else if (e.key === "End") go(-1);
|
|
414
|
+
else if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); close("block"); }
|
|
415
|
+
else if (e.key === "Tab") { e.preventDefault(); close("block"); }
|
|
416
|
+
}}>
|
|
417
|
+
<BlockMenuItems ids={at.ids} close={() => close("canvas")} onLock={() => setLock(store.block(at.ids[0]) ?? null)} />
|
|
418
|
+
</div>
|
|
419
|
+
)}
|
|
420
|
+
{lock && <LockDialog block={lock} onClose={() => setLock(null)} />}
|
|
421
|
+
</>
|
|
422
|
+
);
|
|
423
|
+
}
|
|
424
|
+
|
|
336
425
|
/** Hộp sửa liên kết của chữ đang chọn (con trỏ trong liên kết → sửa cả liên kết). */
|
|
337
426
|
function LinkPopover({ viewKey, top, left, onClose }: { viewKey: string; top: number; left: number; onClose(): void }) {
|
|
338
427
|
const { labels } = useEditor();
|