@ecomcx/ecomweb-editor 1.18.0 → 1.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +25 -7
- package/src/index.ts +26 -25
- package/src/{ask.tsx → legacy/ask.tsx} +2 -2
- package/src/{blockMeta.ts → legacy/block-meta.ts} +1 -1
- package/src/{blocks.tsx → legacy/blocks.tsx} +8 -32
- package/src/{content.ts → legacy/content.ts} +1 -1
- package/src/{handle.tsx → legacy/drag-handle.tsx} +3 -3
- package/src/{dynamic.tsx → legacy/dynamic.tsx} +7 -3
- package/src/{Editor.tsx → legacy/editor.tsx} +9 -9
- package/src/{extensions.ts → legacy/extensions.ts} +1 -1
- package/src/legacy/insert-pattern.ts +13 -0
- package/src/{inserter.tsx → legacy/inserter.tsx} +6 -5
- package/src/{inspector.tsx → legacy/inspector.tsx} +7 -7
- package/src/{layoutUi.tsx → legacy/layout-ui.tsx} +6 -5
- package/src/{layout.tsx → legacy/layout.tsx} +2 -2
- package/src/{media.ts → legacy/media.ts} +1 -1
- package/src/{nodes.tsx → legacy/nodes.tsx} +2 -2
- package/src/{outline.tsx → legacy/outline.tsx} +4 -4
- package/src/legacy/panels.ts +22 -0
- package/src/{rank.ts → legacy/rank.ts} +2 -2
- package/src/{registry.ts → legacy/registry.ts} +1 -1
- package/src/{handles.tsx → legacy/resize-handles.tsx} +1 -1
- package/src/{styleattr.ts → legacy/style-attr.ts} +15 -1
- package/src/{synced.tsx → legacy/synced.tsx} +2 -2
- package/src/{toolbar.tsx → legacy/toolbar.tsx} +7 -7
- package/src/{unknown.tsx → legacy/unknown.tsx} +1 -1
- package/src/shared/block-defs.ts +38 -0
- package/src/shared/color-swatch.tsx +19 -0
- package/src/{panels.ts → shared/panel-store.ts} +4 -21
- package/src/{patterns.ts → shared/patterns.ts} +0 -12
- package/src/{stylepanel.tsx → shared/style-panel.tsx} +2 -2
- package/src/{types.ts → shared/types.ts} +2 -0
- package/src/v2/blocks/compat.tsx +51 -0
- package/src/v2/blocks/index.ts +42 -0
- package/src/v2/blocks/layout.tsx +281 -0
- package/src/v2/blocks/media-actions.tsx +76 -0
- package/src/v2/blocks/media.tsx +234 -0
- package/src/v2/blocks/resize.tsx +111 -0
- package/src/v2/blocks/text.tsx +150 -0
- package/src/v2/blocks/theme.tsx +293 -0
- package/src/v2/blocks/tools.tsx +72 -0
- package/src/v2/canvas/block-list.tsx +216 -0
- package/src/v2/canvas/canvas-css.ts +131 -0
- package/src/v2/canvas/canvas.tsx +379 -0
- package/src/v2/canvas/dnd.ts +192 -0
- package/src/v2/context.tsx +146 -0
- package/src/v2/core/bindings.ts +64 -0
- package/src/v2/core/clipboard.ts +238 -0
- package/src/v2/core/host.ts +80 -0
- package/src/v2/core/model.ts +157 -0
- package/src/v2/core/ops.ts +151 -0
- package/src/v2/core/patterns.ts +10 -0
- package/src/v2/core/registry.ts +135 -0
- package/src/v2/core/store.ts +804 -0
- package/src/v2/core/structure.ts +106 -0
- package/src/v2/core/tables.ts +194 -0
- package/src/v2/editor.css +324 -0
- package/src/v2/editor.tsx +288 -0
- package/src/v2/index.ts +28 -0
- package/src/v2/labels.ts +349 -0
- package/src/v2/prefs.ts +69 -0
- package/src/v2/text/paste.ts +75 -0
- package/src/v2/text/rich-schema.ts +96 -0
- package/src/v2/text/rich-text.tsx +512 -0
- package/src/v2/ui/attr-form.tsx +182 -0
- package/src/v2/ui/attr-hints.ts +129 -0
- package/src/v2/ui/bindings.tsx +91 -0
- package/src/v2/ui/block-descriptions.ts +34 -0
- package/src/v2/ui/color-field.tsx +17 -0
- package/src/v2/ui/doc-title.tsx +45 -0
- package/src/v2/ui/inserter.tsx +300 -0
- package/src/v2/ui/inspector.tsx +85 -0
- package/src/v2/ui/layout-panel.tsx +159 -0
- package/src/v2/ui/list-view.tsx +65 -0
- package/src/v2/ui/options.tsx +242 -0
- package/src/v2/ui/style-controls.tsx +57 -0
- package/src/v2/ui/style-tab.tsx +158 -0
- package/src/v2/ui/toolbar.tsx +402 -0
- package/src/v2/ui/unit-controls.tsx +99 -0
- /package/src/{basic.tsx → legacy/basic.tsx} +0 -0
- /package/src/{blockops.ts → legacy/block-ops.ts} +0 -0
- /package/src/{boundary.tsx → legacy/boundary.tsx} +0 -0
- /package/src/{editor.css → legacy/editor.css} +0 -0
- /package/src/{insert.ts → legacy/insert.ts} +0 -0
- /package/src/{labels.ts → shared/labels.ts} +0 -0
- /package/src/{paste.ts → shared/paste.ts} +0 -0
- /package/src/{util.ts → shared/util.ts} +0 -0
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
import { AlignLeft, ArrowLeftRight, CalendarDays, ChevronsRight, Heading1, Copyright, FileText, Globe2, Image as ImageIcon, LayoutTemplate, ListOrdered, Menu, MessageSquare, PanelTop, Repeat2, Rows3, Search, SquareDashed, Tag, Type, User } from "lucide-react";
|
|
2
|
+
import { useCallback, useEffect, useMemo, useState, type CSSProperties, type ReactNode } from "react";
|
|
3
|
+
import { Block, DocBlocks, InnerBlocks, NestedDoc } from "../canvas/block-list";
|
|
4
|
+
import { DocScopeProvider, LoopPostContext, useDocScope, useDynamicData, useEditor, useEditorState } from "../context";
|
|
5
|
+
import type { DynamicPost, QueryArgs } from "../core/host";
|
|
6
|
+
import type { BNode } from "../core/model";
|
|
7
|
+
import { makeBlock } from "../core/model";
|
|
8
|
+
import type { BlockEditProps, BlockType } from "../core/registry";
|
|
9
|
+
|
|
10
|
+
const cx = (...c: unknown[]) => c.filter((x): x is string => typeof x === "string" && x !== "").join(" ");
|
|
11
|
+
const align = (a: Record<string, unknown>): CSSProperties | undefined => (typeof a.textAlign === "string" ? { textAlign: a.textAlign as CSSProperties["textAlign"] } : undefined);
|
|
12
|
+
const merge = (bp: BlockEditProps["blockProps"], className: string, style?: CSSProperties) => ({ ...bp, className: cx(bp.className, "ecx-dynamic", className), style: { ...(bp.style ?? {}), ...style } });
|
|
13
|
+
const TEXT_ALIGN = { type: "string" as const, enum: ["left", "center", "right", "justify"] };
|
|
14
|
+
|
|
15
|
+
/** Khối động: hiện dữ liệu thật do ứng dụng cung cấp (host.dynamic), không có thì hiện tên khối. */
|
|
16
|
+
const useDynamic = useDynamicData;
|
|
17
|
+
|
|
18
|
+
function SiteTitleEdit({ block, blockProps }: BlockEditProps) {
|
|
19
|
+
const d = useDynamic();
|
|
20
|
+
const level = Number(block.attrs.level) || 0;
|
|
21
|
+
const Tag = (level ? `h${Math.min(6, level)}` : "p") as "p";
|
|
22
|
+
return <Tag {...merge(blockProps, "ecx-site-title", align(block.attrs))}>{d.site?.title || "Site Title"}</Tag>;
|
|
23
|
+
}
|
|
24
|
+
function SiteTaglineEdit({ block, blockProps }: BlockEditProps) {
|
|
25
|
+
const d = useDynamic();
|
|
26
|
+
return <p {...merge(blockProps, "ecx-site-tagline", align(block.attrs))}>{d.site?.tagline || "Tagline"}</p>;
|
|
27
|
+
}
|
|
28
|
+
function SiteLogoEdit({ block, blockProps }: BlockEditProps) {
|
|
29
|
+
const d = useDynamic();
|
|
30
|
+
const w = Number(block.attrs.width) || 120;
|
|
31
|
+
return <div {...merge(blockProps, "ecx-site-logo")}>{d.site?.logo ? <img src={d.site.logo} alt="" width={w} draggable={false} /> : <span className="ecx-logo-placeholder" style={{ width: w }}><ImageIcon className="ecx-icon" /></span>}</div>;
|
|
32
|
+
}
|
|
33
|
+
/** Menu: cùng markup với website (theme-sdk) — nav.ecx-navigation-menu > ul > li > a, nút ☰ cho điện thoại. */
|
|
34
|
+
function NavigationEdit({ block, blockProps }: BlockEditProps) {
|
|
35
|
+
const d = useDynamic();
|
|
36
|
+
const { labels } = useEditor();
|
|
37
|
+
const location = String(block.attrs.location ?? "primary");
|
|
38
|
+
const items = d.menus?.[location];
|
|
39
|
+
const mobile = block.attrs.mobile !== false;
|
|
40
|
+
const vi = labels.lang === "vi";
|
|
41
|
+
if (!items?.length) {
|
|
42
|
+
return (
|
|
43
|
+
<div {...merge(blockProps, "ecx-navigation ecx-placeholder-block")}>
|
|
44
|
+
<span className="ecx-placeholder-title"><Menu className="ecx-icon" /> {vi ? "Menu" : "Menu"} · {location}</span>
|
|
45
|
+
<span className="ecx-placeholder-summary">{vi ? "Chưa có menu nào gán cho vị trí này — gán ở Giao diện › Menu, hoặc chọn vị trí khác trong bảng cài đặt." : "No menu is assigned to this location — assign one in Appearance › Menus, or pick another location."}</span>
|
|
46
|
+
</div>
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
const menu = <nav className="ecx-navigation-menu" aria-label={location}><ul>{items.map((it, i) => <li key={i}><a href={it.url} onClick={(e) => e.preventDefault()}>{it.title}</a></li>)}</ul></nav>;
|
|
50
|
+
return (
|
|
51
|
+
<div {...merge(blockProps, cx("ecx-navigation", `ecx-navigation-${block.attrs.orientation ?? "horizontal"}`, mobile && "has-mobile"))}>
|
|
52
|
+
<div className="ecx-navigation-items">{menu}</div>
|
|
53
|
+
{mobile && <details className="ecx-navigation-toggle"><summary aria-label={vi ? "Menu" : "Menu"}>☰</summary>{menu}</details>}
|
|
54
|
+
</div>
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
function SearchEdit({ block, blockProps }: BlockEditProps) {
|
|
58
|
+
return (
|
|
59
|
+
<div {...merge(blockProps, "ecx-search")}>
|
|
60
|
+
<form onSubmit={(e) => e.preventDefault()}><input type="search" placeholder={String(block.attrs.placeholder || "…")} readOnly tabIndex={-1} /> <button type="button" tabIndex={-1}>{String(block.attrs.buttonText || "🔍")}</button></form>
|
|
61
|
+
</div>
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
function CopyrightEdit({ block, blockProps }: BlockEditProps) {
|
|
65
|
+
const d = useDynamic();
|
|
66
|
+
return <p {...merge(blockProps, "ecx-copyright", align(block.attrs))}>© {new Date().getFullYear()} {String(block.attrs.text || d.site?.title || "")}</p>;
|
|
67
|
+
}
|
|
68
|
+
function LanguageEdit({ blockProps }: BlockEditProps) {
|
|
69
|
+
const d = useDynamic();
|
|
70
|
+
return <div {...merge(blockProps, "ecx-language-switcher")}>{(d.languages?.length ? d.languages : ["vi", "en"]).join(" · ")}</div>;
|
|
71
|
+
}
|
|
72
|
+
function PostTitleEdit({ block, blockProps }: BlockEditProps) {
|
|
73
|
+
const d = useDynamic();
|
|
74
|
+
const Tag = `h${Math.min(6, Math.max(1, Number(block.attrs.level) || 1))}` as "h1";
|
|
75
|
+
return <Tag {...merge(blockProps, "ecx-post-title", align(block.attrs))}>{d.post?.title || "Post Title"}</Tag>;
|
|
76
|
+
}
|
|
77
|
+
function PostExcerptEdit({ block, blockProps }: BlockEditProps) {
|
|
78
|
+
const d = useDynamic();
|
|
79
|
+
return <p {...merge(blockProps, "ecx-post-excerpt")}>{d.post?.excerpt || "Lorem ipsum dolor sit amet…"}{block.attrs.moreText ? <> <a className="ecx-more-link">{String(block.attrs.moreText)}</a></> : null}</p>;
|
|
80
|
+
}
|
|
81
|
+
function FeaturedImageEdit({ block, blockProps }: BlockEditProps) {
|
|
82
|
+
const d = useDynamic();
|
|
83
|
+
const ratio = block.attrs.aspect && block.attrs.aspect !== "auto" ? String(block.attrs.aspect) : undefined;
|
|
84
|
+
return (
|
|
85
|
+
<div {...merge(blockProps, "ecx-featured-image", { aspectRatio: ratio ?? (d.post?.image ? undefined : "16/9"), overflow: "hidden" })}>
|
|
86
|
+
{d.post?.image ? <img src={d.post.image} alt="" draggable={false} style={{ width: "100%", height: "100%", objectFit: "cover" }} /> : <span className="ecx-image-placeholder"><ImageIcon className="ecx-icon" /></span>}
|
|
87
|
+
</div>
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
function PostDateEdit({ block, blockProps }: BlockEditProps) {
|
|
91
|
+
const d = useDynamic();
|
|
92
|
+
return <p {...merge(blockProps, "ecx-post-date", align(block.attrs))}>{d.post?.date || new Date().toLocaleDateString()}</p>;
|
|
93
|
+
}
|
|
94
|
+
function PostAuthorEdit({ blockProps }: BlockEditProps) {
|
|
95
|
+
const d = useDynamic();
|
|
96
|
+
return <p {...merge(blockProps, "ecx-post-author")}>{d.post?.author || "Admin"}</p>;
|
|
97
|
+
}
|
|
98
|
+
function PostTermsEdit({ block, blockProps }: BlockEditProps) {
|
|
99
|
+
const d = useDynamic();
|
|
100
|
+
return <p {...merge(blockProps, "ecx-post-terms")}>{(d.post?.terms?.length ? d.post.terms : block.attrs.taxonomy === "post_tag" ? ["Thẻ A", "Thẻ B"] : ["Chuyên mục A", "Chuyên mục B"]).join(String(block.attrs.separator ?? ", "))}</p>;
|
|
101
|
+
}
|
|
102
|
+
function CommentsEdit({ blockProps }: BlockEditProps) {
|
|
103
|
+
const d = useDynamic();
|
|
104
|
+
return <div {...merge(blockProps, "ecx-comments")}><MessageSquare className="ecx-icon" /> {d.post?.comments ?? 0}</div>;
|
|
105
|
+
}
|
|
106
|
+
/** Tiêu đề trang lưu trữ / tìm kiếm (H1 của trang chuyên mục, thẻ, tác giả…). */
|
|
107
|
+
function QueryTitleEdit({ block, blockProps, labels }: BlockEditProps) {
|
|
108
|
+
const d = useDynamic();
|
|
109
|
+
const vi = labels.lang === "vi";
|
|
110
|
+
const Tag = `h${Math.min(6, Math.max(1, Number(block.attrs.level) || 1))}` as "h1";
|
|
111
|
+
const name = d.archive?.title ?? (vi ? "Tên chuyên mục" : "Category name");
|
|
112
|
+
return <Tag {...merge(blockProps, "ecx-query-title", align(block.attrs))}>{block.attrs.prefix ? (vi ? "Chuyên mục: " : "Category: ") : ""}{name}</Tag>;
|
|
113
|
+
}
|
|
114
|
+
function TermDescriptionEdit({ block, blockProps, labels }: BlockEditProps) {
|
|
115
|
+
const d = useDynamic();
|
|
116
|
+
return <div {...merge(blockProps, "ecx-term-description", align(block.attrs))}>{d.archive?.description || (labels.lang === "vi" ? "Mô tả của chuyên mục / thẻ đang xem." : "The description of the category / tag being viewed.")}</div>;
|
|
117
|
+
}
|
|
118
|
+
function BreadcrumbsEdit({ block, blockProps, labels }: BlockEditProps) {
|
|
119
|
+
const d = useDynamic();
|
|
120
|
+
const vi = labels.lang === "vi";
|
|
121
|
+
const sep = String(block.attrs.separator ?? "›");
|
|
122
|
+
const items = [...(block.attrs.showHome !== false ? [vi ? "Trang chủ" : "Home"] : []), vi ? "Chuyên mục" : "Category", ...(block.attrs.showCurrent !== false ? [d.post?.title || (vi ? "Trang hiện tại" : "Current page")] : [])];
|
|
123
|
+
return (
|
|
124
|
+
<nav {...(merge(blockProps, "ecx-breadcrumbs") as object)}>
|
|
125
|
+
<ol>{items.map((t, i) => <li key={i}>{i > 0 && <span className="ecx-breadcrumbs-sep" aria-hidden="true">{sep}</span>}{i < items.length - 1 ? <a>{t}</a> : <span>{t}</span>}</li>)}</ol>
|
|
126
|
+
</nav>
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
function PostNavigationEdit({ block, blockProps, labels }: BlockEditProps) {
|
|
130
|
+
const vi = labels.lang === "vi";
|
|
131
|
+
const titles = block.attrs.showTitle !== false;
|
|
132
|
+
return (
|
|
133
|
+
<nav {...(merge(blockProps, "ecx-post-navigation") as object)}>
|
|
134
|
+
<a className="ecx-post-navigation-prev"><span>{vi ? "Bài trước" : "Previous"}</span>{titles && <strong>{vi ? "Tiêu đề bài trước" : "Previous post title"}</strong>}</a>
|
|
135
|
+
<a className="ecx-post-navigation-next"><span>{vi ? "Bài sau" : "Next"}</span>{titles && <strong>{vi ? "Tiêu đề bài sau" : "Next post title"}</strong>}</a>
|
|
136
|
+
</nav>
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function PostContentEdit({ blockProps }: BlockEditProps) {
|
|
141
|
+
const { labels } = useEditor();
|
|
142
|
+
const scope = useDocScope();
|
|
143
|
+
const frameId = useEditorState((s) => s.frameId);
|
|
144
|
+
const rootId = useEditorState((s) => s.rootId);
|
|
145
|
+
// Trong template đang bao quanh trang: đây là chỗ sửa nội dung trang (tài liệu gốc, sửa được)
|
|
146
|
+
if (frameId && scope.docId === frameId) {
|
|
147
|
+
return (
|
|
148
|
+
<div {...merge(blockProps, "ecx-post-content ecx-frame-content")} data-ecx-editable-doc="">
|
|
149
|
+
<DocScopeProvider value={{ docId: rootId, mode: "default", depth: scope.depth + 1, chain: [...(scope.chain ?? []), rootId] }}><DocBlocks docId={rootId} /></DocScopeProvider>
|
|
150
|
+
</div>
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
return <div {...merge(blockProps, "ecx-post-content ecx-content-placeholder")}><FileText className="ecx-icon" /> {labels.lang === "vi" ? "Nội dung bài viết" : "Post content"}</div>;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function QueryEdit({ block, blockProps }: BlockEditProps) {
|
|
157
|
+
return <div {...merge(blockProps, "ecx-query")}><InnerBlocks parent={block} /></div>;
|
|
158
|
+
}
|
|
159
|
+
/** Thiết lập của khối query (mặc định giống website). */
|
|
160
|
+
export function queryArgs(a: Record<string, unknown>): QueryArgs {
|
|
161
|
+
return {
|
|
162
|
+
inherit: a.inherit !== false, postType: typeof a.postType === "string" && a.postType ? a.postType : "post",
|
|
163
|
+
perPage: Math.min(100, Math.max(1, Number(a.perPage) || 10)),
|
|
164
|
+
category: typeof a.category === "string" && a.category ? a.category : undefined, tag: typeof a.tag === "string" && a.tag ? a.tag : undefined,
|
|
165
|
+
orderBy: typeof a.orderBy === "string" ? a.orderBy : "date", order: a.order === "asc" ? "asc" : "desc",
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
/** Bài của danh sách: host.queryPosts theo thiết lập, không có thì bài mẫu (dynamic.posts). */
|
|
169
|
+
function useQueryPosts(q: QueryArgs): DynamicPost[] | undefined {
|
|
170
|
+
const { host } = useEditor();
|
|
171
|
+
const key = JSON.stringify(q);
|
|
172
|
+
const [posts, setPosts] = useState<{ key: string; list: DynamicPost[] } | null>(null);
|
|
173
|
+
useEffect(() => {
|
|
174
|
+
if (!host.queryPosts) return;
|
|
175
|
+
let alive = true;
|
|
176
|
+
const t = setTimeout(() => host.queryPosts!(q).then((list) => { if (alive) setPosts({ key, list }); }, () => { if (alive) setPosts({ key, list: [] }); }), 150);
|
|
177
|
+
return () => { alive = false; clearTimeout(t); };
|
|
178
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
179
|
+
}, [key, host]);
|
|
180
|
+
if (host.queryPosts) return posts?.list;
|
|
181
|
+
return host.dynamic?.posts;
|
|
182
|
+
}
|
|
183
|
+
/** Bản sao chỉ xem của khuôn (id riêng cho mỗi mục: không trùng ô gõ, không chọn được). */
|
|
184
|
+
const previewClone = (n: BNode, tag: string): BNode => ({ ...n, id: `${n.id}~${tag}`, content: n.content?.map((c) => previewClone(c, tag)) });
|
|
185
|
+
function PreviewBlocks({ nodes, tag }: { nodes: BNode[]; tag: string }) {
|
|
186
|
+
const scope = useDocScope();
|
|
187
|
+
const clones = useMemo(() => nodes.map((n) => previewClone(n, tag)), [nodes, tag]);
|
|
188
|
+
return <DocScopeProvider value={{ ...scope, mode: "disabled" }}>{clones.map((n) => <Block key={n.id} node={n} />)}</DocScopeProvider>;
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Khuôn mỗi bài: mỗi mục là một bài thật của danh sách; mục đang chọn sửa được (khối bài hiện dữ liệu của bài đó),
|
|
192
|
+
* các mục khác là bản xem trước — bấm vào để sửa khuôn ngay trên bài đó.
|
|
193
|
+
*/
|
|
194
|
+
function PostTemplateEdit({ block, blockProps, editable, labels }: BlockEditProps) {
|
|
195
|
+
const { store, ui } = useEditor();
|
|
196
|
+
// Khối cha (query) đổi thiết lập → vẽ lại (khối này không đổi tham chiếu)
|
|
197
|
+
const queryAttrs = useEditorState(useCallback(() => store.locate(block.id)?.parent?.attrs, [block.id, store])) ?? {};
|
|
198
|
+
const q = queryArgs(queryAttrs);
|
|
199
|
+
const posts = useQueryPosts(q);
|
|
200
|
+
const [active, setActive] = useState(0);
|
|
201
|
+
const grid = block.attrs.layout === "grid";
|
|
202
|
+
const cols = Math.min(6, Math.max(1, Number(block.attrs.columns) || 3));
|
|
203
|
+
const count = posts ? Math.max(1, Math.min(posts.length, q.perPage, 6)) : 3;
|
|
204
|
+
const current = Math.min(active, count - 1);
|
|
205
|
+
const vi = labels.lang === "vi";
|
|
206
|
+
return (
|
|
207
|
+
<ul {...(merge(blockProps, cx("ecx-post-template", grid && "is-grid"), grid ? { display: "grid", gridTemplateColumns: `repeat(${cols}, minmax(0, 1fr))`, gap: "1.5rem" } : undefined) as object)} data-ecx-posts={posts ? posts.length : ""}>
|
|
208
|
+
{posts && !posts.length && <li className="ecx-post ecx-post-none">{vi ? "Không có bài nào khớp thiết lập — khuôn vẫn sửa được:" : "No posts match these settings — the template is still editable:"}</li>}
|
|
209
|
+
{Array.from({ length: count }, (_, i) => {
|
|
210
|
+
const post = posts?.[i] ?? null;
|
|
211
|
+
if (i === current) return <li key="edit" className={cx("ecx-post", count > 1 && "is-active")}><LoopPostContext.Provider value={post}><InnerBlocks parent={block} /></LoopPostContext.Provider></li>;
|
|
212
|
+
return (
|
|
213
|
+
<li key={i} className="ecx-post ecx-post-preview" data-ecx-post-index={i} title={vi ? "Bấm để sửa khuôn trên bài này" : "Click to edit the template on this post"}
|
|
214
|
+
onMouseDownCapture={(e) => { if (!editable || ui.zoomOut || e.button !== 0) return; e.preventDefault(); e.stopPropagation(); setActive(i); }}>
|
|
215
|
+
<LoopPostContext.Provider value={post}><PreviewBlocks nodes={block.content ?? []} tag={`p${i}`} /></LoopPostContext.Provider>
|
|
216
|
+
</li>
|
|
217
|
+
);
|
|
218
|
+
})}
|
|
219
|
+
</ul>
|
|
220
|
+
);
|
|
221
|
+
}
|
|
222
|
+
function PaginationEdit({ blockProps }: BlockEditProps) {
|
|
223
|
+
return <nav {...(merge(blockProps, "ecx-pagination") as object)}>‹ 1 2 3 ›</nav>;
|
|
224
|
+
}
|
|
225
|
+
function QueryEmptyEdit({ block, blockProps }: BlockEditProps) {
|
|
226
|
+
return <div {...merge(blockProps, "ecx-query-empty")}><InnerBlocks parent={block} /></div>;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** Vỏ của tài liệu lồng (header/footer, mẫu đồng bộ): viền tím + nhãn, bấm đúp để sửa riêng. */
|
|
230
|
+
function NestedShell({ blockProps, className, tag = "div", label, docRef, onFocusEdit, children }: { blockProps: BlockEditProps["blockProps"]; className: string; tag?: string; label: ReactNode; docRef: { kind: string; ref: unknown }; onFocusEdit(docId: string): void; children?: ReactNode }) {
|
|
231
|
+
const Tag = tag as "div";
|
|
232
|
+
return (
|
|
233
|
+
<NestedDoc docRef={docRef} render={(content, state) => (
|
|
234
|
+
<Tag {...(blockProps as object)} className={cx(blockProps.className, "ecx-nested", className, state.status !== "ready" && "is-pending")} data-ecx-nested={state.docId}
|
|
235
|
+
onDoubleClick={(e) => { e.stopPropagation(); onFocusEdit(state.docId); }}>
|
|
236
|
+
<span className="ecx-nested-label" contentEditable={false}>{label}{state.title && state.title !== String(docRef.ref) ? ` · ${state.title}` : ""}</span>
|
|
237
|
+
{content}
|
|
238
|
+
{children}
|
|
239
|
+
</Tag>
|
|
240
|
+
)} />
|
|
241
|
+
);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function TemplatePartEdit({ block, blockProps, labels }: BlockEditProps) {
|
|
245
|
+
const { store } = useEditor();
|
|
246
|
+
const slug = String(block.attrs.slug ?? "");
|
|
247
|
+
const tag = ["header", "footer", "aside", "section"].includes(String(block.attrs.tagName)) ? String(block.attrs.tagName) : "div";
|
|
248
|
+
if (!slug) return <div {...merge(blockProps, "ecx-placeholder-block")}><span className="ecx-placeholder-title"><PanelTop className="ecx-icon" />{labels.templatePart}</span></div>;
|
|
249
|
+
return <NestedShell blockProps={blockProps} className={cx("ecx-template-part", `ecx-template-part-${slug}`)} tag={tag} label={<><PanelTop className="ecx-icon" />{slug}</>} docRef={{ kind: "part", ref: slug }} onFocusEdit={(id) => store.enterFocus(id)} />;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function SyncedPatternEdit({ block, blockProps, labels }: BlockEditProps) {
|
|
253
|
+
const { store } = useEditor();
|
|
254
|
+
const ref = Number(block.attrs.ref);
|
|
255
|
+
if (!ref) return <div {...merge(blockProps, "ecx-placeholder-block")}><span className="ecx-placeholder-title"><Repeat2 className="ecx-icon" />{labels.syncedPattern}</span></div>;
|
|
256
|
+
return <NestedShell blockProps={blockProps} className="ecx-synced-pattern" label={<><Repeat2 className="ecx-icon" />{labels.syncedPattern}</>} docRef={{ kind: "pattern", ref }} onFocusEdit={(id) => store.enterFocus(id)} />;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
export function themeBlocks(): BlockType[] {
|
|
260
|
+
const theme = "theme";
|
|
261
|
+
return [
|
|
262
|
+
{ name: "siteTitle", title: "Tên website", icon: Type, category: theme, keywords: "ten website site title", kind: "atom", edit: SiteTitleEdit, attributes: { level: { type: "integer", default: 0, min: 0, max: 6 }, link: { type: "boolean", default: true }, textAlign: TEXT_ALIGN }, supports: { style: true, className: true } },
|
|
263
|
+
{ name: "siteLogo", title: "Logo", icon: ImageIcon, category: theme, keywords: "logo", kind: "atom", edit: SiteLogoEdit, attributes: { width: { type: "number", default: 120 }, link: { type: "boolean", default: true } }, supports: { style: true, className: true } },
|
|
264
|
+
{ name: "siteTagline", title: "Khẩu hiệu", icon: Type, category: theme, keywords: "khau hieu tagline mo ta", kind: "atom", edit: SiteTaglineEdit, attributes: { textAlign: TEXT_ALIGN }, supports: { style: true, className: true } },
|
|
265
|
+
{ name: "navigation", title: "Menu", icon: Menu, category: theme, keywords: "menu dieu huong navigation", kind: "atom", edit: NavigationEdit, attributes: { location: { type: "string", default: "primary" }, orientation: { type: "string", enum: ["horizontal", "vertical"], default: "horizontal" }, mobile: { type: "boolean", default: true } }, supports: { style: true, className: true }, summary: (a) => a.location },
|
|
266
|
+
{ name: "search", title: "Tìm kiếm", icon: Search, category: theme, keywords: "tim kiem search", kind: "atom", edit: SearchEdit, attributes: { placeholder: { type: "string" }, buttonText: { type: "string" } }, supports: { style: true, className: true } },
|
|
267
|
+
{ name: "languageSwitcher", title: "Chọn ngôn ngữ", icon: Globe2, category: theme, keywords: "ngon ngu language", kind: "atom", edit: LanguageEdit, supports: { style: true, className: true } },
|
|
268
|
+
{ name: "copyright", title: "Bản quyền", icon: Copyright, category: theme, keywords: "ban quyen copyright", kind: "atom", edit: CopyrightEdit, attributes: { text: { type: "string" }, textAlign: TEXT_ALIGN }, supports: { style: true, className: true } },
|
|
269
|
+
{ name: "postTitle", title: "Tiêu đề bài", icon: Type, category: theme, keywords: "tieu de bai post title", kind: "atom", edit: PostTitleEdit, attributes: { level: { type: "integer", default: 1, min: 1, max: 6 }, link: { type: "boolean", default: false }, textAlign: TEXT_ALIGN }, supports: { style: true, className: true } },
|
|
270
|
+
{ name: "postContent", title: "Nội dung bài", icon: FileText, category: theme, keywords: "noi dung bai post content", kind: "atom", edit: PostContentEdit },
|
|
271
|
+
{ name: "postExcerpt", title: "Tóm tắt bài", icon: FileText, category: theme, keywords: "tom tat excerpt", kind: "atom", edit: PostExcerptEdit, attributes: { moreText: { type: "string" } }, supports: { style: true, className: true } },
|
|
272
|
+
{ name: "featuredImage", title: "Ảnh đại diện", icon: ImageIcon, category: theme, keywords: "anh dai dien featured image thumbnail", kind: "atom", edit: FeaturedImageEdit, attributes: { size: { type: "string", default: "large" }, link: { type: "boolean", default: false }, aspect: { type: "string", enum: ["auto", "16/9", "4/3", "1/1", "3/4"], default: "auto" } }, supports: { style: true, className: true } },
|
|
273
|
+
{ name: "postDate", title: "Ngày đăng", icon: CalendarDays, category: theme, keywords: "ngay dang date", kind: "atom", edit: PostDateEdit, attributes: { textAlign: TEXT_ALIGN, displayType: { type: "string", enum: ["published", "modified"], default: "published" } }, supports: { style: true, className: true } },
|
|
274
|
+
{ name: "postAuthor", title: "Tác giả", icon: User, category: theme, keywords: "tac gia author", kind: "atom", edit: PostAuthorEdit, attributes: { avatar: { type: "boolean", default: false } }, supports: { style: true, className: true } },
|
|
275
|
+
{ name: "postTerms", title: "Chuyên mục / thẻ", icon: Tag, category: theme, keywords: "chuyen muc the category tag terms", kind: "atom", edit: PostTermsEdit, attributes: { taxonomy: { type: "string", default: "category" }, separator: { type: "string", default: ", " } }, supports: { style: true, className: true } },
|
|
276
|
+
{ name: "comments", title: "Bình luận", icon: MessageSquare, category: theme, keywords: "binh luan comments", kind: "atom", edit: CommentsEdit },
|
|
277
|
+
{ name: "queryTitle", title: "Tiêu đề trang lưu trữ", icon: Heading1, category: theme, keywords: "tieu de luu tru chuyen muc archive query title h1", kind: "atom", edit: QueryTitleEdit, attributes: { level: { type: "integer", default: 1, min: 1, max: 6 }, prefix: { type: "boolean", default: false }, textAlign: TEXT_ALIGN }, supports: { style: true, className: true } },
|
|
278
|
+
{ name: "termDescription", title: "Mô tả chuyên mục", icon: AlignLeft, category: theme, keywords: "mo ta chuyen muc term description", kind: "atom", edit: TermDescriptionEdit, attributes: { textAlign: TEXT_ALIGN }, supports: { style: true, className: true } },
|
|
279
|
+
{ name: "breadcrumbs", title: "Breadcrumb", icon: ChevronsRight, category: theme, keywords: "breadcrumb duong dan dieu huong", kind: "atom", edit: BreadcrumbsEdit, attributes: { separator: { type: "string", default: "›" }, showHome: { type: "boolean", default: true }, showCurrent: { type: "boolean", default: true } }, supports: { style: true, className: true } },
|
|
280
|
+
{ name: "postNavigation", title: "Bài trước / bài sau", icon: ArrowLeftRight, category: theme, keywords: "bai truoc bai sau dieu huong post navigation", kind: "atom", edit: PostNavigationEdit, attributes: { showTitle: { type: "boolean", default: true } }, supports: { style: true, className: true } },
|
|
281
|
+
{
|
|
282
|
+
name: "query", title: "Danh sách bài", icon: Rows3, category: theme, keywords: "danh sach bai query loop tin tuc", kind: "container", edit: QueryEdit,
|
|
283
|
+
attributes: { inherit: { type: "boolean", default: true }, postType: { type: "string", default: "post" }, perPage: { type: "integer", default: 10, min: 1, max: 100 }, category: { type: "string" }, tag: { type: "string" }, orderBy: { type: "string", enum: ["date", "title", "modified", "menu_order", "comment_count", "rand"], default: "date" }, order: { type: "string", enum: ["desc", "asc"], default: "desc" }, authorId: { type: "integer", min: 1 }, search: { type: "string" }, exclude: { type: "string" }, sticky: { type: "string", enum: ["any", "only", "exclude"], default: "any" }, orderByMeta: { type: "string" }, paginate: { type: "boolean", default: false } },
|
|
284
|
+
create: () => makeBlock("query", { inherit: true }, [makeBlock("postTemplate", { layout: "list" }, [makeBlock("postTitle", { level: 2, link: true }), makeBlock("postExcerpt")]), makeBlock("pagination")]),
|
|
285
|
+
supports: { style: true, className: true },
|
|
286
|
+
},
|
|
287
|
+
{ name: "postTemplate", title: "Khuôn mỗi bài", icon: LayoutTemplate, kind: "container", edit: PostTemplateEdit, hidden: true, attributes: { layout: { type: "string", enum: ["list", "grid"], default: "list" }, columns: { type: "integer", default: 3, min: 1, max: 6 } }, structure: { parents: ["query"] } },
|
|
288
|
+
{ name: "pagination", title: "Phân trang", icon: ListOrdered, kind: "atom", edit: PaginationEdit, hidden: true, structure: { parents: ["query"] } },
|
|
289
|
+
{ name: "queryEmpty", title: "Khi không có bài", icon: SquareDashed, kind: "container", edit: QueryEmptyEdit, hidden: true, structure: { parents: ["query"] } },
|
|
290
|
+
{ name: "templatePart", title: "Phần dùng chung", icon: PanelTop, category: theme, keywords: "phan dung chung template part header footer", kind: "atom", edit: TemplatePartEdit, attributes: { slug: { type: "string" }, tagName: { type: "string", enum: ["div", "header", "footer", "aside", "section"], default: "div" } }, summary: (a) => a.slug },
|
|
291
|
+
{ name: "syncedPattern", title: "Mẫu đồng bộ", icon: Repeat2, category: "widgets", keywords: "mau dong bo synced pattern reusable", kind: "atom", edit: SyncedPatternEdit, attributes: { ref: { type: "integer" } }, hidden: true },
|
|
292
|
+
];
|
|
293
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { Columns2, Minus, Plus, Table2, ArrowUpToLine, ArrowDownToLine, ArrowLeftToLine, ArrowRightToLine, Trash2, Heading, TableCellsMerge, TableCellsSplit } from "lucide-react";
|
|
2
|
+
import { useEditor } from "../context";
|
|
3
|
+
import { makeBlock, type BNode } from "../core/model";
|
|
4
|
+
import { addColumn, addRow, canMerge, canSplit, deleteColumn, deleteRow, hasHeaderRow, mergeCells, splitCell, tableContext, toggleHeaderRow } from "../core/tables";
|
|
5
|
+
import { Dropdown, MenuItem, ToolButton } from "../ui/toolbar";
|
|
6
|
+
|
|
7
|
+
/** Công cụ bảng khi đang gõ trong ô (hoặc chọn cả bảng). */
|
|
8
|
+
export function TableTools({ ancestor, currentId }: { ancestor: BNode; currentId: string }) {
|
|
9
|
+
const { store, labels } = useEditor();
|
|
10
|
+
const ctx = tableContext(store, currentId);
|
|
11
|
+
if (!ctx || ctx.table.id !== ancestor.id) return null;
|
|
12
|
+
return (
|
|
13
|
+
<Dropdown label={labels.tableTools} trigger={<Table2 className="ecx-icon" />}>
|
|
14
|
+
{(close) => (
|
|
15
|
+
<>
|
|
16
|
+
<MenuItem icon={ArrowUpToLine} label={labels.rowBefore} onClick={() => { close(); addRow(store, ctx, false); }} />
|
|
17
|
+
<MenuItem icon={ArrowDownToLine} label={labels.rowAfter} onClick={() => { close(); addRow(store, ctx, true); }} />
|
|
18
|
+
<MenuItem icon={ArrowLeftToLine} label={labels.colBefore} onClick={() => { close(); addColumn(store, ctx, false); }} />
|
|
19
|
+
<MenuItem icon={ArrowRightToLine} label={labels.colAfter} onClick={() => { close(); addColumn(store, ctx, true); }} />
|
|
20
|
+
{ancestor.id !== currentId && canMerge(ctx, "right") && <MenuItem icon={TableCellsMerge} label={labels.mergeRight} onClick={() => { close(); mergeCells(store, ctx, "right"); }} />}
|
|
21
|
+
{ancestor.id !== currentId && canMerge(ctx, "down") && <MenuItem icon={TableCellsMerge} label={labels.mergeDown} onClick={() => { close(); mergeCells(store, ctx, "down"); }} />}
|
|
22
|
+
{ancestor.id !== currentId && canSplit(ctx) && <MenuItem icon={TableCellsSplit} label={labels.splitCell} onClick={() => { close(); splitCell(store, ctx); }} />}
|
|
23
|
+
<MenuItem icon={Heading} label={`${labels.headerRow}${hasHeaderRow(ctx.table) ? " ✓" : ""}`} onClick={() => { close(); toggleHeaderRow(store, ctx); }} />
|
|
24
|
+
<MenuItem icon={Trash2} label={labels.deleteRow} danger onClick={() => { close(); deleteRow(store, ctx); }} />
|
|
25
|
+
<MenuItem icon={Trash2} label={labels.deleteColumn} danger onClick={() => { close(); deleteColumn(store, ctx); }} />
|
|
26
|
+
</>
|
|
27
|
+
)}
|
|
28
|
+
</Dropdown>
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Thêm một cột cuối (tối đa 6), chia lại độ rộng đều nếu đang đặt độ rộng. */
|
|
33
|
+
export function addColumnTo(store: ReturnType<typeof useEditor>["store"], columns: BNode) {
|
|
34
|
+
const cols = columns.content ?? [];
|
|
35
|
+
if (cols.length >= 6) return;
|
|
36
|
+
const n = cols.length + 1;
|
|
37
|
+
const even = cols.some((c) => Number(c.attrs.width) > 0) ? Math.round(100 / n) : undefined;
|
|
38
|
+
const col = makeBlock("column", even ? { width: even } : {}, [makeBlock("paragraph")]);
|
|
39
|
+
store.replace(columns.id, [{ ...columns, content: [...cols.map((c) => ({ ...c, attrs: { ...c.attrs, width: even } })), col] }], { select: { ids: [], editing: col.content![0].id }, caret: { id: col.content![0].id, offset: 0 } });
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Thêm / bớt cột (chia lại độ rộng đều). */
|
|
43
|
+
export function ColumnsTools({ ancestor }: { ancestor: BNode; currentId: string }) {
|
|
44
|
+
const { store, labels } = useEditor();
|
|
45
|
+
const cols = ancestor.content ?? [];
|
|
46
|
+
const even = (n: number) => (cols.some((c) => Number(c.attrs.width) > 0) ? Math.round(100 / n) : undefined);
|
|
47
|
+
const add = () => addColumnTo(store, ancestor);
|
|
48
|
+
const remove = () => {
|
|
49
|
+
if (cols.length <= 1) return;
|
|
50
|
+
const n = cols.length - 1;
|
|
51
|
+
const next: BNode = { ...ancestor, content: cols.slice(0, -1).map((c) => ({ ...c, attrs: { ...c.attrs, width: even(n) } })) };
|
|
52
|
+
store.replace(ancestor.id, [next]);
|
|
53
|
+
};
|
|
54
|
+
return (
|
|
55
|
+
<>
|
|
56
|
+
<span className="ecx-tool is-static" title={`${cols.length} ${labels.columns}`}><Columns2 className="ecx-icon" /></span>
|
|
57
|
+
<ToolButton label={labels.removeColumn} disabled={cols.length <= 1} onClick={remove}><Minus className="ecx-icon" /></ToolButton>
|
|
58
|
+
<ToolButton label={labels.addColumn} disabled={cols.length >= 6} onClick={add}><Plus className="ecx-icon" /></ToolButton>
|
|
59
|
+
</>
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Thêm nút vào nhóm nút. */
|
|
64
|
+
export function ButtonsTools({ ancestor }: { ancestor: BNode; currentId: string }) {
|
|
65
|
+
const { store, labels } = useEditor();
|
|
66
|
+
return (
|
|
67
|
+
<ToolButton label={labels.addButton} onClick={() => {
|
|
68
|
+
const btn = makeBlock("button", { variant: "primary" });
|
|
69
|
+
store.insert(store.locate(ancestor.id)!.docId, ancestor.id, ancestor.content?.length ?? 0, [btn], { focus: false });
|
|
70
|
+
}}><Plus className="ecx-icon" /></ToolButton>
|
|
71
|
+
);
|
|
72
|
+
}
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import { normalizeStyle, styleClass } from "@ecomcx/ecomweb-content";
|
|
2
|
+
import { Component, memo, useCallback, useEffect, useMemo, useRef, type ErrorInfo, type MouseEvent, type ReactElement, type ReactNode } from "react";
|
|
3
|
+
import { DocScopeProvider, useDocScope, useEditor, useEditorState } from "../context";
|
|
4
|
+
import { docIdOf, type NestedDocRef } from "../core/host";
|
|
5
|
+
import { blocksFromDoc, makeBlock, type BNode } from "../core/model";
|
|
6
|
+
import type { BlockEditProps, BlockProps } from "../core/registry";
|
|
7
|
+
import type { EditingMode } from "../core/store";
|
|
8
|
+
|
|
9
|
+
const cx = (...c: unknown[]) => c.filter((x): x is string => typeof x === "string" && x !== "").join(" ");
|
|
10
|
+
|
|
11
|
+
/** Phần (khối cấp cao nhất của tài liệu đang sửa) chứa phần tử khối — null nếu nằm ngoài (template bị khoá). */
|
|
12
|
+
export function sectionOf(store: ReturnType<typeof useEditor>["store"], el: HTMLElement | null): string | null {
|
|
13
|
+
const active = store.activeDocId;
|
|
14
|
+
for (let cur = el; cur; cur = cur.parentElement?.closest<HTMLElement>("[data-ecx-block]") ?? null) {
|
|
15
|
+
const loc = store.locate(cur.dataset.ecxBlock!);
|
|
16
|
+
if (loc && loc.docId === active && !loc.parent) return loc.block.id;
|
|
17
|
+
}
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Props gắn vào phần tử gốc của khối: chọn, viền, kiểu dáng, neo. */
|
|
22
|
+
export function useBlockProps(block: BNode, state: { selected: boolean; editing: boolean; mode: EditingMode }): BlockProps {
|
|
23
|
+
const { store, registry, ui } = useEditor();
|
|
24
|
+
const a = block.attrs;
|
|
25
|
+
const style = a.style && typeof a.style === "object" ? normalizeStyle(a.style) : undefined;
|
|
26
|
+
const type = registry.get(block.type);
|
|
27
|
+
const onMouseDown = useCallback((e: MouseEvent<HTMLElement>) => {
|
|
28
|
+
if (e.button !== 0) return;
|
|
29
|
+
const target = e.target as HTMLElement;
|
|
30
|
+
const own = target.closest<HTMLElement>("[data-ecx-block]");
|
|
31
|
+
if (own?.dataset.ecxBlock !== block.id) return; // khối con tự xử lý
|
|
32
|
+
e.stopPropagation();
|
|
33
|
+
if (ui.zoomOut) {
|
|
34
|
+
// Thu nhỏ: chọn cả phần (khối cấp cao nhất của tài liệu đang sửa) chứa chỗ bấm, không đặt con trỏ chữ
|
|
35
|
+
e.preventDefault();
|
|
36
|
+
const section = sectionOf(store, own);
|
|
37
|
+
if (section) { store.select([section], { editing: null }); (own.ownerDocument.activeElement as HTMLElement | null)?.blur?.(); own.ownerDocument.querySelector<HTMLElement>(".ecx-canvas-root")?.focus({ preventScroll: true }); }
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
if (store.modeOf(block.id) === "disabled") return;
|
|
41
|
+
const rich = target.closest<HTMLElement>("[data-ecx-rich]");
|
|
42
|
+
if (rich && rich.isContentEditable && !e.shiftKey) return; // bấm vào chữ: ProseMirror đặt con trỏ, focus báo đang gõ
|
|
43
|
+
if (target.closest("input, textarea, select, button, [contenteditable=true]") && !e.shiftKey) return;
|
|
44
|
+
e.preventDefault();
|
|
45
|
+
// Chọn khối: rời ô gõ, đưa focus về khung soạn (phím Delete, ⌘C… thuộc về vùng chọn khối)
|
|
46
|
+
const active = own.ownerDocument.activeElement as HTMLElement | null;
|
|
47
|
+
if (active?.isContentEditable) active.blur();
|
|
48
|
+
if (e.shiftKey) store.selectRange(block.id);
|
|
49
|
+
else if (e.metaKey || e.ctrlKey) {
|
|
50
|
+
const ids = store.getState().selection.ids;
|
|
51
|
+
store.select(ids.includes(block.id) ? ids.filter((x) => x !== block.id) : [...ids, block.id], { editing: null });
|
|
52
|
+
} else store.select([block.id], { editing: null });
|
|
53
|
+
if (own.isContentEditable) own.ownerDocument.querySelector<HTMLElement>(".ecx-canvas-root")?.focus({ preventScroll: true });
|
|
54
|
+
else own.focus({ preventScroll: true });
|
|
55
|
+
}, [block.id, store, ui]);
|
|
56
|
+
return {
|
|
57
|
+
ref: null,
|
|
58
|
+
"data-ecx-block": block.id,
|
|
59
|
+
"data-type": block.type,
|
|
60
|
+
tabIndex: type?.kind === "text" ? undefined : -1,
|
|
61
|
+
id: typeof a.anchor === "string" ? a.anchor : undefined,
|
|
62
|
+
className: cx(
|
|
63
|
+
"ecx-block",
|
|
64
|
+
state.selected && "is-selected",
|
|
65
|
+
state.editing && "is-editing",
|
|
66
|
+
state.mode === "disabled" && "is-locked",
|
|
67
|
+
style && styleClass(style),
|
|
68
|
+
typeof a.blockStyle === "string" && `ecx-is-${a.blockStyle}`,
|
|
69
|
+
typeof a.className === "string" && a.className,
|
|
70
|
+
),
|
|
71
|
+
onMouseDown,
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
class BlockBoundary extends Component<{ id: string; type: string; children: ReactNode }, { error: Error | null }> {
|
|
76
|
+
state = { error: null as Error | null };
|
|
77
|
+
static getDerivedStateFromError(error: Error) { return { error }; }
|
|
78
|
+
componentDidCatch(error: Error, info: ErrorInfo) { console.error(`[ecomweb-editor] khối ${this.props.type} lỗi`, error, info.componentStack); }
|
|
79
|
+
render() {
|
|
80
|
+
if (this.state.error) return <div className="ecx-block ecx-block-error" data-ecx-block={this.props.id} data-type={this.props.type} tabIndex={-1}>⚠ {this.props.type}: {this.state.error.message}</div>;
|
|
81
|
+
return this.props.children;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Một khối trên khung soạn (memo theo tham chiếu khối: chỉ vẽ lại khối đổi). */
|
|
86
|
+
export const Block = memo(function Block({ node }: { node: BNode }) {
|
|
87
|
+
const { registry, store, labels } = useEditor();
|
|
88
|
+
const scope = useDocScope();
|
|
89
|
+
const selected = useEditorState(useCallback((s) => s.selection.ids.includes(node.id), [node.id]));
|
|
90
|
+
const editing = useEditorState(useCallback((s) => s.selection.editing === node.id, [node.id]));
|
|
91
|
+
const type = registry.get(node.type);
|
|
92
|
+
const blockProps = useBlockProps(node, { selected, editing, mode: scope.mode });
|
|
93
|
+
const setAttrs = useCallback((attrs: Record<string, unknown>) => store.setAttrs([node.id], attrs), [node.id, store]);
|
|
94
|
+
const Edit = type?.edit ?? FallbackEdit;
|
|
95
|
+
const props: BlockEditProps = { block: node, attrs: node.attrs, setAttrs, blockProps, selected: selected || editing, editable: scope.mode !== "disabled", labels };
|
|
96
|
+
return <BlockBoundary id={node.id} type={node.type}><Edit {...props} /></BlockBoundary>;
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Danh sách khối: phần tử JSX của khối không đổi (cùng tham chiếu) được dùng lại → React bỏ qua ngay, không so props —
|
|
101
|
+
* tài liệu dài gõ một phím chỉ vẽ lại khối đang gõ.
|
|
102
|
+
*/
|
|
103
|
+
function useBlockElements(list: readonly BNode[]): ReactElement[] {
|
|
104
|
+
const cache = useRef(new WeakMap<BNode, ReactElement>());
|
|
105
|
+
return list.map((b) => {
|
|
106
|
+
let el = cache.current.get(b);
|
|
107
|
+
if (!el) { el = <Block key={b.id} node={b} />; cache.current.set(b, el); }
|
|
108
|
+
return el;
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Khối chưa có giao diện riêng: thẻ tên + tóm tắt (dữ liệu giữ nguyên). */
|
|
113
|
+
export function FallbackEdit({ block, blockProps, labels }: BlockEditProps) {
|
|
114
|
+
const { registry } = useEditor();
|
|
115
|
+
const type = registry.get(block.type);
|
|
116
|
+
const Icon = type?.icon;
|
|
117
|
+
const summary = type?.summary?.(block.attrs);
|
|
118
|
+
return (
|
|
119
|
+
<div {...blockProps} className={cx(blockProps.className, "ecx-placeholder-block", !type && "is-unknown")}>
|
|
120
|
+
<span className="ecx-placeholder-title">{Icon && <Icon className="ecx-icon" />}{type?.title ?? block.type}</span>
|
|
121
|
+
{summary && <span className="ecx-placeholder-summary">{summary}</span>}
|
|
122
|
+
{!type && <span className="ecx-placeholder-summary">{labels.unknownBlock}</span>}
|
|
123
|
+
{block.content && <InnerBlocks parent={block} />}
|
|
124
|
+
</div>
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Khối con của một khối chứa — vẽ thẳng (không thẻ bọc) để bố cục flex/grid của website giữ đúng.
|
|
130
|
+
* `appender`: nút "+" cuối danh sách (khối chứa kiểu luồng như nhóm, cột) — danh sách, bảng, bộ cột tự thêm bằng thanh công cụ.
|
|
131
|
+
*/
|
|
132
|
+
export function InnerBlocks({ parent, appender = "auto" }: { parent: BNode; appender?: "auto" | "none" }) {
|
|
133
|
+
const scope = useDocScope();
|
|
134
|
+
const kids = parent.content ?? [];
|
|
135
|
+
const { store } = useEditor();
|
|
136
|
+
const showAppender = appender === "auto" && scope.mode === "default" && !kids.length && store.canInsertInto(parent.id);
|
|
137
|
+
const elements = useBlockElements(kids);
|
|
138
|
+
return (
|
|
139
|
+
<>
|
|
140
|
+
{elements}
|
|
141
|
+
{showAppender && <Appender docId={scope.docId} parentId={parent.id} index={0} />}
|
|
142
|
+
</>
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Nút "+" chèn khối vào khối chứa trống. */
|
|
147
|
+
export function Appender({ docId, parentId, index }: { docId: string; parentId: string | null; index: number }) {
|
|
148
|
+
const { ui, labels } = useEditor();
|
|
149
|
+
return (
|
|
150
|
+
<button type="button" className="ecx-appender" aria-label={labels.addBlock} title={labels.addBlock} contentEditable={false}
|
|
151
|
+
onMouseDown={(e) => { e.preventDefault(); e.stopPropagation(); }}
|
|
152
|
+
onClick={(e) => {
|
|
153
|
+
const r = (e.currentTarget as HTMLElement).getBoundingClientRect();
|
|
154
|
+
const f = ui.canvasFrame?.getBoundingClientRect();
|
|
155
|
+
ui.openInserter({ mode: "appender", docId, parentId, index, rect: { left: (f?.left ?? 0) + r.left, top: (f?.top ?? 0) + r.top, bottom: (f?.top ?? 0) + r.bottom } });
|
|
156
|
+
}}>+</button>
|
|
157
|
+
);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Danh sách khối cấp cao nhất của một tài liệu; tài liệu trống → ô "bắt đầu viết". */
|
|
161
|
+
export function DocBlocks({ docId }: { docId: string }) {
|
|
162
|
+
const { store, labels } = useEditor();
|
|
163
|
+
const doc = useEditorState(useCallback((s) => s.docs[docId], [docId]));
|
|
164
|
+
const scope = useDocScope();
|
|
165
|
+
const elements = useBlockElements(doc?.blocks ?? []);
|
|
166
|
+
if (!doc) return null;
|
|
167
|
+
if (!doc.blocks.length) {
|
|
168
|
+
if (doc.mode !== "default") return null;
|
|
169
|
+
return (
|
|
170
|
+
<p className="ecx-default-appender" data-placeholder={labels.emptyDoc} tabIndex={0} role="button"
|
|
171
|
+
onMouseDown={(e) => { e.preventDefault(); e.stopPropagation(); const p = makeBlock("paragraph"); store.insert(docId, null, 0, [p]); }}
|
|
172
|
+
onKeyDown={(e) => { if (e.key === "Enter") { const p = makeBlock("paragraph"); store.insert(docId, null, 0, [p]); } }}>
|
|
173
|
+
{labels.emptyDoc}
|
|
174
|
+
</p>
|
|
175
|
+
);
|
|
176
|
+
}
|
|
177
|
+
void scope;
|
|
178
|
+
return <>{elements}</>;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Tài liệu lồng (header, footer, mẫu đồng bộ, nội dung bài trong template): khối con lấy từ tài liệu khác,
|
|
183
|
+
* sửa ngay tại chỗ, lưu riêng. Tự tải qua host.documents khi chưa có trong store.
|
|
184
|
+
*/
|
|
185
|
+
export function NestedDoc({ docRef, mode, render }: { docRef: NestedDocRef; mode?: EditingMode; render?(content: ReactNode, state: NestedState): ReactNode }) {
|
|
186
|
+
const { store, host, labels } = useEditor();
|
|
187
|
+
const scope = useDocScope();
|
|
188
|
+
const docId = useMemo(() => docIdOf(host, docRef), [host, docRef]);
|
|
189
|
+
const doc = useEditorState(useCallback((s) => s.docs[docId], [docId]));
|
|
190
|
+
const cycle = scope.chain?.includes(docId) || docId === scope.docId;
|
|
191
|
+
|
|
192
|
+
useEffect(() => {
|
|
193
|
+
if (cycle || store.doc(docId) || !host.documents) return;
|
|
194
|
+
store.putDoc({ id: docId, kind: docRef.kind, ref: docRef.ref, status: "loading", blocks: [] });
|
|
195
|
+
host.documents.load(docRef).then(
|
|
196
|
+
(res) => {
|
|
197
|
+
if (!res) return store.putDoc({ id: docId, kind: docRef.kind, status: "error", error: labels.missingPart, blocks: [] });
|
|
198
|
+
const content = res.content as { blocks?: Array<{ type: string; data: unknown }> } | { type?: string };
|
|
199
|
+
const rich = content && "blocks" in content && Array.isArray(content.blocks)
|
|
200
|
+
? content.blocks.find((b) => b.type === "richtext")?.data
|
|
201
|
+
: content;
|
|
202
|
+
store.putDoc({ id: docId, kind: docRef.kind, ref: docRef.ref, title: res.title, blocks: blocksFromDoc(rich as never), status: "ready", mode: res.readOnly ? "disabled" : undefined });
|
|
203
|
+
},
|
|
204
|
+
(err: unknown) => store.putDoc({ id: docId, kind: docRef.kind, status: "error", error: String((err as Error)?.message ?? err), blocks: [] }),
|
|
205
|
+
);
|
|
206
|
+
}, [cycle, docId, docRef, host, labels, store]);
|
|
207
|
+
|
|
208
|
+
if (cycle) return <div className="ecx-nested-note">⟳ {docRef.kind} “{String(docRef.ref)}”</div>;
|
|
209
|
+
const state: NestedState = { docId, status: doc?.status ?? (host.documents ? "loading" : "error"), error: doc?.error, title: doc?.title };
|
|
210
|
+
const effective: EditingMode = scope.mode === "disabled" ? "disabled" : doc?.mode === "disabled" ? "disabled" : mode ?? doc?.mode ?? "default";
|
|
211
|
+
const content = state.status === "ready"
|
|
212
|
+
? <DocScopeProvider value={{ docId, mode: effective, depth: scope.depth + 1, chain: [...(scope.chain ?? [scope.docId]), docId] }}><DocBlocks docId={docId} /></DocScopeProvider>
|
|
213
|
+
: <div className="ecx-nested-note">{state.status === "loading" ? labels.loading : state.error ?? labels.loadFailed}</div>;
|
|
214
|
+
return <>{render ? render(content, state) : content}</>;
|
|
215
|
+
}
|
|
216
|
+
export interface NestedState { docId: string; status: "loading" | "ready" | "error"; error?: string; title?: string }
|