@ecomcx/ecomweb-theme-sdk 1.32.0 → 1.34.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/dist/api.d.ts CHANGED
@@ -21,7 +21,15 @@ export interface FetchOptions {
21
21
  query?: Record<string, unknown>;
22
22
  headers?: Record<string, string>;
23
23
  asUser?: boolean;
24
+ /**
25
+ * Chiều biến thiên cache (core ≥ 1.22.0) mà plugin đang bật khai báo trong plugin.json › cacheVary: `{ device: "mobile", "flag:ab": "b" }`.
26
+ * CMS gộp vào khoá cache công khai, mỗi giá trị một bản; chiều chưa ai khai báo bị bỏ qua. Danh sách chiều: GET /api/public/cache-vary.
27
+ * Đọc header / cookie để biết giá trị sẽ khiến trang thành động — chỉ làm khi plugin thật sự cần.
28
+ */
29
+ vary?: Record<string, string>;
24
30
  }
31
+ /** Header X-CMS-Vary từ `vary` ("device=mobile,flag:ab=b"); rỗng → không gửi. */
32
+ export declare function varyHeader(vary?: Record<string, string>): Record<string, string>;
25
33
  /** Gọi Public API của CMS. Kết quả được cache và gắn tag "cms" để revalidate khi nội dung thay đổi. */
26
34
  export declare function cmsFetch<T>(path: string, opts?: FetchOptions): Promise<T>;
27
35
  /** Thông tin site theo ngôn ngữ của request (hoặc locale truyền vào). */
@@ -223,7 +231,10 @@ export declare const getWidgets: (area: string, locale?: string) => Promise<Widg
223
231
  * Bình luận đã duyệt theo trang (số mỗi trang, thứ tự: Cài đặt › Thảo luận).
224
232
  * Bài có mật khẩu (core >= 1.15): CMS chỉ trả bình luận khi có token mở khoá — unlock = giá trị cookie cms-unlock (không cache).
225
233
  */
226
- export declare const getComments: (postId: number, page?: number, unlock?: string) => Promise<CommentPage>;
234
+ export declare const getComments: (postId: number, page?: number, unlock?: string, opts?: {
235
+ perPage?: number;
236
+ order?: "asc" | "desc";
237
+ }) => Promise<CommentPage>;
227
238
  /** Cookie mở khoá bài có mật khẩu của request hiện tại (server component); ngoài request → undefined. */
228
239
  export declare function requestUnlock(): Promise<string | undefined>;
229
240
  export declare const getArchives: (locale?: string) => Promise<{
package/dist/api.js CHANGED
@@ -52,6 +52,11 @@ export class CmsApiError extends Error {
52
52
  this.status = status;
53
53
  }
54
54
  }
55
+ /** Header X-CMS-Vary từ `vary` ("device=mobile,flag:ab=b"); rỗng → không gửi. */
56
+ export function varyHeader(vary) {
57
+ const parts = Object.entries(vary ?? {}).filter(([k, v]) => /^(device|flag:[a-z][a-z0-9-]{0,23})$/.test(k) && /^[A-Za-z0-9_-]{1,32}$/.test(v)).map(([k, v]) => `${k}=${v.toLowerCase()}`);
58
+ return parts.length ? { "X-CMS-Vary": parts.join(",") } : {};
59
+ }
55
60
  /**
56
61
  * API không phản hồi (thường là đang khởi động lại vài giây khi bật/tắt plugin backend):
57
62
  * mọi request đang chờ cùng đợi một lần dò /api/health (tối đa 20 giây — máy chủ yếu khởi động lại chậm hơn) rồi gọi lại, thay vì trả trang lỗi 500.
@@ -85,9 +90,10 @@ const isUnavailable = (e) => isFetchKitError(e) && (!e.status || e.status === 50
85
90
  export async function cmsFetch(path, opts = {}) {
86
91
  if ((breaker.__cmsApiDownUntil ?? 0) > Date.now())
87
92
  throw new CmsApiError(503, `CMS API tạm thời không phản hồi: ${path}`);
93
+ const headers = { ...opts.headers, ...varyHeader(opts.vary) };
88
94
  const get = () => cmsApi.get(path, opts.noStore
89
- ? { cache: "no-store", query: opts.query, headers: opts.headers }
90
- : { next: { tags: ["cms", ...(opts.tags ?? [])], revalidate: opts.revalidate ?? 3600 }, query: opts.query, headers: opts.headers });
95
+ ? { cache: "no-store", query: opts.query, headers }
96
+ : { next: { tags: ["cms", ...(opts.tags ?? [])], revalidate: opts.revalidate ?? 3600 }, query: opts.query, headers });
91
97
  try {
92
98
  try {
93
99
  return ((await get()).data ?? null);
@@ -191,8 +197,8 @@ export const getWidgets = async (area, locale) => cmsFetch(`/widgets/${area}`, {
191
197
  * Bình luận đã duyệt theo trang (số mỗi trang, thứ tự: Cài đặt › Thảo luận).
192
198
  * Bài có mật khẩu (core >= 1.15): CMS chỉ trả bình luận khi có token mở khoá — unlock = giá trị cookie cms-unlock (không cache).
193
199
  */
