@ecomcx/ecomweb-editor 1.27.0 → 1.29.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 +10 -0
- package/src/locales/en/background.ts +22 -0
- package/src/locales/en/block-desc.ts +36 -1
- package/src/locales/en/block-titles.ts +6 -0
- package/src/locales/en/blocks.ts +18 -0
- package/src/locales/en/hints.ts +38 -0
- package/src/locales/en/index.ts +2 -1
- package/src/locales/en/v2.ts +5 -0
- package/src/locales/vi/attrs.ts +10 -0
- package/src/locales/vi/background.ts +22 -0
- package/src/locales/vi/block-desc.ts +36 -1
- package/src/locales/vi/block-titles.ts +6 -0
- package/src/locales/vi/blocks.ts +18 -0
- package/src/locales/vi/hints.ts +38 -0
- package/src/locales/vi/index.ts +2 -1
- package/src/locales/vi/v2.ts +5 -0
- package/src/shared/block-defs.ts +5 -0
- package/src/shared/panel-store.ts +67 -7
- package/src/v2/blocks/compat.tsx +1 -0
- package/src/v2/blocks/index.ts +4 -2
- package/src/v2/blocks/theme.tsx +3 -1
- package/src/v2/blocks/widgets.tsx +65 -0
- 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 +15 -1
- 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 +66 -9
- 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
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { CORE_NODES, ICON_NAMES, widgetMarkup, type WidgetEl } from "@ecomcx/ecomweb-content";
|
|
2
|
+
import { BarChart3, Hash, Image as ImageIcon, ListChecks, Quote, Star } from "lucide-react";
|
|
3
|
+
import { createElement, type CSSProperties, type ReactNode } from "react";
|
|
4
|
+
import { makeBlock } from "../core/model";
|
|
5
|
+
import type { BlockEditProps, BlockType } from "../core/registry";
|
|
6
|
+
import { useMsgs } from "../i18n";
|
|
7
|
+
import { messages } from "../../i18n";
|
|
8
|
+
import { RichText } from "../text/rich-text";
|
|
9
|
+
import { Field } from "../ui/attr-form";
|
|
10
|
+
import { MediaPick } from "./layout";
|
|
11
|
+
|
|
12
|
+
const cx = (...c: unknown[]) => c.filter((x): x is string => typeof x === "string" && x !== "").join(" ");
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Widget lõi trên khung soạn: cùng cây markup với website (@ecomcx/ecomweb-content widgetMarkup) → vẽ y hệt.
|
|
16
|
+
* Ô chữ (`field`) gõ trực tiếp trên khối, chỗ ảnh trống (`slot`) là ô chọn ảnh; số / thanh tiến độ hiện giá trị cuối (không chạy hiệu ứng).
|
|
17
|
+
*/
|
|
18
|
+
function WidgetEdit({ block, blockProps, setAttrs, editable }: BlockEditProps) {
|
|
19
|
+
const t = useMsgs("blocks") as Record<string, string>;
|
|
20
|
+
const tree = widgetMarkup(block.type, block.attrs, true);
|
|
21
|
+
if (!tree || (block.type === "iconList" && !tree.children?.length)) return <div {...blockProps} className={cx(blockProps.className, "ecx-placeholder-block")}>{t.widgetEmpty}</div>;
|
|
22
|
+
const draw = (el: WidgetEl | string, key: number, root?: boolean): ReactNode => {
|
|
23
|
+
if (typeof el === "string") return el;
|
|
24
|
+
if (el.field) {
|
|
25
|
+
const f = el.field;
|
|
26
|
+
return <RichText key={key} blockId={block.id} field={f} tagName="span" value={String(block.attrs[f] ?? "")} onChange={(v) => setAttrs({ [f]: v })} placeholder={t[`widget_${f}`]} placeholderAlways editable={editable} />;
|
|
27
|
+
}
|
|
28
|
+
const kids = el.slot === "media" ? [<MediaPick key="pick" blockId={block.id} />] : (el.children ?? []).map((c, i) => draw(c, i));
|
|
29
|
+
const props: Record<string, unknown> = { key, ...el.props, className: el.className, style: el.style as CSSProperties };
|
|
30
|
+
if (el.tag === "a") props.onClick = (e: Event) => e.preventDefault();
|
|
31
|
+
if (el.tag === "img") props.draggable = false;
|
|
32
|
+
if (root) Object.assign(props, blockProps, { className: cx(blockProps.className, el.className), style: { ...(blockProps.style ?? {}), ...el.style } });
|
|
33
|
+
return createElement(el.tag, props, ...kids);
|
|
34
|
+
};
|
|
35
|
+
return <>{draw(tree, 0, true)}</>;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Danh sách mục của Icon List: mỗi dòng một mục, "chữ | đường dẫn" (đường dẫn tuỳ chọn); dòng trống giữ khi đang gõ, website bỏ qua. Icon riêng từng mục: chỉ qua dữ liệu (AI / mẫu). */
|
|
39
|
+
function IconListInspector({ attrs, setAttrs }: BlockEditProps) {
|
|
40
|
+
const t = useMsgs("blocks") as Record<string, string>;
|
|
41
|
+
const items: Array<{ text: string; href?: string; icon?: string }> = Array.isArray(attrs.items) ? attrs.items : [];
|
|
42
|
+
const value = items.map((it) => (it.href ? `${it.text} | ${it.href}` : it.text)).join("\n");
|
|
43
|
+
const parse = (s: string) => s.split("\n").slice(0, 50).map((line, i) => {
|
|
44
|
+
const [text, href] = line.split("|").map((x) => x.trim());
|
|
45
|
+
return { ...(items[i]?.icon ? { icon: items[i].icon } : {}), text: text ?? "", ...(href ? { href } : {}) };
|
|
46
|
+
});
|
|
47
|
+
return <Field label={t.iconListItems}><textarea className="ecx-input" rows={6} value={value} data-icon-list-items onChange={(e) => setAttrs({ items: parse(e.target.value) })} /></Field>;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const spec = (name: string) => CORE_NODES[name]?.attrs;
|
|
51
|
+
const ICON_SELECT = { type: "string" as const, enum: ICON_NAMES };
|
|
52
|
+
|
|
53
|
+
/** Khối widget của lõi; `lang` = ngôn ngữ của trình soạn (chữ mẫu khi chèn). */
|
|
54
|
+
export function widgetBlocks(lang?: string): BlockType[] {
|
|
55
|
+
const m = messages("blocks", lang) as Record<string, string>;
|
|
56
|
+
const base = { kind: "atom" as const, category: "widgets", edit: WidgetEdit, supports: { style: true, anchor: true, className: true } };
|
|
57
|
+
return [
|
|
58
|
+
{ ...base, name: "iconBox", title: "Icon Box", icon: Star, keywords: "icon box hop bieu tuong tinh nang dich vu feature", attributes: { ...spec("iconBox"), icon: { ...ICON_SELECT, default: "star" } }, create: () => makeBlock("iconBox", { icon: "star", title: m.sampleTitle, text: m.sampleText }), summary: (a) => a.title },
|
|
59
|
+
{ ...base, name: "imageBox", title: "Image Box", icon: ImageIcon, keywords: "image box hop anh the card dich vu", attributes: { ...spec("imageBox"), src: { type: "url", control: "media" } }, create: () => makeBlock("imageBox", { title: m.sampleTitle, text: m.sampleText }), summary: (a) => a.title },
|
|
60
|
+
{ ...base, name: "iconList", title: "Icon List", icon: ListChecks, keywords: "icon list danh sach bieu tuong loi ich checklist", inspector: IconListInspector, attributes: { ...spec("iconList"), icon: { ...ICON_SELECT, default: "check" } }, create: () => makeBlock("iconList", { items: [m.sampleItem1, m.sampleItem2, m.sampleItem3].map((text) => ({ text })) }) },
|
|
61
|
+
{ ...base, name: "counter", title: "Counter", icon: Hash, keywords: "counter dem so con so thong ke number", attributes: spec("counter"), create: () => makeBlock("counter", { end: 100, suffix: "+", title: m.sampleCounter, textAlign: "center" }), summary: (a) => a.title },
|
|
62
|
+
{ ...base, name: "testimonial", title: "Testimonial", icon: Quote, keywords: "testimonial loi chung thuc danh gia khach hang review", attributes: { ...spec("testimonial"), src: { type: "url", control: "media" } }, create: () => makeBlock("testimonial", { quote: m.sampleQuote, name: m.sampleName, role: m.sampleRole }), summary: (a) => a.name },
|
|
63
|
+
{ ...base, name: "progressBar", title: "Progress Bar", icon: BarChart3, keywords: "progress bar thanh tien do ky nang phan tram", attributes: spec("progressBar"), create: () => makeBlock("progressBar", { label: m.sampleSkill, value: 80 }), summary: (a) => a.label },
|
|
64
|
+
];
|
|
65
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { normalizeStyle, styleClass, widthClass } from "@ecomcx/ecomweb-content";
|
|
1
|
+
import { controlsCss, normalizeStyle, styleClass, widthClass } from "@ecomcx/ecomweb-content";
|
|
2
|
+
import { blockControls } from "../../shared/panel-store";
|
|
2
3
|
import { Component, memo, useCallback, useContext, useEffect, useMemo, useRef, type ErrorInfo, type MouseEvent, type ReactElement, type ReactNode } from "react";
|
|
3
4
|
import { DocScopeProvider, LoopPostContext, useDocScope, useEditor, useEditorState } from "../context";
|
|
4
5
|
import { ServerBlock } from "./server-block";
|
|
@@ -72,6 +73,7 @@ export function useBlockProps(block: BNode, state: { selected: boolean; editing:
|
|
|
72
73
|
state.editing && "is-editing",
|
|
73
74
|
state.mode === "disabled" && "is-locked",
|
|
74
75
|
style && styleClass(style),
|
|
76
|
+
controlsCss(blockControls(), block.type, a)?.cls,
|
|
75
77
|
widthClass(block.type, a),
|
|
76
78
|
typeof a.blockStyle === "string" && `ecx-is-${a.blockStyle}`,
|
|
77
79
|
typeof a.className === "string" && a.className,
|
package/src/v2/canvas/canvas.tsx
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { collectStyles, normalizeStyle, presetCss, type BlockStyle } from "@ecomcx/ecomweb-content";
|
|
1
|
+
import { collectStyles, controlsCss, normalizeStyle, presetCss, type BlockStyle } from "@ecomcx/ecomweb-content";
|
|
2
|
+
import { blockAssets, blockControls, blockReadyFns, onBlockPanelsChange } from "../../shared/panel-store";
|
|
2
3
|
import { createElement, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode } from "react";
|
|
3
4
|
import { onAnimationsChange, pluginAnimations } from "../../shared/animation-store";
|
|
4
5
|
import { createPortal } from "react-dom";
|
|
@@ -19,6 +20,7 @@ export type Device = "desktop" | "tablet" | "mobile";
|
|
|
19
20
|
export const DEVICE_WIDTH: Record<Device, number | null> = { desktop: null, tablet: 768, mobile: 390 };
|
|
20
21
|
|
|
21
22
|
export interface CanvasProps {
|
|
23
|
+
/** Bỏ trống = theo `ui.device` (khổ dùng chung với tab Kiểu dáng). */
|
|
22
24
|
device?: Device;
|
|
23
25
|
className?: string;
|
|
24
26
|
/** Class của vùng nội dung trong iframe (theme thường tạo kiểu .ecx-content / .entry-content). */
|
|
@@ -34,11 +36,11 @@ const SRC_DOC = `<!doctype html><html><head><meta charset="utf-8"><meta name="vi
|
|
|
34
36
|
/** Tỉ lệ của chế độ thu nhỏ. */
|
|
35
37
|
export const ZOOM_OUT = 0.5;
|
|
36
38
|
/** 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 =
|
|
39
|
+
export const DESKTOP_MIN_WIDTH = 1025;
|
|
38
40
|
/** 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
41
|
export const MIN_FIT = 0.6;
|
|
40
42
|
|
|
41
|
-
export function Canvas({ device
|
|
43
|
+
export function Canvas({ device: deviceProp, className, contentClassName = "ecx-content", before, after }: CanvasProps) {
|
|
42
44
|
const { ui, labels } = useEditor();
|
|
43
45
|
const frameRef = useRef<HTMLIFrameElement>(null);
|
|
44
46
|
const [doc, setDoc] = useState<Document | null>(null);
|
|
@@ -71,6 +73,8 @@ export function Canvas({ device = "desktop", className, contentClassName = "ecx-
|
|
|
71
73
|
useEffect(() => () => { if (ui.canvasFrame === frameRef.current) { ui.canvasFrame = null; ui.canvasDoc = null; } }, [ui]);
|
|
72
74
|
|
|
73
75
|
useUiTick();
|
|
76
|
+
// Không truyền device → theo khổ dùng chung của trình soạn (DeviceSwitcher, tab Kiểu dáng)
|
|
77
|
+
const device = deviceProp ?? ui.device;
|
|
74
78
|
const width = DEVICE_WIDTH[device];
|
|
75
79
|
// 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ệ
|
|
76
80
|
const ratio = !width && wrapW > 0 && wrapW < DESKTOP_MIN_WIDTH ? wrapW / DESKTOP_MIN_WIDTH : 1;
|
|
@@ -194,8 +198,12 @@ function useCanvasStyles(doc: Document) {
|
|
|
194
198
|
const docs = useEditorState((s) => s.docs);
|
|
195
199
|
// Kiểu dáng gom theo từng cây khối (cache theo tham chiếu): gõ chữ không đổi style → không duyệt lại cả tài liệu dài
|
|
196
200
|
const perTree = useRef(new WeakMap<BNode[], BlockStyle[]>());
|
|
201
|
+
const controls = useSyncExternalStore(onBlockPanelsChange, blockControls, blockControls);
|
|
197
202
|
const css = useMemo(() => {
|
|
198
203
|
const styles: BlockStyle[] = [];
|
|
204
|
+
// Ô điều khiển khai CSS của plugin — cùng hàm controlsCss website dùng
|
|
205
|
+
const ctrl = new Map<string, string>();
|
|
206
|
+
if (controls.length) for (const d of Object.values(docs)) for (const b of flatten(d.blocks)) { const c = controlsCss(controls, b.type, b.attrs); if (c) ctrl.set(c.cls, c.css); }
|
|
199
207
|
for (const d of Object.values(docs)) {
|
|
200
208
|
let list = perTree.current.get(d.blocks);
|
|
201
209
|
if (!list) {
|
|
@@ -205,8 +213,9 @@ function useCanvasStyles(doc: Document) {
|
|
|
205
213
|
}
|
|
206
214
|
styles.push(...list);
|
|
207
215
|
}
|
|
208
|
-
return collectStyles(styles);
|
|
209
|
-
}, [docs]);
|
|
216
|
+
return collectStyles(styles) + [...ctrl.values()].join("");
|
|
217
|
+
}, [docs, controls]);
|
|
218
|
+
usePluginRuntime(doc, docs);
|
|
210
219
|
void store;
|
|
211
220
|
useLayoutEffect(() => {
|
|
212
221
|
let el = head.querySelector<HTMLStyleElement>("style[data-ecx=blocks]");
|
|
@@ -224,7 +233,7 @@ function useCanvasStyles(doc: Document) {
|
|
|
224
233
|
|
|
225
234
|
/** Cuộn / đổi cỡ trong iframe → thanh công cụ đo lại vị trí. */
|
|
226
235
|
function useCanvasEvents(doc: Document) {
|
|
227
|
-
const { ui } = useEditor();
|
|
236
|
+
const { ui, store } = useEditor();
|
|
228
237
|
useEffect(() => {
|
|
229
238
|
const win = doc.defaultView!;
|
|
230
239
|
let raf = 0;
|
|
@@ -237,11 +246,28 @@ function useCanvasEvents(doc: Document) {
|
|
|
237
246
|
win.addEventListener("resize", bump);
|
|
238
247
|
const ro = new ResizeObserver(bump);
|
|
239
248
|
ro.observe(doc.body);
|
|
249
|
+
// Chuột phải / Shift+F10 / phím Menu trên khối → menu của khối (BlockContextMenu); Shift + chuột phải giữ menu của trình duyệt (chính tả, dán…)
|
|
250
|
+
const menu = (e: MouseEvent) => {
|
|
251
|
+
const el = (e.target as Element | null)?.closest?.<HTMLElement>("[data-ecx-block]");
|
|
252
|
+
const id = el?.dataset.ecxBlock;
|
|
253
|
+
if (!id || !ui.canvasFrame || (e.shiftKey && e.button === 2) || store.modeOf(id) === "disabled") return;
|
|
254
|
+
e.preventDefault();
|
|
255
|
+
const sel = store.getState().selection;
|
|
256
|
+
const ids = sel.ids.includes(id) ? sel.ids : sel.editing === id ? [id] : null;
|
|
257
|
+
if (!ids) store.select([id], { editing: null });
|
|
258
|
+
const f = ui.canvasFrame.getBoundingClientRect();
|
|
259
|
+
const scale = f.width / (ui.canvasFrame.offsetWidth || f.width) || 1;
|
|
260
|
+
// Mở bằng bàn phím: không có toạ độ chuột → neo dưới góc trái của khối
|
|
261
|
+
const r = !e.clientX && !e.clientY ? ui.blockRect(id) : null;
|
|
262
|
+
ui.openContextMenu({ x: r ? r.left : f.left + e.clientX * scale, y: r ? r.top + Math.min(r.height, 24) : f.top + e.clientY * scale, ids: ids ?? [id] });
|
|
263
|
+
};
|
|
264
|
+
doc.addEventListener("contextmenu", menu);
|
|
240
265
|
return () => {
|
|
241
266
|
win.removeEventListener("scroll", bump); win.removeEventListener("resize", bump); ro.disconnect(); cancelAnimationFrame(raf);
|
|
242
267
|
doc.removeEventListener("mousemove", moved); document.removeEventListener("mousemove", moved);
|
|
268
|
+
doc.removeEventListener("contextmenu", menu);
|
|
243
269
|
};
|
|
244
|
-
}, [doc, ui]);
|
|
270
|
+
}, [doc, ui, store]);
|
|
245
271
|
}
|
|
246
272
|
|
|
247
273
|
/** Đang gõ chữ / ô nhập: phím thuộc về ô đó. */
|
|
@@ -447,3 +473,50 @@ function useRangeHighlight(doc: Document): boolean {
|
|
|
447
473
|
}, [range, revision, doc, store, ui]);
|
|
448
474
|
return !!range;
|
|
449
475
|
}
|
|
476
|
+
|
|
477
|
+
/**
|
|
478
|
+
* onBlockReady + asset theo nhu cầu của plugin trong khung soạn (iframe): gọi lại khi khối đổi thuộc tính (dọn bản cũ trước),
|
|
479
|
+
* dọn khi khối rời DOM; asset nạp một lần khi nội dung có khối / class khớp.
|
|
480
|
+
*/
|
|
481
|
+
function usePluginRuntime(doc: Document, docs: Record<string, { blocks: BNode[] }>) {
|
|
482
|
+
const ready = useSyncExternalStore(onBlockPanelsChange, blockReadyFns, blockReadyFns);
|
|
483
|
+
const assets = useSyncExternalStore(onBlockPanelsChange, blockAssets, blockAssets);
|
|
484
|
+
const live = useRef(new Map<HTMLElement, { attrs: unknown; cleanups: Array<void | (() => void)> }>());
|
|
485
|
+
useEffect(() => {
|
|
486
|
+
const byId = new Map<string, BNode>();
|
|
487
|
+
for (const d of Object.values(docs)) for (const b of flatten(d.blocks)) byId.set(b.id, b);
|
|
488
|
+
if (assets.length) {
|
|
489
|
+
const types = new Set([...byId.values()].map((b) => b.type));
|
|
490
|
+
const classes = [...byId.values()].flatMap((b) => (typeof b.attrs.className === "string" ? b.attrs.className.split(/\s+/) : []));
|
|
491
|
+
for (const a of assets) {
|
|
492
|
+
const hit = a.when.blocks?.some((t) => types.has(t)) || (!!a.when.className && classes.some((c) => c.startsWith(a.when.className!)));
|
|
493
|
+
if (!hit || doc.head.querySelector(`[data-ecx-asset="${CSS.escape(a.src)}"]`)) continue;
|
|
494
|
+
const el = a.kind === "style" ? Object.assign(doc.createElement("link"), { rel: "stylesheet", href: a.src }) : Object.assign(doc.createElement("script"), { src: a.src, async: true });
|
|
495
|
+
el.dataset.ecxAsset = a.src;
|
|
496
|
+
doc.head.append(el);
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
const run = () => {
|
|
500
|
+
const seen = new Set<HTMLElement>();
|
|
501
|
+
if (ready.length) for (const el of doc.querySelectorAll<HTMLElement>("[data-ecx-block]")) {
|
|
502
|
+
const b = byId.get(el.dataset.ecxBlock!);
|
|
503
|
+
if (!b) continue;
|
|
504
|
+
const fns = ready.filter((r) => r.type === "*" || r.type === b.type);
|
|
505
|
+
if (!fns.length) continue;
|
|
506
|
+
seen.add(el);
|
|
507
|
+
const cur = live.current.get(el);
|
|
508
|
+
if (cur && cur.attrs === b.attrs) continue;
|
|
509
|
+
cur?.cleanups.forEach((c) => { try { c?.(); } catch { /* bỏ qua */ } });
|
|
510
|
+
live.current.set(el, { attrs: b.attrs, cleanups: fns.map((r) => { try { return r.fn(el, b.attrs); } catch (e) { console.warn("[ecomweb-editor] onBlockReady", b.type, e); } }) });
|
|
511
|
+
}
|
|
512
|
+
for (const [el, v] of live.current) if (!seen.has(el)) { v.cleanups.forEach((c) => { try { c?.(); } catch { /* bỏ qua */ } }); live.current.delete(el); }
|
|
513
|
+
};
|
|
514
|
+
run();
|
|
515
|
+
if (!ready.length) return;
|
|
516
|
+
// Khối vẽ lại / thêm / bỏ mà tài liệu không đổi tham chiếu (vd ServerBlock tải xong)
|
|
517
|
+
const mo = new MutationObserver(run);
|
|
518
|
+
mo.observe(doc.body, { childList: true, subtree: true });
|
|
519
|
+
return () => mo.disconnect();
|
|
520
|
+
}, [doc, docs, ready, assets]);
|
|
521
|
+
useEffect(() => () => { for (const v of live.current.values()) v.cleanups.forEach((c) => { try { c?.(); } catch { /* bỏ qua */ } }); live.current.clear(); }, []);
|
|
522
|
+
}
|
package/src/v2/canvas/dnd.ts
CHANGED
|
@@ -23,7 +23,15 @@ export function startDragNew(ctx: EditorContextValue, e: ReactPointerEvent, opti
|
|
|
23
23
|
begin(ctx, e, { ids: [], types: [option.type], create: () => option.create(), newType: option.type });
|
|
24
24
|
}
|
|
25
25
|
|
|
26
|
-
interface Source { ids: string[]; types: string[]; create?: () => BNode; newType?: string }
|
|
26
|
+
interface Source { ids: string[]; types: string[]; create?: () => BNode | BNode[]; newType?: string }
|
|
27
|
+
|
|
28
|
+
/** Kéo một mẫu (nhiều khối) từ thư viện vào khung soạn: thả = chèn cả mẫu, chọn khối đầu của mẫu. */
|
|
29
|
+
export function startDragBlocks(ctx: EditorContextValue, e: ReactPointerEvent, create: () => BNode[]) {
|
|
30
|
+
if (e.button !== 0) return;
|
|
31
|
+
const sample = create();
|
|
32
|
+
if (!sample.length) return;
|
|
33
|
+
begin(ctx, e, { ids: [], types: sample.map((n) => n.type), create, newType: sample[0].type });
|
|
34
|
+
}
|
|
27
35
|
|
|
28
36
|
function begin(ctx: EditorContextValue, e: ReactPointerEvent, src: Source) {
|
|
29
37
|
const { ui, store } = ctx;
|
|
@@ -68,7 +76,12 @@ function begin(ctx: EditorContextValue, e: ReactPointerEvent, src: Source) {
|
|
|
68
76
|
cleanup();
|
|
69
77
|
ui.setDrag(null);
|
|
70
78
|
if (!wasStarted || !target) return;
|
|
71
|
-
if (src.create)
|
|
79
|
+
if (src.create) {
|
|
80
|
+
const made = src.create();
|
|
81
|
+
const nodes = Array.isArray(made) ? made : [made];
|
|
82
|
+
store.insert(target.docId, target.parentId, target.index, nodes);
|
|
83
|
+
if (nodes.length > 1) store.select([nodes[0].id]);
|
|
84
|
+
}
|
|
72
85
|
else store.moveTo(src.ids, target.docId, target.parentId, target.index);
|
|
73
86
|
// Không để click sau khi thả chèn thêm khối (thư viện khối)
|
|
74
87
|
handle.addEventListener("click", (c) => { c.stopPropagation(); c.preventDefault(); }, { capture: true, once: true });
|
package/src/v2/context.tsx
CHANGED
|
@@ -32,6 +32,9 @@ export class EditorUi {
|
|
|
32
32
|
typing = false;
|
|
33
33
|
/** Thu nhỏ: cả trang trong tầm nhìn, chỉ chọn / sắp xếp các phần (khối cấp cao nhất). */
|
|
34
34
|
zoomOut = false;
|
|
35
|
+
/** Khổ màn hình đang soạn: khung soạn vẽ theo bề rộng này, tab Kiểu dáng sửa giá trị của khổ này (dùng chung, đổi một nơi thì nơi kia theo). */
|
|
36
|
+
device: "desktop" | "tablet" | "mobile" = "desktop";
|
|
37
|
+
setDevice(d: "desktop" | "tablet" | "mobile") { if (this.device !== d) { this.device = d; this.bump(); } }
|
|
35
38
|
/** Mở thư viện khối đầy đủ (cột trái) — nút "Xem tất cả" của chèn nhanh; ứng dụng / BlockEditor gán. */
|
|
36
39
|
browseAll: (() => void) | null = null;
|
|
37
40
|
setZoomOut(v: boolean) { if (this.zoomOut !== v) { this.zoomOut = v; this.bump(); } }
|
|
@@ -69,6 +72,9 @@ export class EditorUi {
|
|
|
69
72
|
/** Alt+F10: đưa bàn phím lên thanh công cụ của khối. */
|
|
70
73
|
focusToolbar() { document.querySelector<HTMLElement>(".ecx-toolbar button:not(:disabled)")?.focus(); }
|
|
71
74
|
setDrag(d: DragState | null) { this.drag = d; this.bump(); }
|
|
75
|
+
/** Menu chuột phải đang mở: vị trí theo toạ độ trang ngoài + các khối áp dụng. */
|
|
76
|
+
contextMenu: { x: number; y: number; ids: string[] } | null = null;
|
|
77
|
+
openContextMenu(m: { x: number; y: number; ids: string[] } | null) { if (m || this.contextMenu) { this.contextMenu = m; this.bump(); } }
|
|
72
78
|
}
|
|
73
79
|
|
|
74
80
|
export interface InserterRequest {
|
package/src/v2/core/registry.ts
CHANGED
|
@@ -96,7 +96,8 @@ export interface BlockType {
|
|
|
96
96
|
plain?: boolean;
|
|
97
97
|
/** Khối chữ: chữ gợi ý khi trống. */
|
|
98
98
|
placeholder?: string | ((labels: V2Labels) => string);
|
|
99
|
-
|
|
99
|
+
/** style: false = không có tab Kiểu dáng; mảng nhóm ("typography", "color", "background"…) = chỉ hiện các nhóm đó (xem ui/style-supports.ts). */
|
|
100
|
+
supports?: { style?: boolean | string[]; anchor?: boolean; className?: boolean; blockStyle?: boolean; align?: boolean };
|
|
100
101
|
/** Tóm tắt một dòng (cây khối, khung chung). */
|
|
101
102
|
summary?(attrs: Record<string, any>): string | undefined;
|
|
102
103
|
}
|
package/src/v2/editor.css
CHANGED
|
@@ -338,3 +338,24 @@ body.is-dragging, body.is-dragging * { cursor: grabbing !important; user-select:
|
|
|
338
338
|
.ecx-ai-note { margin: 0; font-size: 12px; color: var(--ecx-ed-muted, #667085); }
|
|
339
339
|
@keyframes ecx-ai-pulse { 50% { opacity: .45; } }
|
|
340
340
|
@media (prefers-reduced-motion: reduce) { .ecx-ai-wait { animation: none; } }
|
|
341
|
+
|
|
342
|
+
/* Ảnh nền (tab Kiểu dáng) */
|
|
343
|
+
.ecx-bg-image { display: grid; gap: 8px; }
|
|
344
|
+
.ecx-bg-thumb { width: 100%; aspect-ratio: 16 / 9; object-fit: cover; border-radius: 6px; border: 1px solid var(--ecx-ed-line); background: var(--ecx-ed-subtle); }
|
|
345
|
+
.ecx-bg-thumb.is-inherited { opacity: .55; }
|
|
346
|
+
.ecx-bg-actions { display: flex; gap: 6px; flex-wrap: wrap; }
|
|
347
|
+
.ecx-bg-focal { display: grid; grid-template-columns: repeat(3, 28px); gap: 4px; }
|
|
348
|
+
.ecx-bg-focal-dot { width: 28px; height: 28px; border-radius: 6px; border: 1px solid var(--ecx-ed-line-strong); background: var(--ecx-ed-panel); cursor: pointer; position: relative; }
|
|
349
|
+
.ecx-bg-focal-dot::after { content: ""; position: absolute; inset: 10px; border-radius: 50%; background: var(--ecx-ed-line-strong); }
|
|
350
|
+
.ecx-bg-focal-dot:hover { background: var(--ecx-ed-hover); }
|
|
351
|
+
.ecx-bg-focal-dot.is-active { border-color: var(--ecx-ed-accent); background: var(--ecx-ed-accent-soft); }
|
|
352
|
+
.ecx-bg-focal-dot.is-active::after { background: var(--ecx-ed-accent); }
|
|
353
|
+
.ecx-bg-focal-dot:focus-visible { outline: 2px solid var(--ecx-ed-accent); outline-offset: 1px; }
|
|
354
|
+
|
|
355
|
+
/* Nút "+ Thêm section" giữa hai section cấp trên cùng */
|
|
356
|
+
.ecx-section-adder { position: fixed; z-index: 30; display: grid; place-items: center; width: 28px; height: 28px; border-radius: 999px; border: 0; background: var(--ecx-ed-accent); color: var(--ecx-ed-accent-fg); box-shadow: var(--ecx-ed-shadow); cursor: pointer; }
|
|
357
|
+
.ecx-section-adder:hover { background: var(--ecx-ed-accent-hover); }
|
|
358
|
+
.ecx-section-adder:focus-visible { outline: 2px solid var(--ecx-ed-accent); outline-offset: 2px; }
|
|
359
|
+
.ecx-section-adder .ecx-icon { width: 16px; height: 16px; }
|
|
360
|
+
.ecx-inserter-popover .ecx-tabs { margin-bottom: 6px; }
|
|
361
|
+
.ecx-inserter-patterns { max-height: 320px; overflow-y: auto; }
|
package/src/v2/editor.tsx
CHANGED
|
@@ -10,6 +10,7 @@ import { Canvas, type Device } from "./canvas/canvas";
|
|
|
10
10
|
import { EditorContext, EditorUi, useEditor, useEditorState, useUiTick, type EditorContextValue } from "./context";
|
|
11
11
|
import type { EditorHost } from "./core/host";
|
|
12
12
|
import { InserterPanel, InserterPopover } from "./ui/inserter";
|
|
13
|
+
import { SectionAdder } from "./ui/section-adder";
|
|
13
14
|
import { AiWrite } from "./ui/ai";
|
|
14
15
|
import { labelsV2, type V2Labels } from "./labels";
|
|
15
16
|
import { localesVersion, onLocalesChange } from "../i18n";
|
|
@@ -20,7 +21,7 @@ import { ListView } from "./ui/list-view";
|
|
|
20
21
|
import { PrefsStore, usePrefs, type PrefsStorage } from "./prefs";
|
|
21
22
|
import { Breadcrumbs, CodeEditor, MoreMenu } from "./ui/options";
|
|
22
23
|
import { EditorStore, type DocRecord } from "./core/store";
|
|
23
|
-
import { BlockToolbar, DropIndicator, ToolButton } from "./ui/toolbar";
|
|
24
|
+
import { BlockContextMenu, BlockToolbar, DropIndicator, ToolButton } from "./ui/toolbar";
|
|
24
25
|
|
|
25
26
|
const cx = (...c: unknown[]) => c.filter((x): x is string => typeof x === "string" && x !== "").join(" ");
|
|
26
27
|
|
|
@@ -181,7 +182,8 @@ function EditorShell({ className, onSave, header, actions, menuExtra, canvasBefo
|
|
|
181
182
|
const [left, setLeft] = useState<"inserter" | "list" | null>(() => (ctx.prefs.get().showListView ? "list" : null));
|
|
182
183
|
useEffect(() => { ctx.ui.browseAll = () => setLeft("inserter"); return () => { ctx.ui.browseAll = null; }; }, [ctx.ui]);
|
|
183
184
|
const [right, setRight] = useState(true);
|
|
184
|
-
|
|
185
|
+
// Khổ ban đầu do ứng dụng chọn; sau đó dùng chung qua ui.device (DeviceSwitcher, tab Kiểu dáng)
|
|
186
|
+
useEffect(() => { if (defaultDevice) ctx.ui.setDevice(defaultDevice); }, [ctx.ui, defaultDevice]);
|
|
185
187
|
const [saving, setSaving] = useState<"idle" | "saving" | "saved" | "error">("idle");
|
|
186
188
|
const [error, setError] = useState<string | null>(null);
|
|
187
189
|
useEditorState((s) => s.revision);
|
|
@@ -235,9 +237,7 @@ function EditorShell({ className, onSave, header, actions, menuExtra, canvasBefo
|
|
|
235
237
|
{p.mode === "visual" && <ZoomToggle />}
|
|
236
238
|
</div>
|
|
237
239
|
<div className="ecx-topbar-end">
|
|
238
|
-
<
|
|
239
|
-
{([["desktop", Monitor, labels.deviceDesktop], ["tablet", Tablet, labels.deviceTablet], ["mobile", Smartphone, labels.deviceMobile]] as const).map(([d, I, text]) => <ToolButton key={d} label={text} active={device === d} onClick={() => setDevice(d)}><I className="ecx-icon" /></ToolButton>)}
|
|
240
|
-
</div>
|
|
240
|
+
<DeviceSwitcher />
|
|
241
241
|
{!p.distractionFree && <ToolButton label={labels.settings} active={right} onClick={() => setRight(!right)}><PanelRight className="ecx-icon" /></ToolButton>}
|
|
242
242
|
{actions}
|
|
243
243
|
<MoreMenu extra={menuExtra} />
|
|
@@ -252,7 +252,7 @@ function EditorShell({ className, onSave, header, actions, menuExtra, canvasBefo
|
|
|
252
252
|
{p.fixedToolbar && p.mode === "visual" && <div className="ecx-fixed-toolbar"><BlockToolbar placement="fixed" /></div>}
|
|
253
253
|
<div className="ecx-body">
|
|
254
254
|
{left && !p.distractionFree && <aside className="ecx-left">{left === "inserter" ? <InserterPanel onClose={() => setLeft(null)} /> : <ListView />}</aside>}
|
|
255
|
-
<main className="ecx-main">{p.mode === "code" ? <CodeEditor /> : <Canvas
|
|
255
|
+
<main className="ecx-main">{p.mode === "code" ? <CodeEditor /> : <Canvas before={canvasBefore} />}</main>
|
|
256
256
|
{right && !p.distractionFree && <aside className="ecx-right"><Inspector blockStyles={blockStyles} /></aside>}
|
|
257
257
|
</div>
|
|
258
258
|
{p.showBreadcrumbs && !p.distractionFree && p.mode === "visual" && <Breadcrumbs />}
|
|
@@ -261,6 +261,18 @@ function EditorShell({ className, onSave, header, actions, menuExtra, canvasBefo
|
|
|
261
261
|
);
|
|
262
262
|
}
|
|
263
263
|
|
|
264
|
+
/** Chọn khổ màn hình đang soạn (máy tính / máy tính bảng / điện thoại): khung soạn và tab Kiểu dáng cùng theo. */
|
|
265
|
+
export function DeviceSwitcher() {
|
|
266
|
+
const { ui, labels } = useEditor();
|
|
267
|
+
useUiTick();
|
|
268
|
+
return (
|
|
269
|
+
<div className="ecx-tool-group" role="group" aria-label={labels.devices}>
|
|
270
|
+
{([["desktop", Monitor, labels.deviceDesktop], ["tablet", Tablet, labels.deviceTablet], ["mobile", Smartphone, labels.deviceMobile]] as const).map(([d, I, text]) =>
|
|
271
|
+
<ToolButton key={d} label={text} active={ui.device === d} aria-pressed={ui.device === d} onClick={() => ui.setDevice(d)}><I className="ecx-icon" /></ToolButton>)}
|
|
272
|
+
</div>
|
|
273
|
+
);
|
|
274
|
+
}
|
|
275
|
+
|
|
264
276
|
/** Bật / tắt hiện template quanh trang (khi có template bao quanh). */
|
|
265
277
|
function ZoomToggle() {
|
|
266
278
|
const { ui, labels } = useEditor();
|
|
@@ -292,7 +304,9 @@ export function EditorOverlays() {
|
|
|
292
304
|
return (
|
|
293
305
|
<>
|
|
294
306
|
<BlockToolbar />
|
|
307
|
+
<BlockContextMenu />
|
|
295
308
|
<InserterPopover />
|
|
309
|
+
<SectionAdder />
|
|
296
310
|
<AiWrite />
|
|
297
311
|
<DropIndicator />
|
|
298
312
|
<LiveRegion />
|
package/src/v2/index.ts
CHANGED
|
@@ -3,9 +3,9 @@
|
|
|
3
3
|
* khung soạn là iframe mang CSS của website, sửa header/footer ngay trong template, một lịch sử hoàn tác xuyên tài liệu,
|
|
4
4
|
* mỗi khối chữ là một ProseMirror nhỏ (gõ tiếng Việt ổn định). Đọc/ghi đúng định dạng của @ecomcx/ecomweb-content.
|
|
5
5
|
*/
|
|
6
|
-
export { BlockEditor, EditorProvider, EditorOverlays, saveAll, blocksFromContent, contentFromBlocks, splitContent, type BlockEditorProps, type EditorProviderProps } from "./editor";
|
|
6
|
+
export { BlockEditor, DeviceSwitcher, EditorProvider, EditorOverlays, saveAll, blocksFromContent, contentFromBlocks, splitContent, type BlockEditorProps, type EditorProviderProps } from "./editor";
|
|
7
7
|
export { Canvas, DEVICE_WIDTH, type CanvasProps, type Device } from "./canvas/canvas";
|
|
8
|
-
export { BlockToolbar, DropIndicator, ToolButton, Dropdown, MenuItem } from "./ui/toolbar";
|
|
8
|
+
export { BlockToolbar, BlockContextMenu, DropIndicator, ToolButton, Dropdown, MenuItem } from "./ui/toolbar";
|
|
9
9
|
export { InserterPanel, InserterPopover, rankOptions, useInsertOptions, type InsertOption } from "./ui/inserter";
|
|
10
10
|
export { Inspector } from "./ui/inspector";
|
|
11
11
|
export { AttrForm } from "./ui/attr-form";
|
|
@@ -30,7 +30,7 @@ export { registerBindingSource, unregisterBindingSource, bindingSources, Binding
|
|
|
30
30
|
export { storeAnimation as registerAnimation, dropAnimation as unregisterAnimation, pluginAnimations, type MotionEffect } from "../shared/animation-store";
|
|
31
31
|
export { defineBlock, type BlockDefinition } from "@ecomcx/ecomweb-content";
|
|
32
32
|
export { registerBlock, unregisterBlock, registeredBlocks, type RegisterBlockOptions } from "../shared/block-defs";
|
|
33
|
-
export { registerBlockPanel, unregisterBlockPanel, blockPanels, type BlockPanel, type BlockPanelProps } from "../shared/panel-store";
|
|
33
|
+
export { registerBlockPanel, unregisterBlockPanel, blockPanels, registerBlockAction, unregisterBlockAction, onBlockReady, registerBlockAssets, type BlockPanel, type BlockPanelProps, type BlockAction, type BlockActionContext, type BlockReadyFn, type BlockAsset } from "../shared/panel-store";
|
|
34
34
|
export { registerPattern, unregisterPattern, registeredPatterns, registerCorePatterns, patternNodes, PATTERN_CATEGORIES, type Pattern } from "../shared/patterns";
|
|
35
35
|
export { viLabels, enLabels, labelsLegacy, type EditorLabels } from "../shared/labels";
|
|
36
36
|
export { StylePanel } from "../shared/style-panel";
|
package/src/v2/ui/attr-hints.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { ICON_NAMES } from "@ecomcx/ecomweb-content";
|
|
1
2
|
import { format, messages } from "../../i18n";
|
|
2
3
|
import type { ChoiceKind } from "../core/host";
|
|
3
4
|
|
|
@@ -118,7 +119,20 @@ export const ATTR_HINTS: Record<string, AttrHint> = {
|
|
|
118
119
|
"loginout.logoutText": { label: true },
|
|
119
120
|
"pageList.parentId": { label: true },
|
|
120
121
|
"archives.showCount": { label: true },
|
|
121
|
-
"icon.name": { control: "select", options: [
|
|
122
|
+
"icon.name": { control: "select", options: [...ICON_NAMES] },
|
|
123
|
+
"iconBox.icon": { control: "select", options: [...ICON_NAMES] },
|
|
124
|
+
"iconBox.position": { control: "segmented", label: true, options: ["top", "left"] },
|
|
125
|
+
"iconBox.level": { control: "select", options: levels(2, 6) },
|
|
126
|
+
"imageBox.level": { control: "select", options: levels(2, 6) },
|
|
127
|
+
"imageBox.src": { label: true },
|
|
128
|
+
"iconList.icon": { control: "select", options: [...ICON_NAMES] },
|
|
129
|
+
"iconList.layout": { control: "segmented", options: ["list", "inline"] },
|
|
130
|
+
"counter.start": { label: true },
|
|
131
|
+
"counter.prefix": { label: true },
|
|
132
|
+
"counter.separator": { control: "select", label: true, options: ["none", ",", ".", "space"] },
|
|
133
|
+
"counter.duration": { help: true },
|
|
134
|
+
"testimonial.src": { label: true },
|
|
135
|
+
"progressBar.value": { control: "range", label: true, min: 0, max: 100, step: 1, unit: "%" },
|
|
122
136
|
"languageSwitcher.display": { control: "segmented", options: ["inline", "dropdown"] },
|
|
123
137
|
"postTerms.taxonomy": { control: "choice", choice: { kind: "taxonomy" } },
|
|
124
138
|
"query.postType": { control: "choice", choice: { kind: "postType" }, when: notInherit },
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { normalizeStyle, type BlockBackground, type BlockStyle, type Device } from "@ecomcx/ecomweb-content";
|
|
2
|
+
import { useState } from "react";
|
|
3
|
+
import { useEditor } from "../context";
|
|
4
|
+
import { useMsgs } from "../i18n";
|
|
5
|
+
import { ColorInput } from "./color-field";
|
|
6
|
+
import { Row, Section, Seg, cx } from "./style-controls";
|
|
7
|
+
|
|
8
|
+
/** Điểm lấy nét chọn nhanh: lưới 3×3 (trên-trái … dưới-phải). */
|
|
9
|
+
const POSITIONS = ["0% 0%", "50% 0%", "100% 0%", "0% 50%", "50% 50%", "100% 50%", "0% 100%", "50% 100%", "100% 100%"];
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Mục "Ảnh nền" của tab Kiểu dáng (attrs.style.background, @ecomcx/ecomweb-content 1.22): ảnh từ thư viện media (hoặc dán URL),
|
|
13
|
+
* ảnh / cách phủ / điểm lấy nét riêng theo khổ màn hình đang chọn, lặp, cố định khi cuộn, lớp phủ màu + độ mờ.
|
|
14
|
+
*/
|
|
15
|
+
export function BackgroundPanel({ style: raw, onChange, device }: { style: unknown; onChange(style: BlockStyle | null): void; device: Device }) {
|
|
16
|
+
const { host } = useEditor();
|
|
17
|
+
const t = useMsgs("background");
|
|
18
|
+
const style: BlockStyle = normalizeStyle(raw) ?? {};
|
|
19
|
+
const bg: BlockBackground = style.background ?? {};
|
|
20
|
+
const [url, setUrl] = useState("");
|
|
21
|
+
|
|
22
|
+
const commit = (next: Record<string, unknown> | undefined) => onChange(normalizeStyle({ ...style, background: next }) ?? null);
|
|
23
|
+
const set = (patch: Record<string, unknown>) => commit({ ...bg, ...patch });
|
|
24
|
+
/** Giá trị theo khổ đang chọn (ảnh, cách phủ, điểm lấy nét). */
|
|
25
|
+
const setAt = (k: "image" | "size" | "position", v: string | undefined) => {
|
|
26
|
+
const r: Record<string, string | undefined> = { ...(bg[k] ?? {}) };
|
|
27
|
+
if (v) r[device] = v; else delete r[device];
|
|
28
|
+
set({ [k]: Object.keys(r).length ? r : undefined });
|
|
29
|
+
};
|
|
30
|
+
const image = bg.image?.[device];
|
|
31
|
+
const inherited = device === "mobile" ? bg.image?.tablet ?? bg.image?.base : device === "tablet" ? bg.image?.base : undefined;
|
|
32
|
+
const pick = async () => {
|
|
33
|
+
const [item] = (await host.media?.pick({ kind: "image", multiple: false })) ?? [];
|
|
34
|
+
if (item) setAt("image", item.sizes?.large?.url ?? item.url);
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
return (
|
|
38
|
+
<Section title={t.title} modified={!!style.background} onReset={() => commit(undefined)} defaultOpen={!!style.background}>
|
|
39
|
+
<Row label={t.image} device={device}>
|
|
40
|
+
<div className="ecx-bg-image">
|
|
41
|
+
{(image ?? inherited) && <img src={image ?? inherited} alt="" className={cx("ecx-bg-thumb", !image && "is-inherited")} style={{ objectPosition: bg.position?.[device] ?? bg.position?.base ?? "50% 50%" }} />}
|
|
42
|
+
<div className="ecx-bg-actions">
|
|
43
|
+
{host.media && <button type="button" className="ecx-btn" onClick={pick}>{image ? t.replace : t.choose}</button>}
|
|
44
|
+
{image && <button type="button" className="ecx-btn" onClick={() => setAt("image", undefined)}>{t.remove}</button>}
|
|
45
|
+
</div>
|
|
46
|
+
{!host.media && (
|
|
47
|
+
<input className="ecx-input" value={url} placeholder="https://…" aria-label={t.url}
|
|
48
|
+
onChange={(e) => setUrl(e.target.value)} onBlur={() => { setAt("image", url.trim() || undefined); setUrl(""); }} />
|
|
49
|
+
)}
|
|
50
|
+
{inherited && !image && <p className="ecx-muted">{t.inherited}</p>}
|
|
51
|
+
</div>
|
|
52
|
+
</Row>
|
|
53
|
+
{bg.image && (
|
|
54
|
+
<>
|
|
55
|
+
<Row label={t.size} device={device}>
|
|
56
|
+
<Seg label={t.size} value={bg.size?.[device]} onChange={(v) => setAt("size", v)}
|
|
57
|
+
options={[["cover", t.cover, t.cover_help], ["contain", t.contain, t.contain_help], ["auto", t.auto, t.auto_help]]} />
|
|
58
|
+
</Row>
|
|
59
|
+
<Row label={t.focal} device={device}>
|
|
60
|
+
<div role="radiogroup" aria-label={t.focal} className="ecx-bg-focal">
|
|
61
|
+
{POSITIONS.map((p) => (
|
|
62
|
+
<button key={p} type="button" role="radio" aria-checked={(bg.position?.[device] ?? (device === "base" ? "50% 50%" : undefined)) === p} title={p} aria-label={p}
|
|
63
|
+
className={cx("ecx-bg-focal-dot", (bg.position?.[device] ?? (device === "base" ? "50% 50%" : undefined)) === p && "is-active")}
|
|
64
|
+
onClick={() => setAt("position", p === "50% 50%" && device === "base" ? undefined : p)} />
|
|
65
|
+
))}
|
|
66
|
+
</div>
|
|
67
|
+
</Row>
|
|
68
|
+
<label className="ecx-check"><input type="checkbox" checked={!!bg.repeat} onChange={(e) => set({ repeat: e.target.checked || undefined })} /> {t.repeat}</label>
|
|
69
|
+
<label className="ecx-check"><input type="checkbox" checked={!!bg.fixed} onChange={(e) => set({ fixed: e.target.checked || undefined })} /> {t.fixed}</label>
|
|
70
|
+
</>
|
|
71
|
+
)}
|
|
72
|
+
<Row label={t.overlay}>
|
|
73
|
+
<ColorInput label={t.overlay} value={bg.overlay} onChange={(v) => set({ overlay: v, overlayOpacity: v ? bg.overlayOpacity : undefined })} />
|
|
74
|
+
</Row>
|
|
75
|
+
{bg.overlay && (
|
|
76
|
+
<Row label={`${t.opacity}: ${bg.overlayOpacity ?? 50}%`}>
|
|
77
|
+
<input type="range" min={0} max={100} step={5} value={bg.overlayOpacity ?? 50} aria-label={t.opacity}
|
|
78
|
+
onChange={(e) => set({ overlayOpacity: Number(e.target.value) === 50 ? undefined : Number(e.target.value) })} />
|
|
79
|
+
</Row>
|
|
80
|
+
)}
|
|
81
|
+
</Section>
|
|
82
|
+
);
|
|
83
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** Chép / dán kiểu dáng (chỉ `attrs.style`) + vị trí menu chuột phải. */
|
|
2
|
+
|
|
3
|
+
// shortcut: chỉ nhớ trong phiên (bộ nhớ của trang admin, giữ khi chuyển bài trong SPA), mất khi tải lại — cần chép giữa tab thì chuyển sang localStorage.
|
|
4
|
+
let copied: { style?: Record<string, unknown> } | null = null;
|
|
5
|
+
|
|
6
|
+
export function copyStyle(attrs: Record<string, unknown>) {
|
|
7
|
+
const s = attrs.style;
|
|
8
|
+
copied = { style: s && typeof s === "object" ? structuredClone(s as Record<string, unknown>) : undefined };
|
|
9
|
+
}
|
|
10
|
+
export const hasCopiedStyle = () => copied !== null;
|
|
11
|
+
/** Thuộc tính để dán (bản sao mới mỗi lần); khối nguồn không có kiểu dáng → dán = bỏ kiểu dáng. null = chưa chép. */
|
|
12
|
+
export const pastedStyle = (): { style: Record<string, unknown> | undefined } | null => copied && { style: copied.style && structuredClone(copied.style) };
|
|
13
|
+
|
|
14
|
+
/** Góc trên-trái của menu (w×h) mở tại (x, y): sát mép phải / dưới thì lật sang trái / lên trên, luôn cách mép 8px. */
|
|
15
|
+
export function menuPosition(x: number, y: number, w: number, h: number, vw: number, vh: number) {
|
|
16
|
+
const left = x + w > vw - 8 ? x - w : x;
|
|
17
|
+
const top = y + h > vh - 8 ? y - h : y;
|
|
18
|
+
return { left: Math.round(Math.max(8, Math.min(left, vw - 8 - w))), top: Math.round(Math.max(8, Math.min(top, vh - 8 - h))) };
|
|
19
|
+
}
|
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
|
))}
|