@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
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { CORE_NODES, FORM_FIELD_NAME, blockShell } from "@ecomcx/ecomweb-content";
|
|
2
|
+
import { ClipboardList, TextCursorInput } from "lucide-react";
|
|
3
|
+
import { useEffect, type CSSProperties } from "react";
|
|
4
|
+
import { InnerBlocks } from "../canvas/block-list";
|
|
5
|
+
import { makeBlock } from "../core/model";
|
|
6
|
+
import type { BlockEditProps, BlockType } from "../core/registry";
|
|
7
|
+
import { useMsgs } from "../i18n";
|
|
8
|
+
import { messages } from "../../i18n";
|
|
9
|
+
import { RichText } from "../text/rich-text";
|
|
10
|
+
import { Field } from "../ui/attr-form";
|
|
11
|
+
import { useEditor } from "../context";
|
|
12
|
+
|
|
13
|
+
const cx = (...c: unknown[]) => c.filter((x): x is string => typeof x === "string" && x !== "").join(" ");
|
|
14
|
+
const merge = (bp: BlockEditProps["blockProps"], className: string, style?: CSSProperties) => ({ ...bp, className: cx(bp.className, className), style: { ...(bp.style ?? {}), ...style } });
|
|
15
|
+
/** Mã form: máy chủ tìm lại định nghĩa form (các ô) theo mã này trong trang / template chứa nó. */
|
|
16
|
+
export const newFormId = () => `f_${Math.random().toString(36).slice(2, 10)}`;
|
|
17
|
+
const optionsOf = (a: Record<string, unknown>): string[] => (Array.isArray(a.options) ? a.options.filter((x): x is string => typeof x === "string") : []);
|
|
18
|
+
|
|
19
|
+
/** Tên ô hợp lệ (khoá trong bài gửi) từ nhãn: bỏ dấu, chữ thường, gạch dưới. */
|
|
20
|
+
export function fieldNameFrom(label: string, taken: string[] = []): string {
|
|
21
|
+
const base = label.normalize("NFD").replace(/[̀-ͯ]/g, "").replace(/đ/gi, "d").toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "").replace(/^(\d)/, "f_$1").slice(0, 32) || "field";
|
|
22
|
+
let name = FORM_FIELD_NAME.test(base) ? base : "field", n = 2;
|
|
23
|
+
while (taken.includes(name)) name = `${base}_${n++}`;
|
|
24
|
+
return name;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function FormEdit({ block, blockProps, setAttrs, editable }: BlockEditProps) {
|
|
28
|
+
const t = useMsgs("blocks");
|
|
29
|
+
const a = block.attrs;
|
|
30
|
+
// Mẫu (pattern) chèn vào chưa có mã: tạo một lần để máy chủ nhận ra form này
|
|
31
|
+
useEffect(() => { if (editable && !a.formId) setAttrs({ formId: newFormId() }); }, [editable, a.formId, setAttrs]);
|
|
32
|
+
return (
|
|
33
|
+
<div {...merge(blockProps, "ecx-form-blocks")} data-form-id={String(a.formId ?? "")}>
|
|
34
|
+
<InnerBlocks parent={block} />
|
|
35
|
+
<div className="ecx-form-actions">
|
|
36
|
+
<span className={blockShell("button", { variant: "primary" })?.className} style={blockShell("button", { variant: "primary" })?.style as CSSProperties} role="presentation">
|
|
37
|
+
<RichText blockId={block.id} field="submitText" tagName="span" value={String(a.submitText ?? "")} onChange={(v) => setAttrs({ submitText: v })} placeholder={t.formSubmit} placeholderAlways editable={editable} />
|
|
38
|
+
</span>
|
|
39
|
+
</div>
|
|
40
|
+
</div>
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Ô nhập trên khung soạn: đúng markup website (nhãn + ô), ô bị khoá — sửa nhãn ngay trên ô, phần còn lại ở bảng cài đặt. */
|
|
45
|
+
function FieldEdit({ block, blockProps, setAttrs, editable }: BlockEditProps) {
|
|
46
|
+
const t = useMsgs("blocks");
|
|
47
|
+
const { store } = useEditor();
|
|
48
|
+
const a = block.attrs;
|
|
49
|
+
// Tên ô = khoá trong bài gửi: phải hợp lệ và không trùng ô đứng trước trong cùng form (chèn hai ô cùng loại, chép / dán ô)
|
|
50
|
+
const siblings = (store.locate(block.id)?.parent?.content ?? []).filter((b) => b.type === "formField");
|
|
51
|
+
const sibKey = siblings.map((b) => `${b.id}:${String(b.attrs.name ?? "")}`).join("|");
|
|
52
|
+
useEffect(() => {
|
|
53
|
+
if (!editable) return;
|
|
54
|
+
const name = String(a.name ?? "");
|
|
55
|
+
const before = siblings.slice(0, siblings.findIndex((b) => b.id === block.id)).map((b) => String(b.attrs.name ?? ""));
|
|
56
|
+
if (!FORM_FIELD_NAME.test(name) || before.includes(name)) setAttrs({ name: fieldNameFrom(name || String(a.label ?? ""), siblings.filter((b) => b.id !== block.id).map((b) => String(b.attrs.name ?? ""))) });
|
|
57
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
58
|
+
}, [editable, a.name, sibKey]);
|
|
59
|
+
const kind = String(a.kind ?? "text");
|
|
60
|
+
const label = <RichText blockId={block.id} field="label" tagName="span" value={String(a.label ?? "")} onChange={(v) => setAttrs({ label: v })} placeholder={t.fieldLabel} placeholderAlways editable={editable} />;
|
|
61
|
+
const star = a.required ? <span className="ecx-field-required" aria-hidden> *</span> : null;
|
|
62
|
+
const opts = optionsOf(a);
|
|
63
|
+
const ph = String(a.placeholder ?? "");
|
|
64
|
+
const check = kind === "checkbox" || kind === "consent";
|
|
65
|
+
return (
|
|
66
|
+
<div {...merge(blockProps, cx("ecx-field", `is-${kind}`, a.width === "half" && "is-half", check && "is-check"))}>
|
|
67
|
+
{check ? <label><input type="checkbox" disabled tabIndex={-1} /> <span>{label}{star}</span></label> : <label>{label}{star}</label>}
|
|
68
|
+
{kind === "textarea" ? <textarea disabled tabIndex={-1} placeholder={ph} />
|
|
69
|
+
: kind === "select" ? <select disabled tabIndex={-1}><option>{opts[0] ?? ph ?? "—"}</option></select>
|
|
70
|
+
: kind === "radio" ? <div className="ecx-field-options">{(opts.length ? opts : ["…"]).map((o, i) => <label key={i}><input type="radio" disabled tabIndex={-1} /> {o}</label>)}</div>
|
|
71
|
+
: check ? null
|
|
72
|
+
: <input disabled tabIndex={-1} placeholder={ph} type={kind === "number" ? "number" : kind === "date" ? "date" : "text"} />}
|
|
73
|
+
{a.help ? <span className="ecx-field-help">{String(a.help)}</span> : null}
|
|
74
|
+
</div>
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Bảng cài đặt thêm của ô: danh sách lựa chọn (mỗi dòng một lựa chọn) cho ô chọn / chọn một, và tên ô (khoá trong bài gửi). */
|
|
79
|
+
function FieldInspector({ attrs, setAttrs }: BlockEditProps) {
|
|
80
|
+
const t = useMsgs("blocks");
|
|
81
|
+
const kind = String(attrs.kind ?? "text");
|
|
82
|
+
const name = String(attrs.name ?? "");
|
|
83
|
+
return (
|
|
84
|
+
<>
|
|
85
|
+
{(kind === "select" || kind === "radio") && (
|
|
86
|
+
<Field label={t.fieldOptions}>
|
|
87
|
+
<textarea className="ecx-input" rows={4} value={optionsOf(attrs).join("\n")} data-field-options
|
|
88
|
+
onChange={(e) => setAttrs({ options: e.target.value.split("\n").map((s) => s.trim()).filter(Boolean).slice(0, 30) })} />
|
|
89
|
+
</Field>
|
|
90
|
+
)}
|
|
91
|
+
{name && !FORM_FIELD_NAME.test(name) && <p className="ecx-muted" role="alert">{t.fieldNameInvalid}</p>}
|
|
92
|
+
</>
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const spec = (name: string) => CORE_NODES[name]?.attrs;
|
|
97
|
+
|
|
98
|
+
/** Khối form cơ bản; `lang` = ngôn ngữ của trình soạn (nhãn mặc định của ô mới). */
|
|
99
|
+
export function formBlocks(lang?: string): BlockType[] {
|
|
100
|
+
const m = messages("blocks", lang) as Record<string, string>;
|
|
101
|
+
const field = (kind: string, name: string, label: string, extra: Record<string, unknown> = {}) => makeBlock("formField", { kind, name, label, ...extra });
|
|
102
|
+
const KINDS: Array<[string, string, string, Record<string, unknown>?]> = [
|
|
103
|
+
["text", "text", m.fieldText], ["email", "email", m.fieldEmail], ["tel", "phone", m.fieldPhone], ["textarea", "message", m.fieldMessage],
|
|
104
|
+
["select", "topic", m.fieldSelect, { options: [m.option1, m.option2] }], ["radio", "choice", m.fieldRadio, { options: [m.option1, m.option2] }],
|
|
105
|
+
["checkbox", "subscribe", m.fieldCheckbox], ["consent", "consent", m.fieldConsent, { required: true }], ["number", "quantity", m.fieldNumber], ["date", "date", m.fieldDate],
|
|
106
|
+
];
|
|
107
|
+
return [
|
|
108
|
+
{
|
|
109
|
+
name: "form", title: "Form", icon: ClipboardList, category: "widgets", keywords: "form lien he contact dang ky gui bieu mau", kind: "container", edit: FormEdit,
|
|
110
|
+
attributes: { ...spec("form"), formId: { type: "string" } },
|
|
111
|
+
structure: { allowedChildren: ["formField", "paragraph", "heading"] },
|
|
112
|
+
create: () => makeBlock("form", { formId: newFormId() }, [
|
|
113
|
+
field("text", "name", m.fieldName, { required: true, width: "half" }),
|
|
114
|
+
field("tel", "phone", m.fieldPhone, { required: true, width: "half" }),
|
|
115
|
+
field("email", "email", m.fieldEmail),
|
|
116
|
+
field("textarea", "message", m.fieldMessage, { required: true }),
|
|
117
|
+
]),
|
|
118
|
+
supports: { style: true, anchor: true, className: true },
|
|
119
|
+
},
|
|
120
|
+
{
|
|
121
|
+
name: "formField", title: "Ô nhập", icon: TextCursorInput, category: "widgets", keywords: "o nhap truong field input", kind: "atom", edit: FieldEdit, inspector: FieldInspector,
|
|
122
|
+
// Chỉ hiện trong trình chèn khi đang ở trong một form (structure.parents)
|
|
123
|
+
attributes: spec("formField"), structure: { parents: ["form"] },
|
|
124
|
+
create: (attrs) => field("text", "text", m.fieldText, attrs ?? {}),
|
|
125
|
+
variations: KINDS.map(([kind, name, title, extra]) => ({ name: kind, title, attrs: { kind }, create: () => field(kind, name, title, extra), isActive: (a) => (a.kind ?? "text") === kind })),
|
|
126
|
+
supports: { style: true, className: true }, summary: (a) => a.label,
|
|
127
|
+
},
|
|
128
|
+
];
|
|
129
|
+
}
|
package/src/v2/blocks/index.ts
CHANGED
|
@@ -5,6 +5,8 @@ import { layoutBlocks } from "./layout";
|
|
|
5
5
|
import { mediaBlocks } from "./media";
|
|
6
6
|
import { textBlocks } from "./text";
|
|
7
7
|
import { themeBlocks } from "./theme";
|
|
8
|
+
import { formBlocks } from "./form";
|
|
9
|
+
import { blockDescription } from "../ui/block-descriptions";
|
|
8
10
|
|
|
9
11
|
/** Tên khối theo ngôn ngữ giao diện (khối có nhãn trong bộ chữ). */
|
|
10
12
|
const TITLE_KEYS: Partial<Record<string, keyof V2Labels>> = {
|
|
@@ -16,13 +18,13 @@ const TITLE_KEYS: Partial<Record<string, keyof V2Labels>> = {
|
|
|
16
18
|
|
|
17
19
|
export function coreBlockTypes(labels: V2Labels): BlockType[] {
|
|
18
20
|
const names = messages("blockTitles", labels.lang);
|
|
19
|
-
return [...textBlocks(), ...layoutBlocks(), ...mediaBlocks(), ...themeBlocks()].map((t) => {
|
|
21
|
+
return [...textBlocks(), ...layoutBlocks(), ...mediaBlocks(), ...formBlocks(labels.lang), ...themeBlocks()].map((t) => {
|
|
20
22
|
const key = TITLE_KEYS[t.name];
|
|
21
23
|
const str = (v: unknown) => (typeof v === "string" ? v : undefined);
|
|
22
24
|
const title = key ? String(labels[key]) : str(names[t.name]) ?? t.title;
|
|
23
25
|
// Biến thể đứng riêng (Hàng ngang / Xếp dọc / Lưới) theo ngôn ngữ
|
|
24
26
|
const variations = t.variations?.map((v) => { const vt = str(names[`${t.name}/${v.name}`]); return vt ? { ...v, title: vt } : v; });
|
|
25
|
-
return { ...t, title, variations };
|
|
27
|
+
return { ...t, title, variations, description: t.description ?? blockDescription(t.name, labels.lang) };
|
|
26
28
|
});
|
|
27
29
|
}
|
|
28
30
|
|
|
@@ -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
|
@@ -95,6 +95,13 @@ export const ATTR_HINTS: Record<string, AttrHint> = {
|
|
|
95
95
|
"gallery.imageCrop": { label: true },
|
|
96
96
|
"gallery.lightbox": { label: true },
|
|
97
97
|
"countdown.expiredText": { label: true },
|
|
98
|
+
// 1.27: form cơ bản
|
|
99
|
+
"form.formId": { control: "hidden" },
|
|
100
|
+
"form.notifyEmail": { help: true },
|
|
101
|
+
"formField.kind": { control: "select", options: ["text", "email", "tel", "textarea", "select", "radio", "checkbox", "consent", "number", "date"] },
|
|
102
|
+
"formField.name": { label: true, help: true },
|
|
103
|
+
"formField.label": { label: true, help: true },
|
|
104
|
+
"formField.width": { control: "segmented", options: ["full", "half"] },
|
|
98
105
|
"search.showLabel": { label: true },
|
|
99
106
|
"search.buttonPosition": { control: "segmented", label: true, options: ["right", "left", "below"] },
|
|
100
107
|
"postAuthor.showName": { label: true },
|
|
@@ -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
|
+
}
|