194
- export const getComments = (postId, page = 1, unlock) => cmsFetch(`/comments/${postId}`, {
195
- tags: [`comments:${postId}`], noStore: !!unlock, query: page > 1 ? { page } : undefined, headers: unlock ? { [UNLOCK_HEADER]: unlock } : undefined,
200
+ export const getComments = (postId, page = 1, unlock, opts = {}) => cmsFetch(`/comments/${postId}`, {
201
+ tags: [`comments:${postId}`], noStore: !!unlock, query: clean({ page: page > 1 ? page : undefined, perPage: opts.perPage, order: opts.order }), headers: unlock ? { [UNLOCK_HEADER]: unlock } : undefined,
196
202
  });
197
203
  /** Cookie mở khoá bài có mật khẩu của request hiện tại (server component); ngoài request → undefined. */
198
204
  export async function requestUnlock() {
@@ -92,6 +92,13 @@ export declare function LogoutButton({ redirectTo, className, children }: {
92
92
  className?: string;
93
93
  children?: ReactNode;
94
94
  }): import("react").JSX.Element;
95
+ /** Liên kết "Đăng nhập" / nút "Đăng xuất" theo phiên; kiểm ở client nên trang vẫn cache được. Đang tải → chưa hiện gì. */
96
+ export declare function LoginOutLink({ loginHref, loginText, logoutText, className }: {
97
+ loginHref: string;
98
+ loginText: string;
99
+ logoutText: string;
100
+ className?: string;
101
+ }): import("react").JSX.Element;
95
102
  /**
96
103
  * Người đang đăng nhập, dùng trong component client (null = khách, undefined = đang tải).
97
104
  * Server Component nên dùng getCurrentUser() để khỏi tốn thêm một request.
@@ -86,7 +86,8 @@ export function LoginForm({ redirectTo, labels, links = true, paths, fields }) {
86
86
  return;
87
87
  }
88
88
  // Tải lại hẳn trang đích: mọi Server Component đọc được cookie phiên mới
89
- window.location.assign(safeRedirect(redirectParam, redirectTo ?? P.home));
89
+ // redirectTo từ máy chủ (plugin chọn qua filter auth.login_redirect) thắng đích mặc định của form
90
+ window.location.assign(safeRedirect(data.redirectTo ?? redirectParam, redirectTo ?? P.home));
90
91
  }
91
92
  catch (err) {
92
93
  setError(errorMessage(err, L.error));
@@ -206,6 +207,15 @@ export function LogoutButton({ redirectTo = "/", className, children }) {
206
207
  }
207
208
  }, children: children ?? AUTH_LABELS.logout }));
208
209
  }
210
+ /** Liên kết "Đăng nhập" / nút "Đăng xuất" theo phiên; kiểm ở client nên trang vẫn cache được. Đang tải → chưa hiện gì. */
211
+ export function LoginOutLink({ loginHref, loginText, logoutText, className }) {
212
+ const user = useCurrentUser();
213
+ if (user === undefined)
214
+ return _jsx("span", { className: className, "aria-hidden": "true" });
215
+ return user
216
+ ? _jsx(LogoutButton, { className: className, redirectTo: "/", children: logoutText })
217
+ : _jsx("a", { className: className, href: loginHref, children: loginText });
218
+ }
209
219
  /**
210
220
  * Người đang đăng nhập, dùng trong component client (null = khách, undefined = đang tải).
211
221
  * Server Component nên dùng getCurrentUser() để khỏi tốn thêm một request.
package/dist/client.d.ts CHANGED
@@ -40,12 +40,15 @@ export type LinkProps = Omit<AnchorHTMLAttributes<HTMLAnchorElement>, "href"> &
40
40
  };
41
41
  export declare function Link({ href, prefetch, activeClassName, matchNested, className, children, ...rest }: LinkProps): import("react").JSX.Element;
42
42
  /** Form tìm kiếm (GET) chuyển trang phía client. */
43
- export declare function SearchFormClient({ action, defaultValue, placeholder, label, buttonLabel }: {
43
+ export declare function SearchFormClient({ action, defaultValue, placeholder, label, buttonLabel, postType, showLabel, buttonPosition }: {
44
44
  action: string;
45
45
  defaultValue?: string | null;
46
46
  placeholder: string;
47
47
  label: string;
48
48
  buttonLabel: string;
49
+ postType?: string;
50
+ showLabel?: boolean;
51
+ buttonPosition?: "right" | "left" | "below";
49
52
  }): import("react").JSX.Element;
50
53
  /** Ghi tuỳ chọn hiển thị của người đọc (xem getPreference). value = null để xoá. */
51
54
  export declare function setPreference(key: string, value: string | null, maxAgeDays?: number): void;
@@ -67,12 +70,14 @@ type DateSite = {
67
70
  locale?: string;
68
71
  };
69
72
  /** Danh sách bình luận lồng nhau (render được cả ở server lẫn client). */
70
- export declare function CommentList({ comments, site }: {
73
+ export declare function CommentList({ comments, site, avatarSize, showDate }: {
71
74
  comments: Comment[];
72
75
  site: DateSite;
76
+ avatarSize?: number;
77
+ showDate?: boolean;
73
78
  }): import("react").JSX.Element;
74
79
  /** Nút "Xem thêm bình luận": tải các trang tiếp theo qua /api/cms/comments. */
75
- export declare function CommentsMore({ postId, totalPages, site, labels }: {
80
+ export declare function CommentsMore({ postId, totalPages, site, labels, perPage, order, avatarSize, showDate }: {
76
81
  postId: number;
77
82
  totalPages: number;
78
83
  site: DateSite;
@@ -81,6 +86,10 @@ export declare function CommentsMore({ postId, totalPages, site, labels }: {
81
86
  loading: string;
82
87
  error: string;
83
88
  };
89
+ perPage?: number;
90
+ order?: "asc" | "desc";
91
+ avatarSize?: number;
92
+ showDate?: boolean;
84
93
  }): import("react").JSX.Element;
85
94
  /** Form mật khẩu của bài được bảo vệ. Đúng mật khẩu → cookie httpOnly, tải lại nội dung trang. */
86
95
  export declare function PostPasswordForm({ postId, labels }: {
@@ -106,5 +115,22 @@ export declare function LanguageSwitcherClient({ languages, current, defaultLoca
106
115
  className?: string;
107
116
  variant: "list" | "select";
108
117
  }): import("react").JSX.Element;
109
- export { LoginForm, RegisterForm, ForgotPasswordForm, ResetPasswordForm, LogoutButton, useCurrentUser, extraFields, ProfileForm, ChangePasswordForm, DeleteAccountForm, AUTH_LABELS, AUTH_PATHS, type AuthLabels, type AuthPaths, type SignInProvider } from "./auth-forms.js";
118
+ export { LoginForm, RegisterForm, ForgotPasswordForm, ResetPasswordForm, LogoutButton, LoginOutLink, useCurrentUser, extraFields, ProfileForm, ChangePasswordForm, DeleteAccountForm, AUTH_LABELS, AUTH_PATHS, type AuthLabels, type AuthPaths, type SignInProvider } from "./auth-forms.js";
110
119
  export { safeRedirect, type CurrentUser } from "./auth-shared.js";
120
+ /** Khối countdown: đếm ngược tới `target` (ms). Dựng lần đầu cùng giá trị trên máy chủ, rồi cập nhật mỗi giây. */
121
+ export declare function CountdownClient({ target, label, expiredText }: {
122
+ target: number;
123
+ label?: string;
124
+ expiredText?: string;
125
+ }): import("react").JSX.Element;
126
+ /** Khối tabs: các panel đã vẽ sẵn trên máy chủ (nội dung vẫn có trong HTML cho SEO); chỉ đổi panel đang hiện. */
127
+ export declare function TabsClient({ titles, panels }: {
128
+ titles: string[];
129
+ panels: ReactNode[];
130
+ }): import("react").JSX.Element;
131
+ /** Phóng to ảnh: bấm ảnh mở lớp phủ (Esc hoặc bấm nền để đóng). `src` đã qua safeUrl ở máy chủ. */
132
+ export declare function LightboxClient({ src, alt, children }: {
133
+ src: string;
134
+ alt: string;
135
+ children: ReactNode;
136
+ }): import("react").JSX.Element;
package/dist/client.js CHANGED
@@ -1,7 +1,7 @@
1
1
  "use client";
2
2
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
3
  import { extraFields } from "./auth-forms.js";
4
- import { Component, Suspense, useEffect, useState } from "react";
4
+ import { Component, Suspense, useEffect, useId, useState } from "react";
5
5
  import { usePathname, useRouter } from "next/navigation";
6
6
  import NextLink, { useLinkStatus } from "next/link";
7
7
  import NextForm from "next/form";
@@ -58,8 +58,10 @@ export function Link({ href, prefetch = false, activeClassName, matchNested = tr
58
58
  }, children: [children, _jsx(PendingSignal, {})] }));
59
59
  }
60
60
  /** Form tìm kiếm (GET) chuyển trang phía client. */
61
- export function SearchFormClient({ action, defaultValue, placeholder, label, buttonLabel }) {
62
- return (_jsxs(NextForm, { action: action, role: "search", className: "search-form", children: [_jsx("input", { type: "search", name: "s", defaultValue: defaultValue ?? "", placeholder: placeholder, "aria-label": label, required: true }), _jsx("button", { type: "submit", children: buttonLabel })] }));
61
+ export function SearchFormClient({ action, defaultValue, placeholder, label, buttonLabel, postType, showLabel, buttonPosition = "right" }) {
62
+ const id = useId();
63
+ const button = _jsx("button", { type: "submit", children: buttonLabel });
64
+ return (_jsxs(NextForm, { action: action, role: "search", style: buttonPosition === "below" ? { display: "flex", flexDirection: "column", gap: 8 } : undefined, className: `search-form${buttonPosition !== "right" ? ` search-button-${buttonPosition}` : ""}`, children: [showLabel && _jsx("label", { htmlFor: id, className: "search-label", children: label }), buttonPosition === "left" && button, _jsx("input", { id: id, type: "search", name: "s", defaultValue: defaultValue ?? "", placeholder: placeholder, "aria-label": showLabel ? undefined : label, required: true }), postType && _jsx("input", { type: "hidden", name: "type", value: postType }), buttonPosition !== "left" && button] }));
63
65
  }
64
66
  /** Ghi tuỳ chọn hiển thị của người đọc (xem getPreference). value = null để xoá. */
65
67
  export function setPreference(key, value, maxAgeDays = 365) {
@@ -115,11 +117,11 @@ export function CommentForm({ postId, parentId, labels, fields }) {
115
117
  return (_jsxs("form", { className: "comment-form", onSubmit: onSubmit, children: [_jsx("h3", { children: L.title }), _jsx("p", { children: _jsxs("label", { children: [L.content, " *", _jsx("textarea", { name: "content", required: true, rows: 5, maxLength: 5000 })] }) }), _jsxs("p", { className: "comment-form-row", children: [_jsxs("label", { children: [L.name, " *", _jsx("input", { name: "authorName", required: true, maxLength: 100 })] }), _jsxs("label", { children: [L.email, " *", _jsx("input", { name: "authorEmail", type: "email", required: true, maxLength: 200 })] })] }), _jsx("p", { children: _jsxs("label", { children: [L.website, _jsx("input", { name: "authorUrl", type: "url", maxLength: 200 })] }) }), _jsx("input", { name: "website2", tabIndex: -1, autoComplete: "off", style: { position: "absolute", left: "-9999px" }, "aria-hidden": true }), fields, _jsx("p", { children: _jsx("button", { type: "submit", disabled: state === "sending", children: state === "sending" ? L.sending : L.submit }) }), message && _jsx("p", { className: state === "error" ? "form-error" : "form-success", role: "status", children: message })] }));
116
118
  }
117
119
  /** Danh sách bình luận lồng nhau (render được cả ở server lẫn client). */
118
- export function CommentList({ comments, site }) {
119
- return (_jsx("ol", { className: "comment-list", children: comments.map((c) => (_jsxs("li", { id: `comment-${c.id}`, className: "comment", children: [_jsxs("article", { children: [_jsxs("header", { className: "comment-meta", children: [c.avatarUrl && _jsx("img", { className: "comment-avatar avatar", src: c.avatarUrl, alt: "", width: 40, height: 40, loading: "lazy", decoding: "async" }), _jsx("b", { className: "comment-author", children: c.authorUrl ? _jsx("a", { href: c.authorUrl, rel: "nofollow ugc", children: c.authorName }) : c.authorName }), " · ", _jsx("time", { dateTime: c.createdAt, children: formatDate(c.createdAt, site) })] }), _jsx("div", { className: "comment-content", children: c.content.split("\n").map((l, i) => _jsx("p", { children: l }, i)) })] }), c.replies.length > 0 && _jsx(CommentList, { comments: c.replies, site: site })] }, c.id))) }));
120
+ export function CommentList({ comments, site, avatarSize = 40, showDate = true }) {
121
+ return (_jsx("ol", { className: "comment-list", children: comments.map((c) => (_jsxs("li", { id: `comment-${c.id}`, className: "comment", children: [_jsxs("article", { children: [_jsxs("header", { className: "comment-meta", children: [c.avatarUrl && _jsx("img", { className: "comment-avatar avatar", src: c.avatarUrl, alt: "", width: avatarSize, height: avatarSize, loading: "lazy", decoding: "async" }), _jsx("b", { className: "comment-author", children: c.authorUrl ? _jsx("a", { href: c.authorUrl, rel: "nofollow ugc", children: c.authorName }) : c.authorName }), showDate && _jsxs(_Fragment, { children: [" · ", _jsx("time", { dateTime: c.createdAt, children: formatDate(c.createdAt, site) })] })] }), _jsx("div", { className: "comment-content", children: c.content.split("\n").map((l, i) => _jsx("p", { children: l }, i)) })] }), c.replies.length > 0 && _jsx(CommentList, { comments: c.replies, site: site, avatarSize: avatarSize, showDate: showDate })] }, c.id))) }));
120
122
  }
121
123
  /** Nút "Xem thêm bình luận": tải các trang tiếp theo qua /api/cms/comments. */
122
- export function CommentsMore({ postId, totalPages, site, labels }) {
124
+ export function CommentsMore({ postId, totalPages, site, labels, perPage, order, avatarSize, showDate }) {
123
125
  const [pages, setPages] = useState([]);
124
126
  const [loading, setLoading] = useState(false);
125
127
  const [error, setError] = useState("");
@@ -128,7 +130,7 @@ export function CommentsMore({ postId, totalPages, site, labels }) {
128
130
  setLoading(true);
129
131
  setError("");
130
132
  try {
131
- const { data } = await browserApi.get("/comments", { query: { postId, page: next } });
133
+ const { data } = await browserApi.get("/comments", { query: { postId, page: next, ...(perPage ? { perPage } : {}), ...(order ? { order } : {}) } });
132
134
  setPages((p) => [...p, data.items]);
133
135
  }
134
136
  catch (e) {
@@ -138,7 +140,7 @@ export function CommentsMore({ postId, totalPages, site, labels }) {
138
140
  setLoading(false);
139
141
  }
140
142
  }
141
- return (_jsxs(_Fragment, { children: [pages.map((items, i) => _jsx(CommentList, { comments: items, site: site }, i)), next <= totalPages && _jsx("p", { className: "comments-more", children: _jsx("button", { type: "button", onClick: load, disabled: loading, children: loading ? labels.loading : labels.more }) }), error && _jsx("p", { className: "form-error", role: "alert", children: error })] }));
143
+ return (_jsxs(_Fragment, { children: [pages.map((items, i) => _jsx(CommentList, { comments: items, site: site, avatarSize: avatarSize, showDate: showDate }, i)), next <= totalPages && _jsx("p", { className: "comments-more", children: _jsx("button", { type: "button", onClick: load, disabled: loading, children: loading ? labels.loading : labels.more }) }), error && _jsx("p", { className: "form-error", role: "alert", children: error })] }));
142
144
  }
143
145
  /** Form mật khẩu của bài được bảo vệ. Đúng mật khẩu → cookie httpOnly, tải lại nội dung trang. */
144
146
  export function PostPasswordForm({ postId, labels }) {
@@ -188,5 +190,45 @@ export function LanguageSwitcherClient({ languages, current, defaultLocale, labe
188
190
  return (_jsx("select", { className: className ?? "lang-switcher", "aria-label": label, value: current, onChange: (e) => { window.location.href = href(e.target.value); }, children: languages.map((l) => _jsxs("option", { value: l.code, children: [l.flag ? `${l.flag} ` : "", l.name] }, l.code)) }));
189
191
  return (_jsx("nav", { className: className ?? "lang-switcher", "aria-label": label, children: _jsx("ul", { children: languages.map((l) => (_jsx("li", { className: l.code === current ? "current-lang" : undefined, children: _jsxs("a", { href: href(l.code), hrefLang: l.code, lang: l.code, "aria-current": l.code === current ? "true" : undefined, children: [l.flag && _jsxs("span", { "aria-hidden": true, children: [l.flag, " "] }), l.code.toUpperCase()] }) }, l.code))) }) }));
190
192
  }
191
- export { LoginForm, RegisterForm, ForgotPasswordForm, ResetPasswordForm, LogoutButton, useCurrentUser, extraFields, ProfileForm, ChangePasswordForm, DeleteAccountForm, AUTH_LABELS, AUTH_PATHS } from "./auth-forms.js";
193
+ export { LoginForm, RegisterForm, ForgotPasswordForm, ResetPasswordForm, LogoutButton, LoginOutLink, useCurrentUser, extraFields, ProfileForm, ChangePasswordForm, DeleteAccountForm, AUTH_LABELS, AUTH_PATHS } from "./auth-forms.js";
192
194
  export { safeRedirect } from "./auth-shared.js";
195
+ /** Khối countdown: đếm ngược tới `target` (ms). Dựng lần đầu cùng giá trị trên máy chủ, rồi cập nhật mỗi giây. */
196
+ export function CountdownClient({ target, label, expiredText }) {
197
+ const [now, setNow] = useState(() => Date.now());
198
+ useEffect(() => { const id = setInterval(() => setNow(Date.now()), 1000); return () => clearInterval(id); }, []);
199
+ const left = Math.max(0, target - now);
200
+ if (left === 0 && expiredText)
201
+ return _jsx("div", { className: "ecx-countdown is-expired", children: expiredText });
202
+ const p = (n) => String(n).padStart(2, "0");
203
+ const s = Math.floor(left / 1000);
204
+ const parts = [["d", Math.floor(s / 86400)], ["h", Math.floor(s / 3600) % 24], ["m", Math.floor(s / 60) % 60], ["s", s % 60]];
205
+ return (_jsxs("div", { className: "ecx-countdown", role: "timer", "aria-live": "off", suppressHydrationWarning: true, children: [label && _jsx("p", { className: "ecx-countdown-label", children: label }), _jsx("div", { className: "ecx-countdown-parts", children: parts.map(([u, n]) => _jsxs("span", { className: `ecx-countdown-${u}`, children: [_jsx("strong", { children: p(n) }), _jsx("small", { children: u })] }, u)) })] }));
206
+ }
207
+ /** Khối tabs: các panel đã vẽ sẵn trên máy chủ (nội dung vẫn có trong HTML cho SEO); chỉ đổi panel đang hiện. */
208
+ export function TabsClient({ titles, panels }) {
209
+ const [active, setActive] = useState(0);
210
+ const id = useId();
211
+ const move = (e, i) => {
212
+ const n = titles.length;
213
+ const next = e.key === "ArrowRight" ? (i + 1) % n : e.key === "ArrowLeft" ? (i + n - 1) % n : e.key === "Home" ? 0 : e.key === "End" ? n - 1 : -1;
214
+ if (next < 0)
215
+ return;
216
+ e.preventDefault();
217
+ setActive(next);
218
+ document.getElementById(`${id}-t${next}`)?.focus();
219
+ };
220
+ return (_jsxs("div", { className: "ecx-tabs", children: [_jsx("div", { role: "tablist", className: "ecx-tabs-list", children: titles.map((t, i) => (_jsx("button", { type: "button", role: "tab", id: `${id}-t${i}`, "aria-selected": i === active, "aria-controls": `${id}-p${i}`, tabIndex: i === active ? 0 : -1, className: cx("ecx-tab-button", i === active && "is-active"), onClick: () => setActive(i), onKeyDown: (e) => move(e, i), children: t }, i))) }), panels.map((p, i) => _jsx("div", { role: "tabpanel", id: `${id}-p${i}`, "aria-labelledby": `${id}-t${i}`, hidden: i !== active, className: "ecx-tab-panel", children: p }, i))] }));
221
+ }
222
+ /** Phóng to ảnh: bấm ảnh mở lớp phủ (Esc hoặc bấm nền để đóng). `src` đã qua safeUrl ở máy chủ. */
223
+ export function LightboxClient({ src, alt, children }) {
224
+ const [open, setOpen] = useState(false);
225
+ useEffect(() => {
226
+ if (!open)
227
+ return;
228
+ const onKey = (e) => { if (e.key === "Escape")
229
+ setOpen(false); };
230
+ document.addEventListener("keydown", onKey);
231
+ return () => document.removeEventListener("keydown", onKey);
232
+ }, [open]);
233
+ return (_jsxs(_Fragment, { children: [_jsx("button", { type: "button", className: "ecx-lightbox-trigger", "aria-haspopup": "dialog", onClick: () => setOpen(true), style: { all: "unset", display: "block", cursor: "zoom-in" }, children: children }), open && (_jsx("div", { role: "dialog", "aria-modal": "true", "aria-label": alt || "Image", className: "ecx-lightbox", onClick: () => setOpen(false), style: { position: "fixed", inset: 0, zIndex: 9999, background: "rgba(0,0,0,.85)", display: "flex", alignItems: "center", justifyContent: "center", cursor: "zoom-out" }, children: _jsx("img", { src: src, alt: alt, style: { maxWidth: "95vw", maxHeight: "95vh", objectFit: "contain" } }) }))] }));
234
+ }
@@ -19,15 +19,22 @@ export declare function Slot<P = any>({ name, data, props, fallback, className,
19
19
  className?: string;
20
20
  }): Promise<import("react").JSX.Element>;
21
21
  /** Ô tìm kiếm — gửi về trang chủ của ngôn ngữ hiện tại (/?s= hoặc /en?s=). */
22
- export declare function SearchForm({ defaultValue, placeholder, buttonLabel }: {
22
+ export declare function SearchForm({ defaultValue, placeholder, buttonLabel, postType, showLabel, buttonPosition }: {
23
23
  defaultValue?: string | null;
24
24
  placeholder?: string;
25
25
  buttonLabel?: string;
26
+ postType?: string;
27
+ showLabel?: boolean;
28
+ buttonPosition?: "right" | "left" | "below";
26
29
  }): Promise<import("react").JSX.Element>;
27
- export declare function Pagination({ data, prevLabel, nextLabel }: {
30
+ /** `pageParam`: phân trang bằng tham số URL (?qpage=2) thay cho /page/2 — dùng cho khối Query nằm trong trang, không phải trang lưu trữ. */
31
+ export declare function Pagination({ data, prevLabel, nextLabel, pageParam, type, midSize }: {
28
32
  data: ResolveResult;
29
33
  prevLabel?: string;
30
34
  nextLabel?: string;
35
+ pageParam?: string;
36
+ type?: "numbers" | "prevNext" | "both";
37
+ midSize?: number;
31
38
  }): Promise<import("react").JSX.Element | null>;
32
39
  /** Ảnh đại diện: responsive, WebP, srcset. */
33
40
  export declare function FeaturedImage({ media, size, className, link, sizes, priority }: {
@@ -54,9 +61,13 @@ export declare function TermLinks({ terms, separator }: {
54
61
  }>;
55
62
  separator?: string;
56
63
  }): import("react").JSX.Element | null;
57
- export declare function Comments({ post, title }: {
64
+ export declare function Comments({ post, title, perPage, order, avatarSize, showDate }: {
58
65
  post: Post;
59
66
  title?: string;
67
+ perPage?: number;
68
+ order?: "asc" | "desc";
69
+ avatarSize?: number;
70
+ showDate?: boolean;
60
71
  }): Promise<import("react").JSX.Element | null>;
61
72
  /**
62
73
  * Nút chuyển ngôn ngữ. Đặt ở layout của theme. Ẩn khi site chỉ có một ngôn ngữ.
@@ -85,11 +85,19 @@ export async function Slot({ name, data, props, fallback, className, }) {
85
85
  // Tiện ích hiển thị
86
86
  // ---------------------------------------------------------------------------
87
87
  /** Ô tìm kiếm — gửi về trang chủ của ngôn ngữ hiện tại (/?s= hoặc /en?s=). */
88
- export async function SearchForm({ defaultValue, placeholder, buttonLabel }) {
88
+ export async function SearchForm({ defaultValue, placeholder, buttonLabel, postType, showLabel, buttonPosition }) {
89
89
  const [t, site] = await Promise.all([getT(), getSite()]);
90
- return _jsx(SearchFormClient, { action: localeHref(site, "/"), defaultValue: defaultValue, placeholder: placeholder ?? t("search.placeholder"), label: t("search.label"), buttonLabel: buttonLabel ?? t("search.button") });
90
+ return _jsx(SearchFormClient, { action: localeHref(site, "/"), defaultValue: defaultValue, placeholder: placeholder ?? t("search.placeholder"), label: t("search.label"), buttonLabel: buttonLabel ?? t("search.button"), postType: postType, showLabel: showLabel, buttonPosition: buttonPosition });
91
91
  }
92
- export async function Pagination({ data, prevLabel, nextLabel }) {
92
+ function paramLink(data, param, p) {
93
+ const q = new URLSearchParams(Object.entries(data.query ?? {}).filter(([k]) => k !== param));
94
+ if (p > 1)
95
+ q.set(param, String(p));
96
+ const s = q.toString();
97
+ return s ? `${data.basePath}?${s}` : data.basePath;
98
+ }
99
+ /** `pageParam`: phân trang bằng tham số URL (?qpage=2) thay cho /page/2 — dùng cho khối Query nằm trong trang, không phải trang lưu trữ. */
100
+ export async function Pagination({ data, prevLabel, nextLabel, pageParam, type = "both", midSize = 2 }) {
93
101
  if (data.totalPages <= 1)
94
102
  return null;
95
103
  const t = await getT();
@@ -97,19 +105,19 @@ export async function Pagination({ data, prevLabel, nextLabel }) {
97
105
  nextLabel ??= t("pagination.next");
98
106
  const pages = [];
99
107
  for (let i = 1; i <= data.totalPages; i++) {
100
- if (i === 1 || i === data.totalPages || Math.abs(i - data.page) <= 2)
108
+ if (i === 1 || i === data.totalPages || Math.abs(i - data.page) <= midSize)
101
109
  pages.push(i);
102
110
  else if (pages[pages.length - 1] !== "…")
103
111
  pages.push("…");
104
112
  }
105
113
  // Danh sách có bộ lọc (?phong-ban=…, ?muc-luong=…) → giữ nguyên bộ lọc khi chuyển trang
106
114
  const hasFilters = Object.keys(data.query ?? {}).some((k) => k !== "s" && k !== "page");
107
- const link = (p) => hasFilters
115
+ const link = (p) => pageParam ? paramLink(data, pageParam, p) : hasFilters
108
116
  ? pageLinkWithQuery(data.basePath, p, data.query)
109
117
  : pageLink(data.basePath, p, data.kind === "search" ? data.search : null);
110
- return (_jsxs("nav", { className: "pagination", "aria-label": t("pagination.label"), children: [data.page > 1 && _jsx(Link, { className: "prev", href: link(data.page - 1), children: prevLabel }), pages.map((p, i) => p === "…" ? _jsx("span", { className: "dots", children: "\u2026" }, `e${i}`)
118
+ return (_jsxs("nav", { className: "pagination", "aria-label": t("pagination.label"), children: [type !== "numbers" && data.page > 1 && _jsx(Link, { className: "prev", href: link(data.page - 1), children: prevLabel }), type !== "prevNext" && pages.map((p, i) => p === "…" ? _jsx("span", { className: "dots", children: "\u2026" }, `e${i}`)
111
119
  : p === data.page ? _jsx("span", { className: "current", "aria-current": "page", children: p }, p)
112
- : _jsx(Link, { href: link(p), children: p }, p)), data.page < data.totalPages && _jsx(Link, { className: "next", href: link(data.page + 1), children: nextLabel })] }));
120
+ : _jsx(Link, { href: link(p), children: p }, p)), type !== "numbers" && data.page < data.totalPages && _jsx(Link, { className: "next", href: link(data.page + 1), children: nextLabel })] }));
113
121
  }
114
122
  /** Ảnh đại diện: responsive, WebP, srcset. */
115
123
  export function FeaturedImage({ media, size = "large", className, link, sizes, priority }) {
@@ -129,18 +137,18 @@ export function TermLinks({ terms, separator = ", " }) {
129
137
  // ---------------------------------------------------------------------------
130
138
  // Khu bình luận
131
139
  // ---------------------------------------------------------------------------
132
- export async function Comments({ post, title }) {
140
+ export async function Comments({ post, title, perPage, order, avatarSize, showDate }) {
133
141
  if (post.commentStatus !== "open" && post.commentCount === 0)
134
142
  return null;
135
143
  if (post.passwordProtected && !post.content)
136
144
  return null; // bài có mật khẩu: ẩn bình luận tới khi mở khoá
137
145
  const unlock = post.passwordProtected ? await requestUnlock() : undefined;
138
- const [site, page, t] = await Promise.all([getSite(), getComments(post.id, 1, unlock), getT()]);
146
+ const [site, page, t] = await Promise.all([getSite(), getComments(post.id, 1, unlock, { perPage, order }), getT()]);
139
147
  const comments = page?.items ?? [];
140
148
  const dateSite = { dateFormat: site.dateFormat, timezone: site.timezone, locale: site.locale };
141
149
  title ??= t("comments.title");
142
150
  const labels = Object.fromEntries(["title", "content", "name", "email", "website", "submit", "sending", "approved", "pending", "error"].map((k) => [k, t(`comments.form.${k}`)]));
143
- return (_jsxs("section", { id: "comments", className: "comments-area", children: [_jsx(Slot, { name: "comments.before", props: { post } }), _jsxs("h2", { className: "comments-title", children: [title, " (", post.commentCount, ")"] }), comments.length > 0 && _jsx(CommentList, { comments: comments, site: dateSite }), (page?.totalPages ?? 1) > 1 && _jsx(CommentsMore, { postId: post.id, totalPages: page.totalPages, site: dateSite, labels: { more: t("comments.more"), loading: t("comments.loading"), error: t("comments.form.error") } }), post.commentStatus === "open"
151
+ return (_jsxs("section", { id: "comments", className: "comments-area", children: [_jsx(Slot, { name: "comments.before", props: { post } }), _jsxs("h2", { className: "comments-title", children: [title, " (", post.commentCount, ")"] }), comments.length > 0 && _jsx(CommentList, { comments: comments, site: dateSite, avatarSize: avatarSize, showDate: showDate }), (page?.totalPages ?? 1) > 1 && _jsx(CommentsMore, { postId: post.id, totalPages: page.totalPages, site: dateSite, perPage: perPage, order: order, avatarSize: avatarSize, showDate: showDate, labels: { more: t("comments.more"), loading: t("comments.loading"), error: t("comments.form.error") } }), post.commentStatus === "open"
144
152
  ? _jsx(CommentForm, { postId: post.id, labels: labels, fields: _jsx(Slot, { name: "comment_form.fields", props: { post } }) })
145
153
  : _jsx("p", { className: "no-comments", children: t("comments.closed") }), _jsx(Slot, { name: "comments.after", props: { post } })] }));
146
154
  }
package/dist/content.d.ts CHANGED
@@ -5,10 +5,11 @@ import { type RenderContext } from "./rich.js";
5
5
  * Render nội dung bài viết (định dạng của CMS — @ecomcx/ecomweb-content; phần vẽ ở rich.tsx, không phụ thuộc trình soạn).
6
6
  * Luôn có class `ecx-content` (giao diện nền trong @ecomcx/ecomweb-content/style.css, theme ghi đè được); `className` thay cho `entry-content`.
7
7
  */
8
- export declare function PostContent({ post, content, className }: {
8
+ export declare function PostContent({ post, content, className, page }: {
9
9
  post?: Post | null;
10
10
  content?: PostContentDoc | null;
11
11
  className?: string;
12
+ page?: number;
12
13
  }): Promise<import("react").JSX.Element | null>;
13
14
  /**
14
15
  * Vùng của theme: header, footer (vùng chuẩn của core — nên luôn bọc) và vùng hybrid khai báo ở theme.json › regions.
package/dist/content.js CHANGED
@@ -1,5 +1,5 @@
1
- import { jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
2
- import { ExtensionBoundary, PostPasswordForm } from "./client.js";
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { ExtensionBoundary, Link, PostPasswordForm } from "./client.js";
3
3
  import { applyFilters, findBlock, findRegion, findShortcode, getActiveExtensions } from "./runtime.js";
4
4
  import { getPattern, getSite, getTemplates } from "./api.js";
5
5
  import { CORE_BINDING_SOURCES } from "./bindings.js";
@@ -11,7 +11,7 @@ import { cx } from "./utils.js";
11
11
  * Render nội dung bài viết (định dạng của CMS — @ecomcx/ecomweb-content; phần vẽ ở rich.tsx, không phụ thuộc trình soạn).
12
12
  * Luôn có class `ecx-content` (giao diện nền trong @ecomcx/ecomweb-content/style.css, theme ghi đè được); `className` thay cho `entry-content`.
13
13
  */
14
- export async function PostContent({ post, content, className }) {
14
+ export async function PostContent({ post, content, className, page }) {
15
15
  const site = await getSite();
16
16
  const doc = content ?? post?.content;
17
17
  if (!content && post?.passwordProtected && !post.content) {
@@ -20,8 +20,42 @@ export async function PostContent({ post, content, className }) {
20
20
  }
21
21
  if (!doc?.blocks?.length)
22
22
  return null;
23
- const rendered = await renderContent(doc, { ...(await contentContext(site, post)), source: post ? `post:${post.id}` : undefined }, (blocks) => applyFilters("post.blocks", blocks, { site, post }, site));
24
- return _jsx("div", { className: cx(className ?? "entry-content", "ecx-content"), children: rendered });
23
+ // Khối pageBreak chia bài thành nhiều trang (?trang=N): chỉ vẽ trang đang xem + thanh chuyển trang
24
+ let total = 1;
25
+ const current = Math.max(1, Math.floor(Number(page)) || 1);
26
+ const rendered = await renderContent(doc, { ...(await contentContext(site, post)), source: post ? `post:${post.id}` : undefined }, async (blocks) => {
27
+ const pages = splitPages(await applyFilters("post.blocks", blocks, { site, post }, site));
28
+ total = pages.length;
29
+ return pages[Math.min(current, total) - 1];
30
+ });
31
+ const n = Math.min(current, total);
32
+ const t = total > 1 ? await getT() : null;
33
+ const href = (i) => (post?.link ?? "") + (i > 1 ? `?trang=${i}` : "");
34
+ return (_jsxs("div", { className: cx(className ?? "entry-content", "ecx-content"), children: [rendered, t && post && (_jsxs("nav", { className: "ecx-page-links", "aria-label": t("pagination.label"), children: [n > 1 && _jsx(Link, { href: href(n - 1), rel: "prev", children: t("pagination.prev") }), Array.from({ length: total }, (_, i) => i + 1).map((i) => i === n ? _jsx("span", { "aria-current": "page", children: i }, i) : _jsx(Link, { href: href(i), children: i }, i)), n < total && _jsx(Link, { href: href(n + 1), rel: "next", children: t("pagination.next") })] }))] }));
35
+ }
36
+ /** Cắt khối richtext tại mỗi `pageBreak` cấp cao nhất; khối khác nằm ở trang đang mở. Không có pageBreak → một trang. */
37
+ function splitPages(blocks) {
38
+ const pages = [[]];
39
+ for (const b of blocks) {
40
+ const nodes = b.type === "richtext" ? (b.data?.content ?? []) : [];
41
+ if (!nodes.some((x) => x.type === "pageBreak")) {
42
+ pages[pages.length - 1].push(b);
43
+ continue;
44
+ }
45
+ let seg = [];
46
+ const flush = () => { if (seg.length)
47
+ pages[pages.length - 1].push({ ...b, data: { ...b.data, content: seg } }); seg = []; };
48
+ for (const x of nodes) {
49
+ if (x.type === "pageBreak") {
50
+ flush();
51
+ pages.push([]);
52
+ }
53
+ else
54
+ seg.push(x);
55
+ }
56
+ flush();
57
+ }
58
+ return pages.filter((p, i) => p.length || i === 0);
25
59
  }
26
60
  /**
27
61
  * Vùng của theme: header, footer (vùng chuẩn của core — nên luôn bọc) và vùng hybrid khai báo ở theme.json › regions.
@@ -48,9 +82,13 @@ export async function contentContext(site, post, data) {
48
82
  const t = await getT();
49
83
  // Bản nháp (xem trực tiếp / Trình dựng) không vào cache công khai → được gắn vị trí khối cho khung soạn
50
84
  const markBlocks = await import("next/headers").then(async ({ draftMode }) => (await draftMode()).isEnabled).catch(() => false);
51
- const blocks = (await getActiveExtensions(site)).flatMap((d) => d.blockTypes ?? []);
85
+ const extensions = await getActiveExtensions(site);
86
+ const blocks = extensions.flatMap((d) => d.blockTypes ?? []);
87
+ // Không plugin nào đăng ký "block.render" thì không tốn một lần gọi filter cho mỗi khối
88
+ const hasBlockFilter = extensions.some((d) => d.filters?.["block.render"]);
52
89
  return {
53
90
  site, post, data, blocks, markBlocks,
91
+ filterBlock: hasBlockFilter ? (node, el) => applyFilters("block.render", el, { node, site, post }, site) : undefined,
54
92
  resolve: { shortcode: (name) => findShortcode(name, site), block: (type) => findBlock(type, site) },
55
93
  labels: { download: t("file.download"), toc: t("toc.title") },
56
94
  boundary: (name, key, el) => _jsx(ExtensionBoundary, { name: name, children: el }, key),
package/dist/dynamic.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
2
  import { Fragment } from "react";
3
- import { getPosts } from "./api.js";
4
- import { Link } from "./client.js";
3
+ import { getArchives, getPosts, getTerms } from "./api.js";
4
+ import { Link, LoginOutLink } from "./client.js";
5
5
  import { Comments, FeaturedImage, LanguageSwitcher, Menu, Pagination, PostDate, SearchForm, TermLinks } from "./components.js";
6
6
  import { getT } from "./i18n.js";
7
7
  import { localeHref } from "./locale.js";
@@ -36,12 +36,14 @@ export async function renderDynamic(node, key, ctx, children) {
36
36
  const location = String(a.location ?? "primary");
37
37
  const menu = _jsx(Menu, { location: location, className: "ecx-navigation-menu" });
38
38
  const t = await getT();
39
- return (_jsxs("div", { className: cx("ecx-navigation", `ecx-navigation-${a.orientation ?? "horizontal"}`, a.mobile !== false && "has-mobile"), children: [_jsx("div", { className: "ecx-navigation-items", children: menu }), a.mobile !== false && _jsxs("details", { className: "ecx-navigation-toggle", children: [_jsx("summary", { "aria-label": t("navigation.menu"), children: "\u2630" }), menu] })] }, key));
39
+ // next: overlayMenu never|mobile|always; thiếu thì theo `mobile` cũ
40
+ const overlay = ["never", "mobile", "always"].includes(a.overlayMenu) ? a.overlayMenu : a.mobile === false ? "never" : "mobile";
41
+ return (_jsxs("div", { className: cx("ecx-navigation", `ecx-navigation-${a.orientation ?? "horizontal"}`, overlay !== "never" && "has-mobile", overlay === "always" && "overlay-always"), children: [overlay !== "always" && _jsx("div", { className: "ecx-navigation-items", children: menu }), overlay !== "never" && _jsxs("details", { className: "ecx-navigation-toggle", children: [_jsx("summary", { "aria-label": t("navigation.menu"), children: "\u2630" }), menu] })] }, key));
40
42
  }
41
43
  case "search":
42
- return _jsx("div", { className: "ecx-search", children: _jsx(SearchForm, { defaultValue: ctx.data?.search, placeholder: a.placeholder, buttonLabel: a.buttonText }) }, key);
44
+ return _jsx("div", { className: "ecx-search", children: _jsx(SearchForm, { defaultValue: ctx.data?.search, placeholder: a.placeholder, buttonLabel: a.buttonText, postType: typeof a.postType === "string" && /^[a-z0-9_-]{1,64}$/i.test(a.postType) ? a.postType : undefined, showLabel: a.showLabel === true, buttonPosition: a.buttonPosition === "left" || a.buttonPosition === "below" ? a.buttonPosition : "right" }) }, key);
43
45
  case "languageSwitcher":
44
- return _jsx(LanguageSwitcher, { className: "ecx-language-switcher" }, key);
46
+ return _jsx(LanguageSwitcher, { className: "ecx-language-switcher", variant: a.display === "dropdown" ? "select" : "list" }, key);
45
47
  case "copyright":
46
48
  return _jsxs("p", { className: "ecx-copyright", style: align(a), children: ["\u00A9 ", new Date().getFullYear(), " ", a.text || site.title] }, key);
47
49
  case "postTitle": {
@@ -54,7 +56,7 @@ export async function renderDynamic(node, key, ctx, children) {
54
56
  if (!post || !ctx.data)
55
57
  return null;
56
58
  const { PostContent } = await import("./content.js");
57
- return _jsx(PostContent, { post: post }, key);
59
+ return _jsx(PostContent, { post: post, page: Number(ctx.data.query?.trang) }, key);
58
60
  }
59
61
  case "postExcerpt":
60
62
  if (!post?.excerpt)
@@ -67,17 +69,79 @@ export async function renderDynamic(node, key, ctx, children) {
67
69
  return _jsx("div", { className: "ecx-featured-image", style: ratio ? { aspectRatio: ratio, overflow: "hidden" } : undefined, children: _jsx(FeaturedImage, { media: post.featuredMedia, size: a.size ?? "large", link: a.link ? post.link : undefined }) }, key);
68
70
  }
69
71
  case "postDate":
70
- return post ? _jsx("p", { className: "ecx-post-date", style: align(a), children: _jsx(PostDate, { post: post, site: site }) }, key) : null;
72
+ return post ? _jsx("p", { className: "ecx-post-date", style: align(a), children: _jsx(PostDate, { post: a.displayType === "modified" ? { ...post, publishedAt: post.updatedAt } : post, site: site }) }, key) : null;
71
73
  case "postAuthor":
72
74
  if (!post?.author)
73
75
  return null;
74
- return _jsxs("p", { className: "ecx-post-author", children: [a.avatar && post.author.avatarUrl && _jsx("img", { src: post.author.avatarUrl, alt: "", width: 32, height: 32, style: { borderRadius: "50%", verticalAlign: "middle", marginRight: 8 } }), _jsx(Link, { href: localeHref(site, `/author/${post.author.slug}`), rel: "author", children: post.author.name })] }, key);
76
+ {
77
+ const size = Math.min(128, Math.max(16, Number(a.avatarSize) || 32));
78
+ const name = a.showName === false ? null : a.link === false ? _jsx("span", { children: post.author.name }) : _jsx(Link, { href: localeHref(site, `/author/${post.author.slug}`), rel: "author", children: post.author.name });
79
+ return _jsxs("p", { className: "ecx-post-author", children: [a.avatar && post.author.avatarUrl && _jsx("img", { src: post.author.avatarUrl, alt: a.showName === false ? post.author.name : "", width: size, height: size, style: { borderRadius: "50%", verticalAlign: "middle", marginRight: name ? 8 : 0 } }), name, a.showBio === true && post.author.bio && _jsxs("span", { className: "ecx-post-author-bio", children: [" ", post.author.bio] })] }, key);
80
+ }
81
+ case "readMore":
82
+ return post ? _jsx("p", { className: "ecx-read-more", style: align(a), children: _jsx(Link, { href: post.link, children: a.text || (await getT())("post.read_more") }) }, key) : null;
83
+ case "commentsCount":
84
+ return post ? _jsx("p", { className: "ecx-comments-count", style: align(a), children: post.commentCount }, key) : null;
85
+ case "avatar": {
86
+ const size = Math.min(256, Math.max(16, Number(a.size) || 48));
87
+ const au = post?.author;
88
+ if (!au?.avatarUrl)
89
+ return null;
90
+ const img = _jsx("img", { src: au.avatarUrl, alt: au.name, width: size, height: size, loading: "lazy", style: { borderRadius: "50%" } });
91
+ return _jsx("span", { className: "ecx-avatar", children: a.link === false ? img : _jsx(Link, { href: localeHref(site, `/author/${au.slug}`), rel: "author", children: img }) }, key);
92
+ }
93
+ case "queryTotal":
94
+ return ctx.query?.data ? _jsx("p", { className: "ecx-query-total", style: align(a), children: ctx.query.data.total }, key) : null;
95
+ case "loginout": {
96
+ const t = await getT();
97
+ return _jsx("p", { className: "ecx-loginout", style: align(a), children: _jsx(LoginOutLink, { loginHref: localeHref(site, "/login"), loginText: a.loginText || t("auth.submitLogin"), logoutText: a.logoutText || t("auth.logout") }) }, key);
98
+ }
99
+ case "termList": {
100
+ const taxonomy = String(a.taxonomy ?? "category");
101
+ if (!/^[a-z0-9_-]{1,64}$/i.test(taxonomy))
102
+ return null;
103
+ const terms = await getTerms(taxonomy, a.hideEmpty !== false).catch(() => []);
104
+ if (!terms.length)
105
+ return null;
106
+ const label = (t) => _jsxs(_Fragment, { children: [_jsx(Link, { href: t.link, rel: "tag", children: t.name }), a.showCount === true && _jsxs(_Fragment, { children: [" (", t.count, ")"] })] });
107
+ if (a.display === "cloud") {
108
+ const max = Math.max(...terms.map((t) => t.count), 1);
109
+ return _jsx("p", { className: "ecx-term-list is-cloud", children: terms.map((t) => _jsx("span", { style: { fontSize: `${(0.8 + (t.count / max) * 0.9).toFixed(2)}em`, marginRight: "0.5em" }, children: label(t) }, t.id)) }, key);
110
+ }
111
+ if (a.hierarchical === true) {
112
+ const ids = new Set(terms.map((t) => t.id));
113
+ const tree = (parent, depth) => {
114
+ const rows = terms.filter((t) => (parent === null ? !t.parentId || !ids.has(t.parentId) : t.parentId === parent));
115
+ return rows.length && depth < 5 ? _jsx("ul", { children: rows.map((t) => _jsxs("li", { children: [label(t), tree(t.id, depth + 1)] }, t.id)) }) : null;
116
+ };
117
+ return _jsx("nav", { className: "ecx-term-list", children: tree(null, 0) }, key);
118
+ }
119
+ return _jsx("ul", { className: "ecx-term-list", children: terms.map((t) => _jsx("li", { children: label(t) }, t.id)) }, key);
120
+ }
121
+ case "pageList": {
122
+ const pages = (await getPosts({ type: "page", perPage: 50, orderBy: "menu_order", order: "asc" }).catch(() => null))?.items ?? [];
123
+ const rootId = typeof a.parentId === "number" ? a.parentId : null;
124
+ const maxDepth = Math.min(3, Math.max(1, Number(a.depth) || 2));
125
+ const ids = new Set(pages.map((p) => p.id));
126
+ const tree = (parent, depth) => {
127
+ const rows = pages.filter((p) => (parent === null ? !p.parentId || !ids.has(p.parentId) : p.parentId === parent));
128
+ return rows.length && depth < maxDepth ? _jsx("ul", { children: rows.map((p) => _jsxs("li", { children: [_jsx(Link, { href: p.link, children: p.title }), tree(p.id, depth + 1)] }, p.id)) }) : null;
129
+ };
130
+ const list = tree(rootId, 0);
131
+ return list ? _jsx("nav", { className: "ecx-page-list", children: list }, key) : null;
132
+ }
133
+ case "archives": {
134
+ const [rows, t] = await Promise.all([getArchives().catch(() => []), getT()]);
135
+ if (!rows.length)
136
+ return null;
137
+ return _jsx("ul", { className: "ecx-archives", children: rows.slice(0, Math.min(60, Math.max(1, Number(a.limit) || 12))).map((r) => _jsxs("li", { children: [_jsx(Link, { href: r.link, children: t("archives.month", { month: r.month, year: r.year }) }), a.showCount !== false && _jsxs(_Fragment, { children: [" (", r.count, ")"] })] }, r.link)) }, key);
138
+ }
75
139
  case "postTerms": {
76
140
  const terms = post?.terms?.[a.taxonomy ?? "category"];
77
141
  return terms?.length ? _jsx("p", { className: "ecx-post-terms", children: _jsx(TermLinks, { terms: terms, separator: a.separator ?? ", " }) }, key) : null;
78
142
  }
79
143
  case "comments":
80
- return post && ctx.data?.post?.id === post.id ? _jsx(Comments, { post: post }, key) : null;
144
+ return post && ctx.data?.post?.id === post.id ? _jsx(Comments, { post: post, title: a.title ? String(a.title) : undefined, perPage: typeof a.perPage === "number" ? a.perPage : undefined, order: a.order === "asc" || a.order === "desc" ? a.order : undefined, avatarSize: typeof a.avatarSize === "number" ? a.avatarSize : undefined, showDate: a.showDate === false ? false : undefined }, key) : null;
81
145
  // H1 của trang lưu trữ / tìm kiếm / tác giả (trang chủ dạng danh sách bài: tên trang)
82
146
  case "queryTitle": {
83
147
  const d = ctx.data;
@@ -130,17 +194,28 @@ export async function renderDynamic(node, key, ctx, children) {
130
194
  case "query": {
131
195
  let posts;
132
196
  let data;
197
+ let pageParam;
133
198
  if (a.inherit !== false && ctx.data?.posts) {
134
199
  posts = ctx.data.posts;
135
200
  data = ctx.data;
136
201
  }
137
202
  else {
138
203
  const taxonomy = a.category ? "category" : a.tag ? "post_tag" : undefined;
139
- const res = await getPosts({ type: a.postType ?? "post", perPage: a.perPage ?? 10, taxonomy, term: a.category || a.tag || undefined,
140
- orderBy: a.orderBy ?? "date", order: a.order ?? "desc" }).catch(() => null);
204
+ const exclude = String(a.exclude ?? "").split(",").map((x) => Number(x.trim())).filter((x) => Number.isInteger(x) && x > 0);
205
+ // paginate: khối nằm trong một trang → phân trang bằng ?qpage=N (không đụng /page/N của chính trang)
206
+ const paginate = a.paginate === true && !!ctx.data;
207
+ const page = paginate ? Math.max(1, Math.floor(Number(ctx.data?.query?.qpage)) || 1) : 1;
208
+ const res = await getPosts({ page, type: a.postType ?? "post", perPage: a.perPage ?? 10, taxonomy, term: a.category || a.tag || undefined,
209
+ orderBy: a.orderBy ?? "date", order: a.order ?? "desc",
210
+ authorId: typeof a.authorId === "number" ? a.authorId : undefined, search: a.search || undefined, exclude: exclude.length ? exclude : undefined,
211
+ sticky: a.sticky === "only" ? true : a.sticky === "exclude" ? false : undefined, orderByMeta: a.orderByMeta || undefined }).catch(() => null);
141
212
  posts = res?.items ?? [];
213
+ if (paginate && res && ctx.data) {
214
+ data = { ...ctx.data, page: res.page, totalPages: res.totalPages, total: res.total };
215
+ pageParam = "qpage";
216
+ }
142
217
  }
143
- return _jsx("div", { className: "ecx-query", children: await children({ ...ctx, query: { posts, data } }) }, key);
218
+ return _jsx("div", { className: "ecx-query", children: await children({ ...ctx, query: { posts, data, pageParam } }) }, key);
144
219
  }
145
220
  case "postTemplate": {
146
221
  const posts = ctx.query?.posts ?? [];
@@ -152,7 +227,7 @@ export async function renderDynamic(node, key, ctx, children) {
152
227
  return _jsx("ul", { className: cx("ecx-post-template", grid && "is-grid"), style: style, children: items }, key);
153
228
  }
154
229
  case "pagination":
155
- return ctx.query?.data ? _jsx(Pagination, { data: ctx.query.data }, key) : null;
230
+ return ctx.query?.data ? _jsx(Pagination, { data: ctx.query.data, pageParam: ctx.query.pageParam, type: ["numbers", "prevNext", "both"].includes(a.type) ? a.type : "both", midSize: Math.min(5, Math.max(0, Number.isFinite(Number(a.midSize)) ? Number(a.midSize) : 2)) }, key) : null;
156
231
  case "queryEmpty":
157
232
  return ctx.query && !ctx.query.posts.length ? _jsx("div", { className: "ecx-query-empty", children: await children(ctx) }, key) : null;
158
233
  case "syncedPattern": {
package/dist/i18n.js CHANGED
@@ -6,7 +6,7 @@ import { formatMessage } from "./i18n-format.js";
6
6
  export const BUILTIN = {
7
7
  vi: {
8
8
  "search.placeholder": "Tìm kiếm…", "search.button": "Tìm", "search.label": "Từ khoá", "navigation.menu": "Menu", "toc.title": "Mục lục", "query.search": "Kết quả tìm kiếm: {q}", "query.category": "Chuyên mục: {name}", "query.tag": "Thẻ: {name}", "query.author": "Tác giả: {name}", "breadcrumbs.home": "Trang chủ", "breadcrumbs.label": "Đường dẫn", "postNav.previous": "Bài trước", "postNav.next": "Bài sau", "postNav.label": "Bài khác",
9
- "pagination.prev": "« Trước", "pagination.next": "Sau »", "pagination.label": "Phân trang",
9
+ "post.read_more": "Đọc tiếp", "pagination.prev": "« Trước", "pagination.next": "Sau »", "pagination.label": "Phân trang",
10
10
  "comments.title": "Bình luận", "comments.closed": "Bình luận đã đóng.",
11
11
  "comments.form.title": "Để lại bình luận", "comments.form.content": "Bình luận", "comments.form.name": "Tên",
12
12
  "comments.form.email": "Email", "comments.form.website": "Website", "comments.form.submit": "Gửi bình luận",
@@ -31,7 +31,7 @@ export const BUILTIN = {
31
31
  },
32
32
  en: {
33
33
  "search.placeholder": "Search…", "search.button": "Search", "search.label": "Keyword", "navigation.menu": "Menu", "toc.title": "Contents", "query.search": "Search results: {q}", "query.category": "Category: {name}", "query.tag": "Tag: {name}", "query.author": "Author: {name}", "breadcrumbs.home": "Home", "breadcrumbs.label": "Breadcrumb", "postNav.previous": "Previous", "postNav.next": "Next", "postNav.label": "More posts",
34
- "pagination.prev": "« Previous", "pagination.next": "Next »", "pagination.label": "Pagination",
34
+ "post.read_more": "Read more", "pagination.prev": "« Previous", "pagination.next": "Next »", "pagination.label": "Pagination",
35
35
  "comments.title": "Comments", "comments.closed": "Comments are closed.",
36
36
  "comments.form.title": "Leave a comment", "comments.form.content": "Comment", "comments.form.name": "Name",
37
37
  "comments.form.email": "Email", "comments.form.website": "Website", "comments.form.submit": "Post comment",
@@ -0,0 +1,2 @@
1
+ /** Tập icon cố định cho khối `icon` (24×24, nét 2, lucide). Chỉ nhận tên trong bảng này — không nhận SVG tuỳ ý (chống XSS). */
2
+ export declare const ICON_PATHS: Record<string, string>;
package/dist/icons.js ADDED
@@ -0,0 +1,15 @@
1
+ /** Tập icon cố định cho khối `icon` (24×24, nét 2, lucide). Chỉ nhận tên trong bảng này — không nhận SVG tuỳ ý (chống XSS). */
2
+ export const ICON_PATHS = {
3
+ check: "M20 6 9 17l-5-5",
4
+ x: "M18 6 6 18M6 6l12 12",
5
+ star: "M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z",
6
+ heart: "M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z",
7
+ arrowRight: "M5 12h14M12 5l7 7-7 7",
8
+ phone: "M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z",
9
+ mail: "M4 4h16a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2zM22 6l-10 7L2 6",
10
+ mapPin: "M20 10c0 6-8 12-8 12s-8-6-8-12a8 8 0 0 1 16 0zM12 7a3 3 0 1 0 0 6 3 3 0 0 0 0-6z",
11
+ clock: "M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20zM12 6v6l4 2",
12
+ info: "M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20zM12 16v-4M12 8h.01",
13
+ alert: "M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0zM12 9v4M12 17h.01",
14
+ externalLink: "M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6M15 3h6v6M10 14 21 3",
15
+ };
package/dist/index.d.ts CHANGED
@@ -10,7 +10,7 @@ export { getRequestLocale, localeHref, LOCALE_HEADER } from "./locale.js";
10
10
  export { CommentForm, CommentList, CommentsMore, ExtensionBoundary, PostPasswordForm, Link, isInternalHref, type LinkProps } from "./client.js";
11
11
  export { getPreference } from "./preferences.js";
12
12
  export { getCurrentUser, getAccessToken, requireUser, userCan, safeRedirect, ACCESS_COOKIE, REFRESH_COOKIE, type CurrentUser } from "./auth.js";
13
- export { LoginForm, RegisterForm, ForgotPasswordForm, ResetPasswordForm, LogoutButton, useCurrentUser, ProfileForm, ChangePasswordForm, DeleteAccountForm, AUTH_LABELS, AUTH_PATHS, type AuthLabels, type AuthPaths, type SignInProvider } from "./auth-forms.js";
13
+ export { LoginForm, RegisterForm, ForgotPasswordForm, ResetPasswordForm, LogoutButton, LoginOutLink, useCurrentUser, ProfileForm, ChangePasswordForm, DeleteAccountForm, AUTH_LABELS, AUTH_PATHS, type AuthLabels, type AuthPaths, type SignInProvider } from "./auth-forms.js";
14
14
  export { buildDocumentMetadata } from "./metadata.js";
15
15
  /** Lấy giá trị Customizer của theme đang active. */
16
16
  export declare function getThemeSettings(): Promise<import("./types.js").JsonObject>;
package/dist/index.js CHANGED
@@ -10,7 +10,7 @@ export { getRequestLocale, localeHref, LOCALE_HEADER } from "./locale.js";
10
10
  export { CommentForm, CommentList, CommentsMore, ExtensionBoundary, PostPasswordForm, Link, isInternalHref } from "./client.js";
11
11
  export { getPreference } from "./preferences.js";
12
12
  export { getCurrentUser, getAccessToken, requireUser, userCan, safeRedirect, ACCESS_COOKIE, REFRESH_COOKIE } from "./auth.js";
13
- export { LoginForm, RegisterForm, ForgotPasswordForm, ResetPasswordForm, LogoutButton, useCurrentUser, ProfileForm, ChangePasswordForm, DeleteAccountForm, AUTH_LABELS, AUTH_PATHS } from "./auth-forms.js";
13
+ export { LoginForm, RegisterForm, ForgotPasswordForm, ResetPasswordForm, LogoutButton, LoginOutLink, useCurrentUser, ProfileForm, ChangePasswordForm, DeleteAccountForm, AUTH_LABELS, AUTH_PATHS } from "./auth-forms.js";
14
14
  export { buildDocumentMetadata } from "./metadata.js";
15
15
  /** Lấy giá trị Customizer của theme đang active. */
16
16
  export async function getThemeSettings() {
package/dist/metadata.js CHANGED
@@ -5,7 +5,7 @@ export async function buildDocumentMetadata(data, site) {
5
5
  const base = {
6
6
  title: isHome ? `${site.title}${site.tagline ? ` – ${site.tagline}` : ""}` : `${data.title} – ${site.title}`,
7
7
  description: data.post?.excerpt || (data.term?.description || undefined) || site.tagline,
8
- canonical: data.post?.link ?? (data.basePath || undefined),
8
+ canonical: data.post?.link ? data.post.link + (Number(data.query?.trang) > 1 ? `?trang=${Math.floor(Number(data.query?.trang))}` : "") : (data.basePath || undefined),
9
9
  alternates: Object.fromEntries((data.alternates ?? []).map((a) => [a.locale, a.link])),
10
10
  openGraph: {
11
11
  title: data.post?.title ?? data.title,
package/dist/rich.d.ts CHANGED
@@ -13,6 +13,8 @@ export interface RenderContext {
13
13
  /** Khối của plugin: khối cấp cao nhất và nút trong nội dung soạn thảo dùng chung một renderer (definePlugin → blocks). */
14
14
  block(type: string): Promise<ComponentType<BlockProps> | null>;
15
15
  };
16
+ /** Filter "block.render": plugin bọc / thay phần tử đã vẽ của MỌI khối (kể cả khối lõi). Chỉ có khi có plugin đăng ký filter này. */
17
+ filterBlock?(node: Node, el: ReactNode): Promise<ReactNode>;
16
18
  /** Bọc component của plugin (lỗi chỉ ẩn phần đó). Mặc định: không bọc. */
17
19
  boundary?(name: string, key: string, el: ReactNode): ReactNode;
18
20
  /** Khối của plugin (defineBlock) — chuẩn hoá thuộc tính + nâng phiên bản khối lưu bằng bản cũ. */
@@ -26,10 +28,13 @@ export interface RenderContext {
26
28
  data?: ResolveResult;
27
29
  /** Vẽ khối động (@ecomcx/ecomweb-content DYNAMIC_NODES). Không có → khối động bị bỏ qua. */
28
30
  dynamic?(node: RenderNode, key: string, ctx: RenderContext, children: (ctx: RenderContext, nodes?: RenderNode[]) => Promise<ReactNode[]>): Promise<ReactNode>;
31
+ /** Tên nhóm của khối accordion đang vẽ: các `details` con dùng chung `name` để mở một mục thì mục khác đóng. */
32
+ accordion?: string;
29
33
  /** Bài của vòng lặp `query` gần nhất (+ dữ liệu phân trang khi dùng danh sách của trang). */
30
34
  query?: {
31
35
  posts: Post[];
32
36
  data?: ResolveResult;
37
+ pageParam?: string;
33
38
  };
34
39
  /** Nội dung template part theo slug (khối templatePart). */
35
40
  parts?(slug: string): Promise<ContentDoc | null>;
@@ -50,6 +55,14 @@ export interface RenderContext {
50
55
  id: string;
51
56
  text: string;
52
57
  }>;
58
+ /** Chú thích của mark `footnote` trong nội dung đang vẽ (đánh số theo thứ tự xuất hiện). shortcut: chỉ gom trong một lần renderContent, mẫu đồng bộ lồng vào không có số. */
59
+ footnotes?: {
60
+ notes: Array<{
61
+ note: string;
62
+ mark: object;
63
+ }>;
64
+ prefix: string;
65
+ };
53
66
  /**
54
67
  * Đang xem bản nháp (Trình dựng / xem trực tiếp): gắn data-ecx-doc + data-ecx-path cho từng khối để khung soạn ở admin
55
68
  * biết người dùng bấm vào khối nào. `source` = tài liệu đang vẽ ("template:single", "part:header", "post:12", "pattern:3").
package/dist/rich.js CHANGED
@@ -1,8 +1,10 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { Fragment, cloneElement, isValidElement } from "react";
3
+ import { ICON_PATHS } from "./icons.js";
3
4
  import { DYNAMIC_NODES, colorCss, embedInfo, motionClasses, normalizeContent, safeUrl, spacingValue, styleClass, styleCss } from "@ecomcx/ecomweb-content";
4
5
  import { cx } from "./utils.js";
5
6
  import { SOCIAL_ICONS } from "./social-icons.js";
7
+ import { CountdownClient, LightboxClient, TabsClient } from "./client.js";
6
8
  const DYNAMIC = new Set(DYNAMIC_NODES);
7
9
  const SHORTCODE = /^\s*\[([a-z0-9_-]+)((?:\s+[a-z0-9_-]+=(?:"[^"]*"|'[^']*'|[^\s\]]+))*)\s*\]\s*$/i;
8
10
  const SHORTCODE_INLINE = /\[([a-z0-9_-]+)((?:\s+[a-z0-9_-]+=(?:"[^"]*"|'[^']*'|[^\s\]]+))*)\s*\]/gi;
@@ -34,6 +36,20 @@ function collectHeadings(blocks) {
34
36
  walk(b.data);
35
37
  return out;
36
38
  }
39
+ function collectFootnotes(blocks) {
40
+ const out = [];
41
+ const walk = (n) => {
42
+ for (const m of n.marks ?? [])
43
+ if (m.type === "footnote" && typeof m.attrs?.note === "string" && m.attrs.note)
44
+ out.push({ note: m.attrs.note, mark: m });
45
+ for (const c of n.content ?? [])
46
+ walk(c);
47
+ };
48
+ for (const b of blocks)
49
+ if (b.type === "richtext" && b.data)
50
+ walk(b.data);
51
+ return out;
52
+ }
37
53
  function plainText(node) {
38
54
  if (node.type === "text")
39
55
  return node.text ?? "";
@@ -47,7 +63,7 @@ const TONES = { info: "#2563eb", success: "#16a34a", warning: "#d97706", danger:
47
63
  function alignStyle(attrs) {
48
64
  return attrs?.textAlign && attrs.textAlign !== "left" ? { textAlign: attrs.textAlign } : undefined;
49
65
  }
50
- function renderMarks(text, marks, key) {
66
+ function renderMarks(text, marks, key, ctx) {
51
67
  let out = text;
52
68
  for (const [i, m] of (marks ?? []).entries()) {
53
69
  const k = `${key}-m${i}`;
@@ -67,6 +83,16 @@ function renderMarks(text, marks, key) {
67
83
  case "code":
68
84
  out = _jsx("code", { children: out }, k);
69
85
  break;
86
+ case "footnote": {
87
+ const f = ctx?.footnotes;
88
+ const n = f ? f.notes.findIndex((x) => x.mark === m) + 1 : 0;
89
+ if (n > 0)
90
+ out = _jsxs(Fragment, { children: [out, _jsx("sup", { className: "ecx-footnote-ref", id: `fnref-${f.prefix}-${n}`, children: _jsxs("a", { href: `#fn-${f.prefix}-${n}`, children: ["[", n, "]"] }) })] }, k);
91
+ break;
92
+ }
93
+ case "kbd":
94
+ out = _jsx("kbd", { children: out }, k);
95
+ break;
70
96
  case "subscript":
71
97
  out = _jsx("sub", { children: out }, k);
72
98
  break;
@@ -191,7 +217,9 @@ async function applyBindings(node, ctx) {
191
217
  async function renderNode(node, key, ctx) {
192
218
  if (node.attrs?.bindings)
193
219
  node = await applyBindings(node, ctx);
194
- const el = await renderNodeInner(node, key, ctx);
220
+ let el = await renderNodeInner(node, key, ctx);
221
+ if (ctx.filterBlock && node.type !== "text" && node.type !== "doc")
222
+ el = await ctx.filterBlock(node, el);
195
223
  const a = node.attrs;
196
224
  const out = a && (a.style || a.blockStyle || a.className || a.anchor) ? decorate(el, a, key, ctx) : el;
197
225
  return ctx.markBlocks && ctx.source && ctx.pathRoot != null && key.startsWith(ctx.pathRoot + "-") && !UNMARKED.has(node.type)
@@ -214,7 +242,7 @@ async function renderNodeInner(node, key, ctx) {
214
242
  const a = node.attrs ?? {};
215
243
  switch (node.type) {
216
244
  case "doc": return _jsx(Fragment, { children: await children() }, key);
217
- case "text": return renderMarks(node.text ?? "", node.marks, key);
245
+ case "text": return renderMarks(node.text ?? "", node.marks, key, ctx);
218
246
  case "paragraph": {
219
247
  // Đoạn văn chỉ chứa shortcode → render component của plugin.
220
248
  const text = plainText(node);
@@ -236,36 +264,53 @@ async function renderNodeInner(node, key, ctx) {
236
264
  return _jsx(Tag, { id: id || undefined, style: alignStyle(a), children: await children() }, key);
237
265
  }
238
266
  case "bulletList": return _jsx("ul", { children: await children() }, key);
239
- case "orderedList": return _jsx("ol", { start: a.start && a.start !== 1 ? a.start : undefined, children: await children() }, key);
267
+ case "orderedList": return _jsx("ol", { start: a.start && a.start !== 1 ? a.start : undefined, reversed: a.reversed === true || undefined, children: await children() }, key);
240
268
  case "listItem": return _jsx("li", { children: await children() }, key);
241
269
  case "taskList": return _jsx("ul", { className: "ecx-task-list task-list", children: await children() }, key);
242
270
  case "taskItem": return _jsxs("li", { className: "ecx-task-item task-item", children: [_jsx("input", { type: "checkbox", checked: !!a.checked, readOnly: true }), " ", await children()] }, key);
243
- case "blockquote": return _jsx("blockquote", { children: await children() }, key);
271
+ case "blockquote": return _jsxs("blockquote", { children: [await children(), a.citation && _jsx("cite", { children: a.citation })] }, key);
244
272
  case "codeBlock": return _jsx("pre", { children: _jsx("code", { className: a.language ? `language-${a.language}` : undefined, children: plainText(node) }) }, key);
245
273
  case "hardBreak": return _jsx("br", {}, key);
274
+ case "pageBreak": return null;
275
+ case "footnotes": {
276
+ const f = ctx.footnotes;
277
+ if (!f?.notes.length)
278
+ return null;
279
+ return (_jsxs("aside", { className: "ecx-footnotes", children: [a.title && _jsx("p", { className: "ecx-footnotes-title", children: a.title }), _jsx("ol", { children: f.notes.map((x, i) => _jsxs("li", { id: `fn-${f.prefix}-${i + 1}`, children: [x.note, " ", _jsx("a", { href: `#fnref-${f.prefix}-${i + 1}`, "aria-label": "\u21A9", children: "\u21A9" })] }, i)) })] }, key));
280
+ }
281
+ case "icon": {
282
+ const path = ICON_PATHS[String(a.name)];
283
+ if (!path)
284
+ return null;
285
+ const size = Math.min(128, Math.max(12, Number(a.size) || 24));
286
+ return _jsx("div", { className: "ecx-icon-block", style: alignStyle(a), children: _jsx("svg", { width: size, height: size, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round", role: a.label ? "img" : undefined, "aria-label": a.label || undefined, "aria-hidden": a.label ? undefined : true, children: _jsx("path", { d: path }) }) }, key);
287
+ }
246
288
  case "horizontalRule": return _jsx("hr", {}, key);
247
289
  case "image": {
248
290
  // Ảnh chèn từ thư viện mang sẵn srcset (JPEG + WebP) và kích thước → responsive, không nhảy layout
249
291
  // Bề rộng hiển thị = cỡ người viết kéo trong trình soạn → trình duyệt chọn file vừa đúng
250
292
  const sizes = a.width ? `(max-width: ${a.width}px) 100vw, ${a.width}px` : (a.sizes || "(max-width: 1024px) 100vw, 1024px");
251
293
  const img = _jsx("img", { src: safeUrl(a.src, ""), srcSet: a.srcset || undefined, sizes: a.srcset ? sizes : undefined, alt: a.alt ?? "", title: a.title ?? undefined, width: a.width ?? undefined, height: a.height ?? undefined, loading: "lazy", decoding: "async" });
252
- const pic = a.webpSrcset ? _jsxs("picture", { children: [_jsx("source", { type: "image/webp", srcSet: a.webpSrcset, sizes: sizes }), img] }) : img;
294
+ const bare = a.webpSrcset ? _jsxs("picture", { children: [_jsx("source", { type: "image/webp", srcSet: a.webpSrcset, sizes: sizes }), img] }) : img;
295
+ // next: ảnh có liên kết (href qua safeUrl; mở tab mới thì noopener)
296
+ const pic = a.lightbox === true && !a.href ? _jsx(LightboxClient, { src: safeUrl(a.src, ""), alt: a.alt ?? "", children: bare }) : a.href ? _jsx("a", { href: safeUrl(a.href), target: a.linkTarget === "_blank" ? "_blank" : undefined, rel: a.linkTarget === "_blank" ? "noopener noreferrer" : undefined, children: bare }) : bare;
253
297
  const cls = cx("ecx-image cms-image", a.align && `ecx-align-${a.align} align${a.align}`, a.mediaId && `ecx-image-${a.mediaId} cms-image-${a.mediaId}`);
254
298
  return a.caption || a.align ? _jsxs("figure", { className: cls, children: [pic, a.caption && _jsx("figcaption", { children: a.caption })] }, key) : _jsx(Fragment, { children: pic }, key);
255
299
  }
256
300
  case "gallery": {
257
301
  const items = (a.images ?? []);
258
302
  const cols = Math.min(6, Math.max(1, Number(a.columns) || 3));
303
+ const crop = a.imageCrop !== false; // next: imageCrop=false giữ nguyên tỉ lệ ảnh
259
304
  return (_jsxs("figure", { className: cx("ecx-gallery cms-gallery", `ecx-gallery-columns-${cols} columns-${cols}`), style: { display: "grid", gap: 8, gridTemplateColumns: `repeat(${cols}, minmax(0, 1fr))` }, children: [items.map((im, i) => {
260
- const el = _jsx("img", { src: safeUrl(im.src, ""), srcSet: im.srcset || undefined, sizes: `(max-width: 768px) 50vw, ${Math.round(100 / cols)}vw`, alt: im.alt ?? "", width: im.width, height: im.height, loading: "lazy", decoding: "async", style: { width: "100%", height: "100%", objectFit: "cover", aspectRatio: "1" } });
305
+ const el = _jsx("img", { src: safeUrl(im.src, ""), srcSet: im.srcset || undefined, sizes: `(max-width: 768px) 50vw, ${Math.round(100 / cols)}vw`, alt: im.alt ?? "", width: im.width, height: im.height, loading: "lazy", decoding: "async", style: crop ? { width: "100%", height: "100%", objectFit: "cover", aspectRatio: "1" } : { width: "100%", height: "auto" } });
261
306
  const pic = im.webpSrcset ? _jsxs("picture", { children: [_jsx("source", { type: "image/webp", srcSet: im.webpSrcset, sizes: `(max-width: 768px) 50vw, ${Math.round(100 / cols)}vw` }), el] }) : el;
262
- return _jsxs("figure", { className: "ecx-gallery-item cms-gallery-item", style: { margin: 0 }, children: [im.full ? _jsx("a", { href: safeUrl(im.full), children: pic }) : pic, im.caption && _jsx("figcaption", { children: im.caption })] }, i);
307
+ return _jsxs("figure", { className: "ecx-gallery-item cms-gallery-item", style: { margin: 0 }, children: [a.lightbox === true ? _jsx(LightboxClient, { src: safeUrl(im.full || im.src, ""), alt: im.alt ?? "", children: pic }) : im.full && a.linkTo !== "none" ? _jsx("a", { href: safeUrl(im.full), children: pic }) : pic, im.caption && _jsx("figcaption", { children: im.caption })] }, i);
263
308
  }), a.caption && _jsx("figcaption", { className: "ecx-gallery-caption cms-gallery-caption", style: { gridColumn: "1 / -1" }, children: a.caption })] }, key));
264
309
  }
265
310
  case "video":
266
- return _jsxs("figure", { className: "ecx-video cms-video", children: [_jsx("video", { src: safeUrl(a.src, ""), poster: a.poster ? safeUrl(a.poster, "") : undefined, controls: true, preload: "metadata", playsInline: true, style: { width: "100%", height: "auto" } }), a.caption && _jsx("figcaption", { children: a.caption })] }, key);
311
+ return _jsxs("figure", { className: "ecx-video cms-video", children: [_jsx("video", { src: safeUrl(a.src, ""), poster: a.poster ? safeUrl(a.poster, "") : undefined, controls: a.controls !== false, autoPlay: a.autoplay === true, loop: a.loop === true, muted: a.muted === true || a.autoplay === true, preload: ["none", "metadata", "auto"].includes(a.preload) ? a.preload : "metadata", playsInline: a.playsInline !== false, style: { width: "100%", height: "auto" } }), a.caption && _jsx("figcaption", { children: a.caption })] }, key);
267
312
  case "audio":
268
- return _jsxs("figure", { className: "ecx-audio cms-audio", children: [_jsx("audio", { src: safeUrl(a.src, ""), controls: true, preload: "metadata", style: { width: "100%" } }), a.caption && _jsx("figcaption", { children: a.caption })] }, key);
313
+ return _jsxs("figure", { className: "ecx-audio cms-audio", children: [_jsx("audio", { src: safeUrl(a.src, ""), controls: true, autoPlay: a.autoplay === true, loop: a.loop === true, preload: ["none", "metadata", "auto"].includes(a.preload) ? a.preload : "metadata", style: { width: "100%" } }), a.caption && _jsx("figcaption", { children: a.caption })] }, key);
269
314
  case "file": {
270
315
  const isPdf = String(a.mime ?? "").includes("pdf") || /\.pdf($|\?)/i.test(String(a.src ?? ""));
271
316
  return (_jsxs("div", { className: "ecx-file cms-file", children: [isPdf && a.embed !== false && _jsx("object", { data: safeUrl(a.src, ""), type: "application/pdf", style: { width: "100%", height: 600 }, "aria-label": a.name, children: _jsx("a", { href: safeUrl(a.src), children: a.name }) }), _jsx("a", { className: "ecx-file-link cms-file-link", href: safeUrl(a.src), download: a.download ? "" : undefined, target: "_blank", rel: "noopener", children: a.name || ctx.labels?.download || "Download" })] }, key));
@@ -347,8 +392,44 @@ async function renderNodeInner(node, key, ctx) {
347
392
  }
348
393
  case "pullquote":
349
394
  return _jsxs("figure", { className: "ecx-pullquote", children: [_jsx("blockquote", { children: _jsx("p", { children: await children() }) }), a.citation && _jsx("figcaption", { children: a.citation })] }, key);
395
+ case "accordion": {
396
+ const sub = a.multiple === true ? ctx : { ...ctx, accordion: `ecx-acc-${key}` };
397
+ return _jsx("div", { className: "ecx-accordion", children: await Promise.all((node.content ?? []).map((c, i) => renderNode(c, `${key}-${i}`, sub))) }, key);
398
+ }
399
+ case "countdown": {
400
+ const ms = Date.parse(String(a.target ?? ""));
401
+ if (!Number.isFinite(ms))
402
+ return null;
403
+ return _jsx(CountdownClient, { target: ms, label: a.label ? String(a.label) : undefined, expiredText: a.expiredText ? String(a.expiredText) : undefined }, key);
404
+ }
405
+ case "rating": {
406
+ const max = Math.min(10, Math.max(1, Math.round(Number(a.max) || 5)));
407
+ const v = Math.min(max, Math.max(0, Number(a.value) || 0));
408
+ return (_jsxs("div", { className: "ecx-rating", role: "img", "aria-label": `${v}/${max}`, children: [Array.from({ length: max }, (_, i) => _jsx("span", { "aria-hidden": "true", className: i < Math.round(v) ? "is-on" : "is-off", style: { color: i < Math.round(v) ? "#f59e0b" : "#d4d4d8" }, children: "\u2605" }, i)), a.label && _jsxs("span", { className: "ecx-rating-label", children: [" ", String(a.label)] })] }, key));
409
+ }
410
+ case "tabs": {
411
+ const tabs = (node.content ?? []).filter((c) => c.type === "tab");
412
+ if (!tabs.length)
413
+ return null;
414
+ const panels = await Promise.all(tabs.map(async (t, i) => _jsx(Fragment, { children: await Promise.all((t.content ?? []).map((c, j) => renderNode(c, `${key}-${i}-${j}`, ctx))) }, i)));
415
+ return _jsx(TabsClient, { titles: tabs.map((t, i) => String(t.attrs?.title || `Tab ${i + 1}`)), panels: panels }, key);
416
+ }
417
+ case "tab":
418
+ return _jsx("div", { className: "ecx-tab", children: await children() }, key);
419
+ case "carousel": {
420
+ const per = Math.min(4, Math.max(1, Math.round(Number(a.slidesPerView) || 1)));
421
+ const kids = await Promise.all((node.content ?? []).map(async (c, i) => _jsx("div", { className: "ecx-carousel-slide", style: { scrollSnapAlign: "start" }, children: await renderNode(c, `${key}-${i}`, ctx) }, i)));
422
+ return _jsx("div", { className: "ecx-carousel", role: "region", "aria-roledescription": "carousel", tabIndex: 0, style: { display: "grid", gridAutoFlow: "column", gridAutoColumns: `calc((100% - ${(per - 1) * 16}px) / ${per})`, gap: 16, overflowX: "auto", scrollSnapType: "x mandatory" }, children: kids }, key);
423
+ }
424
+ case "shortcode": {
425
+ const name = String(a.name ?? "");
426
+ if (!/^[a-z0-9_-]{1,64}$/i.test(name))
427
+ return null;
428
+ const Comp = await ctx.resolve.shortcode(name);
429
+ return Comp ? _jsx(Comp, { attrs: (a.args && typeof a.args === "object" ? a.args : {}), site: ctx.site, post: ctx.post }, key) : null;
430
+ }
350
431
  case "details":
351
- return _jsxs("details", { className: "ecx-details", open: a.open === true || undefined, children: [_jsx("summary", { children: a.summary || "…" }), await children()] }, key);
432
+ return _jsxs("details", { className: "ecx-details", name: ctx.accordion, open: a.open === true || undefined, children: [_jsx("summary", { children: a.summary || "…" }), await children()] }, key);
352
433
  case "customHtml":
353
434
  // Máy chủ đã lọc HTML khi người soạn thiếu quyền unfiltered_html (ContentSanitizer)
354
435
  return a.html ? _jsx("div", { className: "ecx-html", dangerouslySetInnerHTML: { __html: String(a.html) } }, key) : null;
@@ -434,8 +515,10 @@ export async function renderContent(content, ctx, transform) {
434
515
  const blocks = transform ? await transform(doc.blocks) : doc.blocks;
435
516
  // Lần vẽ ngoài cùng gom CSS kiểu dáng của mọi khối (kể cả phần lồng bên trong) thành một thẻ <style>
436
517
  const own = !ctx.styles;
437
- if (own)
438
- ctx = { ...ctx, styles: new Map(), headings: ctx.headings ?? collectHeadings(blocks) };
518
+ if (own) {
519
+ const notes = collectFootnotes(blocks);
520
+ ctx = { ...ctx, styles: new Map(), headings: ctx.headings ?? collectHeadings(blocks), footnotes: ctx.footnotes ?? (notes.length ? { notes, prefix: String(ctx.post?.id ?? "x") } : undefined) };
521
+ }
439
522
  const out = await Promise.all(blocks.map((b, i) => renderBlock(b, b.id ?? `b${i}`, ctx)));
440
523
  if (own && ctx.styles.size)
441
524
  out.unshift(_jsx("style", { "data-ecx-styles": "", children: [...ctx.styles.values()].join("") }, "ecx-styles"));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ecomcx/ecomweb-theme-sdk",
3
- "version": "1.32.0",
3
+ "version": "1.34.0",
4
4
  "description": "SDK để viết theme và phần frontend của plugin cho Ecomweb",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -33,7 +33,7 @@
33
33
  "README.md"
34
34
  ],
35
35
  "dependencies": {
36
- "@ecomcx/ecomweb-content": "^1.16.0",
36
+ "@ecomcx/ecomweb-content": "^1.18.0",
37
37
  "intl-messageformat": "12.1.3"
38
38
  },
39
39
  "peerDependencies": {