@ecomcx/ecomweb-editor 1.30.0 → 1.31.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.
@@ -0,0 +1,205 @@
1
+ import { embedInfo, isSafeUrl } from "@ecomcx/ecomweb-content";
2
+ import { File as FileIcon, Image as ImageIcon, Images, Link2, Music, Plus, Video } from "lucide-react";
3
+ import { useId, useState, type ComponentType, type CSSProperties, type MouseEvent, type ReactNode } from "react";
4
+ import { useEditor } from "../context";
5
+ import { useMsgs } from "../i18n";
6
+ import { MediaActions, useFileDrop } from "./media-actions";
7
+ import type { BlockProps } from "../core/registry";
8
+ import type { MediaItem, MediaKind } from "../../shared/types";
9
+
10
+ /**
11
+ * Ô giữ chỗ dùng chung (trình soạn v2) — khối lõi và khối plugin cùng một kiểu: ô thả media, ô gõ có gợi ý, ô dán link,
12
+ * ô chọn từ danh sách, nút "+ Thêm khối". Chỉ có trong khung soạn; website không vẽ gì khi ô còn trống.
13
+ */
14
+ const cx = (...c: unknown[]) => c.filter((x): x is string => typeof x === "string" && x !== "").join(" ");
15
+ type Icon = ComponentType<{ className?: string }>;
16
+ const KIND_ICON: Record<MediaKind, Icon> = { image: ImageIcon, gallery: Images, video: Video, audio: Music, file: FileIcon };
17
+ /** Bấm vào ô nhập / nút trong khối: không chọn khối, không để khung soạn bắt phím. */
18
+ const stop = { contentEditable: false, onMouseDown: (e: MouseEvent) => e.stopPropagation() } as const;
19
+
20
+ export interface MediaPlaceholderProps {
21
+ kind: MediaKind;
22
+ onSelect(items: MediaItem[]): void;
23
+ /** Có → hiện nút "Chèn từ URL". */
24
+ onUrl?(url: string): void;
25
+ /** Câu chính (mặc định "Kéo thả ảnh vào đây"…). */
26
+ title?: ReactNode;
27
+ icon?: Icon;
28
+ /** Kiểu tệp nhận khi tải lên (vd "application/pdf"); mặc định theo `kind`. */
29
+ accept?: string;
30
+ /** Nút / nội dung thêm dưới hàng nút (vd chọn màu nền của ảnh bìa). */
31
+ extra?: ReactNode;
32
+ className?: string;
33
+ style?: CSSProperties;
34
+ /** Ô là phần tử gốc của khối (khối Ảnh, Video…): gắn props của khối. */
35
+ blockProps?: BlockProps;
36
+ compact?: boolean;
37
+ }
38
+
39
+ /** Vùng kéo thả media: viền nét đứt luôn thấy; rê chuột → màu chính; kéo tệp vào → nền xanh, viền liền, "Thả để tải lên". */
40
+ export function MediaPlaceholder({ kind, onSelect, onUrl, title, icon, accept, extra, className, style, blockProps, compact }: MediaPlaceholderProps) {
41
+ const t = useMsgs("placeholders");
42
+ const drop = useFileDrop(kind, onSelect);
43
+ const I = icon ?? KIND_ICON[kind] ?? ImageIcon;
44
+ return (
45
+ <div {...(blockProps ?? {})} {...drop.props} data-ecx-placeholder="media"
46
+ className={cx(blockProps?.className, "ecx-media-placeholder ecx-ph-drop", compact && "is-compact", drop.over && "is-drop-target", className)}
47
+ style={{ ...(blockProps?.style ?? {}), ...style }}>
48
+ <I className="ecx-icon ecx-ph-icon" />
49
+ <p className="ecx-ph-title">{drop.over ? t.dropNow : title ?? t.drop[kind] ?? t.drop.file}</p>
50
+ {!drop.over && <p className="ecx-placeholder-hint">{t.dropSub}</p>}
51
+ {!drop.over && <MediaActions kind={kind} accept={accept} onSelect={onSelect} onUrl={onUrl} extra={extra} />}
52
+ </div>
53
+ );
54
+ }
55
+
56
+ export interface TextPlaceholderProps {
57
+ value: string;
58
+ onChange(value: string): void;
59
+ /** Chữ gợi ý (vd nhãn của thuộc tính). */
60
+ placeholder: string;
61
+ /** Nhiều dòng (textarea). */
62
+ multiline?: boolean;
63
+ /** Nhãn cho trình đọc màn hình (mặc định = gợi ý). */
64
+ label?: string;
65
+ required?: boolean;
66
+ id?: string;
67
+ className?: string;
68
+ style?: CSSProperties;
69
+ }
70
+
71
+ /** Ô gõ ngay trên khối: chữ gợi ý luôn hiện khi trống, cỡ chữ = cỡ chữ thật của chỗ đặt ô (kế thừa font). */
72
+ export function TextPlaceholder({ value, onChange, placeholder, multiline, label, required, id, className, style }: TextPlaceholderProps) {
73
+ const props = {
74
+ ...stop, id, className: cx("ecx-ph-text", className), style, value, placeholder, required, "aria-label": label ?? placeholder, "aria-required": required || undefined,
75
+ "data-ecx-placeholder": "text", onChange: (e: { target: { value: string } }) => onChange(e.target.value),
76
+ };
77
+ return multiline ? <textarea {...props} rows={2} /> : <input {...props} type="text" />;
78
+ }
79
+
80
+ export interface LinkPlaceholderProps {
81
+ /** Đường dẫn hợp lệ được gửi (đã trim). */
82
+ onSubmit(url: string): void;
83
+ title?: ReactNode;
84
+ hint?: ReactNode;
85
+ /** Kiểm link nhúng được (embedInfo) thay vì chỉ link an toàn. */
86
+ embed?: boolean;
87
+ /** Kiểm thêm (vd link YouTube); trả về false → báo lỗi. */
88
+ validate?(url: string): boolean;
89
+ buttonText?: string;
90
+ label?: string;
91
+ icon?: Icon;
92
+ defaultValue?: string;
93
+ className?: string;
94
+ blockProps?: BlockProps;
95
+ }
96
+
97
+ /** Ô dán đường dẫn ngay trong khối (nhúng, YouTube, link mua…): kiểm hợp lệ trước khi nhận. */
98
+ export function LinkPlaceholder({ onSubmit, title, hint, embed, validate, buttonText, label, icon: I = Link2, defaultValue = "", className, blockProps }: LinkPlaceholderProps) {
99
+ const t = useMsgs("placeholders");
100
+ const id = useId();
101
+ const [draft, setDraft] = useState(defaultValue);
102
+ const [error, setError] = useState<string | null>(null);
103
+ const submit = () => {
104
+ const url = draft.trim();
105
+ if (!isSafeUrl(url) || (validate && !validate(url))) return setError(t.linkInvalid);
106
+ if (embed && !embedInfo(url)) return setError(t.embedUnsupported);
107
+ setError(null);
108
+ onSubmit(url);
109
+ };
110
+ return (
111
+ <div {...(blockProps ?? {})} data-ecx-placeholder="link" className={cx(blockProps?.className, "ecx-media-placeholder ecx-ph-link", className)}>
112
+ {title && <p className="ecx-ph-title"><I className="ecx-icon" />{title}</p>}
113
+ <form className="ecx-ph-row" {...stop} onSubmit={(e) => { e.preventDefault(); submit(); }}>
114
+ <label htmlFor={id} className="ecx-ph-label">{label ?? t.link}</label>
115
+ <input id={id} className="ecx-input" type="url" inputMode="url" placeholder="https://…" value={draft} aria-invalid={!!error || undefined}
116
+ onChange={(e) => { setDraft(e.target.value); setError(null); }} />
117
+ <button type="submit" className="ecx-btn ecx-btn-primary">{buttonText ?? t.embed}</button>
118
+ </form>
119
+ {error ? <p className="ecx-media-error" role="alert">{error}</p> : hint ? <p className="ecx-placeholder-hint">{hint}</p> : null}
120
+ </div>
121
+ );
122
+ }
123
+
124
+ export interface PickPlaceholderProps {
125
+ title?: ReactNode;
126
+ label: string;
127
+ options: Array<{ value: string; label: string }>;
128
+ value?: string | null;
129
+ onChange(value: string): void;
130
+ /** Nút tạo mới (vd "Tạo form"). */
131
+ createLabel?: string;
132
+ onCreate?(): void;
133
+ hint?: ReactNode;
134
+ icon?: Icon;
135
+ className?: string;
136
+ blockProps?: BlockProps;
137
+ }
138
+
139
+ /** Chọn từ danh sách ngay trong khối (form, menu…) — không bắt nhớ mã số. */
140
+ export function PickPlaceholder({ title, label, options, value, onChange, createLabel, onCreate, hint, icon: I, className, blockProps }: PickPlaceholderProps) {
141
+ const t = useMsgs("placeholders");
142
+ const id = useId();
143
+ return (
144
+ <div {...(blockProps ?? {})} data-ecx-placeholder="pick" className={cx(blockProps?.className, "ecx-media-placeholder ecx-ph-pick", className)}>
145
+ {title && <p className="ecx-ph-title">{I && <I className="ecx-icon" />}{title}</p>}
146
+ <div className="ecx-ph-row" {...stop}>
147
+ <label htmlFor={id} className="ecx-ph-label">{label}</label>
148
+ <select id={id} className="ecx-input" value={value ?? ""} onChange={(e) => e.target.value && onChange(e.target.value)}>
149
+ <option value="">{t.choose}</option>
150
+ {options.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
151
+ </select>
152
+ {onCreate && <button type="button" className="ecx-btn" onClick={onCreate}><Plus className="ecx-icon ecx-icon-sm" />{createLabel}</button>}
153
+ </div>
154
+ {hint && <p className="ecx-placeholder-hint">{hint}</p>}
155
+ </div>
156
+ );
157
+ }
158
+
159
+ export interface AddBlockButtonProps {
160
+ /** Khối chứa nhận khối mới; không truyền → khối chứa gần nhất của nút trên khung soạn. */
161
+ parentId?: string;
162
+ docId?: string;
163
+ /** Vị trí chèn; mặc định cuối danh sách. */
164
+ index?: number;
165
+ label?: string;
166
+ className?: string;
167
+ }
168
+
169
+ /** Nút "+ Thêm khối" lớn giữa khối chứa trống: mở trình chèn ngay tại chỗ. */
170
+ export function AddBlockButton({ parentId, docId, index, label, className }: AddBlockButtonProps) {
171
+ const { ui, store } = useEditor();
172
+ const t = useMsgs("placeholders");
173
+ const text = label ?? t.addBlock;
174
+ return (
175
+ <button type="button" className={cx("ecx-appender ecx-add-block", className)} aria-label={text} contentEditable={false} data-ecx-placeholder="add"
176
+ onMouseDown={(e) => { e.preventDefault(); e.stopPropagation(); }}
177
+ onClick={(e) => {
178
+ const el = e.currentTarget as HTMLElement;
179
+ const pid = parentId ?? el.closest<HTMLElement>("[data-ecx-block]")?.dataset.ecxBlock;
180
+ const loc = pid ? store.locate(pid) : null;
181
+ if (!pid || !loc) return;
182
+ const r = el.getBoundingClientRect();
183
+ const f = ui.canvasFrame?.getBoundingClientRect();
184
+ ui.openInserter({ mode: "appender", docId: docId ?? loc.docId, parentId: pid, index: index ?? loc.block.content?.length ?? 0, rect: { left: (f?.left ?? 0) + r.left, top: (f?.top ?? 0) + r.top, bottom: (f?.top ?? 0) + r.bottom } });
185
+ }}>
186
+ <Plus className="ecx-icon" aria-hidden />{text}
187
+ </button>
188
+ );
189
+ }
190
+
191
+ /** Nút "+ Thêm …" nhỏ ở cuối danh sách (tab, mục accordion, slide, ảnh gallery). */
192
+ export function AddItemButton({ label, onClick, className }: { label: string; onClick(): void; className?: string }) {
193
+ return (
194
+ <button type="button" className={cx("ecx-add-item", className)} {...stop} data-ecx-placeholder="add-item" onClick={onClick}>
195
+ <Plus className="ecx-icon ecx-icon-sm" aria-hidden />{label}
196
+ </button>
197
+ );
198
+ }
199
+
200
+ /** Ô bắt buộc còn trống: viền cam + "Còn thiếu: …". */
201
+ export function MissingNote({ fields }: { fields: string[] }) {
202
+ const t = useMsgs("placeholders");
203
+ if (!fields.length) return null;
204
+ return <p className="ecx-ph-missing" role="status">{t.missing.replace("{fields}", fields.join(", "))}</p>;
205
+ }
@@ -119,6 +119,9 @@ export function BlockToolbar({ placement = "floating" }: { placement?: "floating
119
119
  const type = registry.get(first.type);
120
120
  const sameType = nodes.every((n) => n.type === first.type);
121
121
  const Icon = type?.icon ?? Blocks;
122
+ // Tên khối nằm trong thanh công cụ (nút đầu: biểu tượng + tên + ▾ đổi loại) — thay nhãn tên riêng trên khối (bị thanh đè)
123
+ const variation = sameType && nodes.length === 1 ? type?.variations?.find((v) => v.standalone && v.isActive?.(first.attrs)) : undefined;
124
+ const name = nodes.length > 1 ? `${nodes.length} ${labels.blocks}` : variation?.title ?? type?.title ?? first.type;
122
125
  const editingText = !sel.ids.length && !!sel.editing;
123
126
  const view = editingText ? activeView(ui.activeRich, sel.editing!) : null;
124
127
  const ordered = topLevelOrdered(store.getState().docs[loc.docId].blocks, ids);
@@ -191,13 +194,13 @@ export function BlockToolbar({ placement = "floating" }: { placement?: "floating
191
194
  <div className="ecx-tool-group">
192
195
  {parent && <ToolButton label={labels.selectParent} onClick={() => store.select([parent.id], { editing: null })}><ArrowUpLeft className="ecx-icon" /></ToolButton>}
193
196
  {transforms.length && removable && !store.isContentOnly(first.id) ? (
194
- <Dropdown label={labels.transform} trigger={<><Icon className="ecx-icon" /><ChevronDown className="ecx-icon ecx-icon-sm" /></>}>
197
+ <Dropdown label={`${name} · ${labels.transform}`} className="ecx-toolbar-type" trigger={<><Icon className="ecx-icon" /><span className="ecx-tool-text ecx-toolbar-name">{name}</span><ChevronDown className="ecx-icon ecx-icon-sm" /></>}>
195
198
  {(close) => transforms.map((t, i) => {
196
199
  const target = registry.get(t.to);
197
200
  return <MenuItem key={i} icon={target?.icon} label={`${target?.title ?? t.to}${t.title ? ` ${t.title}` : ""}`} onClick={() => { close(); doTransform(t); }} />;
198
201
  })}
199
202
  </Dropdown>
200
- ) : <span className="ecx-tool is-static" title={type?.title}><Icon className="ecx-icon" /></span>}
203
+ ) : <span className="ecx-tool is-static ecx-toolbar-type" title={name}><Icon className="ecx-icon" /><span className="ecx-tool-text ecx-toolbar-name">{name}</span></span>}
201
204
  {movable && <>
202
205
  <ToolButton label={labels.drag} className="ecx-drag-handle" onPointerDown={(e: React.PointerEvent) => startDrag(ctx, e, ordered)}><GripVertical className="ecx-icon" /></ToolButton>
203
206
  <div className="ecx-movers">
@@ -491,7 +494,8 @@ export function DropIndicator() {
491
494
  if (!ui.drag) return null;
492
495
  return (
493
496
  <>
494
- {t && <div className="ecx-drop-line" style={{ left: t.rect.left, top: t.rect.top, width: t.rect.width, height: t.rect.height }} data-horizontal={t.horizontal || undefined} />}
497
+ {/* key theo chỗ thả: sang chỗ mới thì thanh chạy lại từ giữa ra hai đầu (như WordPress) */}
498
+ {t && <div key={`${t.docId}:${t.parentId}:${t.index}`} className="ecx-drop-line" style={{ left: t.rect.left, top: t.rect.top, width: t.rect.width, height: t.rect.height }} data-horizontal={t.horizontal || undefined} />}
495
499
  <div className={t ? "ecx-drag-chip" : "ecx-drag-chip is-blocked"} style={{ left: ui.drag.x + 12, top: ui.drag.y + 12 }}>{(() => {
496
500
  // Tên khối đang kéo (nhiều khối: số lượng); không có chỗ thả hợp lệ → mờ đi
497
501
  const type = registry.get(ui.drag.newType ?? store.block(ui.drag.ids[0] ?? "")?.type ?? "");