@ecomcx/ecomweb-theme-sdk 2.0.0 → 2.1.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/API.md CHANGED
@@ -209,7 +209,7 @@ ResetPasswordForm({ labels, paths }: { labels?: Partial<AuthLabels>; paths?: Par
209
209
  Ô tìm kiếm — gửi về trang chủ của ngôn ngữ hiện tại (/?s= hoặc /en?s=).
210
210
 
211
211
  ```ts
212
- SearchForm({ defaultValue, placeholder, buttonLabel, postType, showLabel, buttonPosition, buttonIcon }: { buttonIcon?: boolean; defaultValue?: string | null; placeholder?: string; buttonLabel?: string; postType?: string; showLabel?: boolean; buttonPosition?: "right" | "left" | "below"; }): Promise<JSX.Element>
212
+ SearchForm({ defaultValue, placeholder, buttonLabel, postType, showLabel, buttonPosition, buttonIcon, scopes, scopeType, collapse }: { collapse?: "tablet" | "mobile"; scopes?: Array<{ value: string; label: string; }>; scopeType?: string; buttonIcon?: boolean; defaultValue?: string | null; placeholder?: string; buttonLabel?: string; postType?: string; showLabel?: boolean; buttonPosition?: "right" | "left" | "below"; }): Promise<JSX.Element>
213
213
  ```
214
214
 
215
215
  #### `Slot`
@@ -1375,12 +1375,36 @@ Phóng to ảnh: bấm ảnh mở lớp phủ (Esc hoặc bấm nền để đó
1375
1375
  LightboxClient({ src, alt, children }: { src: string; alt: string; children: ReactNode; }): JSX.Element
1376
1376
  ```
1377
1377
 
1378
+ #### `NavDrawer`
1379
+
1380
+ Menu di động của khối Menu: nút burger mở ngăn trượt từ trái (nền mờ, nút đóng, khoá cuộn trang, Esc / bấm nền / bấm liên kết để đóng, trả focus về nút). Menu con hiện thụt vào ngay dưới mục cha. Khác NavToggle (giữ nguyên cho theme cũ dùng <details>).
1381
+
1382
+ ```ts
1383
+ NavDrawer({ label, closeLabel, children }: { label: string; closeLabel: string; children: ReactNode; }): JSX.Element
1384
+ ```
1385
+
1386
+ #### `QueryFilterBar`
1387
+
1388
+ Thanh lọc của khối Query (GET): ô tìm, mục phân loại (liên kết tới trang mục / nút lọc / ô chọn), sắp xếp. Giá trị lên URL dạng ?fq_s, ?fq_sort, ?fq_<phân loại>; khối Query bật "Nhận bộ lọc từ thanh lọc" đọc lại. Ô chọn tự gửi khi đổi.
1389
+
1390
+ ```ts
1391
+ QueryFilterBar({ action, taxonomy, termStyle, terms, currentTerm, values, showSearch, showSort, sorts, labels }: { action: string; taxonomy?: string; termStyle: "none" | "links" | "chips" | "select"; terms: Array<{ slug: string; name: string; link: string; }>; currentTerm?: string; values: Record<string, string>; showSearch: boolean; showSort: boolean; sorts: Array<{ value: string; label: string; }>; labels: { all: string; search: string; placeholder: string; submit: string; sort: string; }; }): JSX.Element
1392
+ ```
1393
+
1394
+ #### `ScrollRow`
1395
+
1396
+ Hàng cuộn ngang có nút trước / sau (Query dạng carousel): cuộn đúng một "trang" mỗi lần bấm, ẩn nút ở hai đầu. Không có JS vẫn vuốt / cuộn được.
1397
+
1398
+ ```ts
1399
+ ScrollRow({ children, arrows }: { children: ReactNode; arrows?: boolean; }): JSX.Element
1400
+ ```
1401
+
1378
1402
  #### `SearchFormClient`
1379
1403
 
1380
1404
  Form tìm kiếm (GET) chuyển trang phía client.
1381
1405
 
1382
1406
  ```ts
1383
- SearchFormClient({ action, defaultValue, placeholder, label, buttonLabel, postType, showLabel, buttonPosition, buttonIcon }: { buttonIcon?: boolean; action: string; defaultValue?: string | null; placeholder: string; label: string; buttonLabel: string; postType?: string; showLabel?: boolean; buttonPosition?: "right" | "left" | "below"; }): JSX.Element
1407
+ SearchFormClient({ action, defaultValue, placeholder, label, buttonLabel, postType, showLabel, buttonPosition, buttonIcon, scopes, scopeAllLabel, scopeLabel, scopeValue, collapse }: { collapse?: "tablet" | "mobile"; scopes?: Array<{ value: string; label: string; }>; scopeAllLabel?: string; scopeLabel?: string; scopeValue?: string; buttonIcon?: boolean; action: string; defaultValue?: string | null; placeholder: string; label: string; buttonLabel: string; postType?: string; showLabel?: boolean; buttonPosition?: "right" | "left" | "below"; }): JSX.Element
1384
1408
  ```
1385
1409
 
1386
1410
  #### `TabsClient`
package/CHANGELOG.md CHANGED
@@ -2,6 +2,18 @@
2
2
 
3
3
  Theo [SemVer](https://semver.org/lang/vi/): bản lớn (x.0.0) mới được đổi hoặc bỏ API công khai. Tên công khai là tên có trong [API.md](API.md).
4
4
 
5
+ ## 2.1.0 (17/11/2026)
6
+
7
+ ### Thêm (không phá tương thích)
8
+ - `getPosts({ extra })`: chuyển tham số `fq_…` của URL cho plugin đọc qua filter `posts.query` (vd lọc giá của plugin bán hàng).
9
+ - Khối Query: bộ lọc nguồn (mới nhất / chọn tay / liên quan), nhiều mục của phân loại, trường tuỳ biến, khoảng ngày, bài con, bỏ N bài đầu, loại bài đang xem, cùng tác giả, nhận bộ lọc từ thanh lọc (`urlFilters`); lọc theo `taxonomy` + `term`.
10
+ - Khối `queryFilter` (thanh lọc: tìm, phân loại dạng liên kết / nút / ô chọn, sắp xếp) và component `QueryFilterBar` (`/client`).
11
+ - Khuôn mỗi bài dạng `carousel` (`ScrollRow`, `/client`), `columnsTablet`, `columnsMobile`, `gap`.
12
+ - Khối Tìm kiếm: `scopeSelect` + `scopes` (ô chọn phạm vi), `collapse` (thu thành nút kính lúp trên tablet / điện thoại).
13
+ - Khối Menu: `NavDrawer` (ngăn trượt, gắn vào `<body>`), `overlayMenu: "tablet"`; menu con thả xuống trên máy tính.
14
+ - Binding `hideIfEmpty` (ẩn khối khi nguồn không có giá trị); core tự gán `formId`.
15
+ - `?type=any` / `?type=a,b` cho tìm kiếm của website (core).
16
+
5
17
  ## 2.0.0 (16/11/2026)
6
18
 
7
19
  ### Phá tương thích, cần làm khi nâng cấp
package/dist/api.d.ts CHANGED
@@ -125,6 +125,12 @@ export interface PostQuery {
125
125
  * Khoá chưa khai báo trả 422 (không có chỉ mục thì sắp xếp phải quét toàn bảng).
126
126
  */
127
127
  orderByMeta?: string;
128
+ /**
129
+ * Tham số bộ lọc phụ do plugin đọc (filter `posts.query`, `PostQueryData.Query`): chỉ nhận khoá `fq_…`, giá trị ≤ 100 ký tự —
130
+ * vd plugin bán hàng đọc `fq_price_min`, `fq_price_max`, `fq_sale`, `fq_stock`, `fq_sort=price_asc`. Khối Query bật "Nhận bộ lọc từ thanh lọc" tự chuyển các `fq_…` trên URL vào đây.
131
+ * @since 2.1.0
132
+ */
133
+ extra?: Record<string, string>;
128
134
  }
129
135
  /**
130
136
  * Danh sách bài đã đăng theo điều kiện (tương đương `WP_Query`). Mặc định không kèm nội dung đầy đủ (`withContent`).
package/dist/api.js CHANGED
@@ -136,9 +136,10 @@ export const getPreview = (token) => cmsFetch("/preview", { noStore: true, query
136
136
  export const getPosts = async ({ withContent, ...q } = {}) => {
137
137
  // Bóc tách TRONG thân hàm, không phải trong tham số: chữ ký đã công bố của getPosts nằm trong baseline
138
138
  // hợp đồng (api/theme-sdk.txt) nên thêm tên vào tham số là đổi một dòng đã ký (CI coi là phá hợp đồng).
139
- const { taxQuery, metaQuery, ...rest } = q;
139
+ const { taxQuery, metaQuery, extra, ...rest } = q;
140
140
  return cmsFetch("/posts", { tags: ["posts"], query: clean({
141
141
  ...postQueryParams(rest),
142
+ ...Object.fromEntries(Object.entries(extra ?? {}).filter(([k, v]) => /^fq_[a-z0-9_-]{1,40}$/i.test(k) && typeof v === "string" && v.length <= 100)),
142
143
  // Bộ lọc phức tạp đi dạng JSON — core phân tích và áp thẳng vào câu SQL (không lọc bằng bộ nhớ).
143
144
  taxQuery: taxQuery?.length ? JSON.stringify(taxQuery) : undefined,
144
145
  metaQuery: metaQuery?.clauses?.length ? JSON.stringify(metaQuery) : undefined,
package/dist/client.d.ts CHANGED
@@ -51,7 +51,15 @@ export type LinkProps = Omit<AnchorHTMLAttributes<HTMLAnchorElement>, "href"> &
51
51
  */
52
52
  export declare function Link({ href, prefetch, activeClassName, matchNested, className, children, ...rest }: LinkProps): import("react").JSX.Element;
53
53
  /** Form tìm kiếm (GET) chuyển trang phía client. */
54
- export declare function SearchFormClient({ action, defaultValue, placeholder, label, buttonLabel, postType, showLabel, buttonPosition, buttonIcon }: {
54
+ export declare function SearchFormClient({ action, defaultValue, placeholder, label, buttonLabel, postType, showLabel, buttonPosition, buttonIcon, scopes, scopeAllLabel, scopeLabel, scopeValue, collapse }: {
55
+ collapse?: "tablet" | "mobile";
56
+ scopes?: Array<{
57
+ value: string;
58
+ label: string;
59
+ }>;
60
+ scopeAllLabel?: string;
61
+ scopeLabel?: string;
62
+ scopeValue?: string;
55
63
  buttonIcon?: boolean;
56
64
  action: string;
57
65
  defaultValue?: string | null;
@@ -200,3 +208,46 @@ export declare function FormBlockClient({ formId, source, successMessage, labels
200
208
  className?: string;
201
209
  children?: ReactNode;
202
210
  }): import("react").JSX.Element;
211
+ /** Hàng cuộn ngang có nút trước / sau (Query dạng carousel): cuộn đúng một "trang" mỗi lần bấm, ẩn nút ở hai đầu. Không có JS vẫn vuốt / cuộn được. */
212
+ export declare function ScrollRow({ children, arrows }: {
213
+ children: ReactNode;
214
+ arrows?: boolean;
215
+ }): import("react").JSX.Element;
216
+ /**
217
+ * Menu di động của khối Menu: nút burger mở ngăn trượt từ trái (nền mờ, nút đóng, khoá cuộn trang, Esc / bấm nền / bấm liên kết để đóng,
218
+ * trả focus về nút). Menu con hiện thụt vào ngay dưới mục cha. Khác NavToggle (giữ nguyên cho theme cũ dùng <details>).
219
+ */
220
+ export declare function NavDrawer({ label, closeLabel, children }: {
221
+ label: string;
222
+ closeLabel: string;
223
+ children: ReactNode;
224
+ }): import("react").JSX.Element;
225
+ /**
226
+ * Thanh lọc của khối Query (GET): ô tìm, mục phân loại (liên kết tới trang mục / nút lọc / ô chọn), sắp xếp.
227
+ * Giá trị lên URL dạng ?fq_s, ?fq_sort, ?fq_<phân loại>; khối Query bật "Nhận bộ lọc từ thanh lọc" đọc lại. Ô chọn tự gửi khi đổi.
228
+ */
229
+ export declare function QueryFilterBar({ action, taxonomy, termStyle, terms, currentTerm, values, showSearch, showSort, sorts, labels }: {
230
+ action: string;
231
+ taxonomy?: string;
232
+ termStyle: "none" | "links" | "chips" | "select";
233
+ terms: Array<{
234
+ slug: string;
235
+ name: string;
236
+ link: string;
237
+ }>;
238
+ currentTerm?: string;
239
+ values: Record<string, string>;
240
+ showSearch: boolean;
241
+ showSort: boolean;
242
+ sorts: Array<{
243
+ value: string;
244
+ label: string;
245
+ }>;
246
+ labels: {
247
+ all: string;
248
+ search: string;
249
+ placeholder: string;
250
+ submit: string;
251
+ sort: string;
252
+ };
253
+ }): import("react").JSX.Element;
package/dist/client.js CHANGED
@@ -2,7 +2,8 @@
2
2
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
3
  import { countdownParts, SEARCH_ICON_PATH } from "@ecomcx/ecomweb-content";
4
4
  import { extraFields } from "./auth-forms.js";
5
- import { Component, Suspense, useEffect, useId, useRef, useState } from "react";
5
+ import { Component, Suspense, useCallback, useEffect, useId, useRef, useState } from "react";
6
+ import { createPortal } from "react-dom";
6
7
  import { usePathname, useRouter } from "next/navigation";
7
8
  import NextLink, { useLinkStatus } from "next/link";
8
9
  import NextForm from "next/form";
@@ -66,12 +67,34 @@ export function Link({ href, prefetch = false, activeClassName, matchNested = tr
66
67
  }, children: [children, _jsx(PendingSignal, {})] }));
67
68
  }
68
69
  /** Form tìm kiếm (GET) chuyển trang phía client. */
69
- export function SearchFormClient({ action, defaultValue, placeholder, label, buttonLabel, postType, showLabel, buttonPosition = "right", buttonIcon }) {
70
+ export function SearchFormClient({ action, defaultValue, placeholder, label, buttonLabel, postType, showLabel, buttonPosition = "right", buttonIcon, scopes, scopeAllLabel, scopeLabel, scopeValue, collapse }) {
70
71
  const id = useId();
71
72
  const button = buttonIcon
72
73
  ? _jsx("button", { type: "submit", "aria-label": buttonLabel, title: buttonLabel, children: _jsx("svg", { viewBox: "0 0 24 24", width: 18, height: 18, fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", focusable: "false", children: _jsx("path", { d: SEARCH_ICON_PATH }) }) })
73
74
  : _jsx("button", { type: "submit", children: buttonLabel });
74
- 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] }));
75
+ const form = (_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 }), scopes && scopes.length > 0
76
+ ? _jsxs("select", { name: "type", className: "search-scope", "aria-label": scopeLabel, defaultValue: scopeValue ?? "any", children: [_jsx("option", { value: "any", children: scopeAllLabel }), scopes.map((s) => _jsx("option", { value: s.value, children: s.label }, s.value))] })
77
+ : postType && _jsx("input", { type: "hidden", name: "type", value: postType }), buttonPosition !== "left" && button] }));
78
+ if (!collapse)
79
+ return form;
80
+ return _jsx(SearchCollapse, { collapse: collapse, label: buttonLabel, children: form });
81
+ }
82
+ /** Ô tìm kiếm thu thành nút kính lúp ở tablet / điện thoại (CSS quyết định ngưỡng); bấm mở ô nhập thả xuống, Esc hoặc bấm ra ngoài để đóng. */
83
+ function SearchCollapse({ collapse, label, children }) {
84
+ const [open, setOpen] = useState(false);
85
+ const ref = useRef(null);
86
+ useEffect(() => {
87
+ if (!open)
88
+ return;
89
+ const onDown = (e) => { if (ref.current && !ref.current.contains(e.target))
90
+ setOpen(false); };
91
+ const onKey = (e) => { if (e.key === "Escape")
92
+ setOpen(false); };
93
+ document.addEventListener("mousedown", onDown);
94
+ document.addEventListener("keydown", onKey);
95
+ return () => { document.removeEventListener("mousedown", onDown); document.removeEventListener("keydown", onKey); };
96
+ }, [open]);
97
+ return (_jsxs("div", { ref: ref, className: cx("ecx-search-collapse", `collapse-${collapse}`, open && "is-open"), children: [_jsx("button", { type: "button", className: "ecx-search-toggle", "aria-label": label, "aria-expanded": open, onClick: () => setOpen((o) => !o), children: _jsx("svg", { viewBox: "0 0 24 24", width: 20, height: 20, fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", focusable: "false", children: _jsx("path", { d: SEARCH_ICON_PATH }) }) }), _jsx("div", { className: "ecx-search-panel", children: children })] }));
75
98
  }
76
99
  /** Ghi tuỳ chọn hiển thị của người đọc (xem getPreference). value = null để xoá. */
77
100
  export function setPreference(key, value, maxAgeDays = 365) {
@@ -377,3 +400,61 @@ export function FormBlockClient({ formId, source, successMessage, labels, button
377
400
  return _jsx("p", { className: "ecx-form-status is-success", role: "status", "data-form-done": formId, children: state.message });
378
401
  return (_jsxs("form", { className: cx("ecx-form-blocks", className), onSubmit: submit, noValidate: true, "data-form": formId, children: [children, extraUi, _jsx("p", { className: "ecx-form-hp", "aria-hidden": "true", children: _jsxs("label", { children: ["Website", _jsx("input", { type: "text", name: "_hp", tabIndex: -1, autoComplete: "off" })] }) }), state.status === "error" && _jsx("p", { className: "ecx-form-status is-error", role: "alert", children: state.message }), _jsx("div", { className: "ecx-form-actions", children: _jsx("button", { type: "submit", className: button?.className ?? "ecx-button", style: { border: 0, cursor: "pointer", font: "inherit", ...button?.style }, disabled: state.status === "sending", children: state.status === "sending" ? labels.sending : labels.submit }) })] }));
379
402
  }
403
+ /** Hàng cuộn ngang có nút trước / sau (Query dạng carousel): cuộn đúng một "trang" mỗi lần bấm, ẩn nút ở hai đầu. Không có JS vẫn vuốt / cuộn được. */
404
+ export function ScrollRow({ children, arrows = true }) {
405
+ const ref = useRef(null);
406
+ const [edge, setEdge] = useState({ start: true, end: false });
407
+ const update = useCallback(() => {
408
+ const el = ref.current;
409
+ if (el)
410
+ setEdge({ start: el.scrollLeft <= 2, end: el.scrollLeft + el.clientWidth >= el.scrollWidth - 2 });
411
+ }, []);
412
+ useEffect(() => {
413
+ update();
414
+ const el = ref.current;
415
+ if (!el || typeof ResizeObserver === "undefined")
416
+ return;
417
+ const ro = new ResizeObserver(update);
418
+ ro.observe(el);
419
+ return () => ro.disconnect();
420
+ }, [update]);
421
+ const go = (dir) => ref.current?.scrollBy({ left: dir * ref.current.clientWidth, behavior: "smooth" });
422
+ return (_jsxs("div", { className: "ecx-scroller", children: [_jsx("div", { className: "ecx-scroller-track", ref: ref, onScroll: update, tabIndex: 0, children: children }), arrows && !edge.start && _jsx("button", { type: "button", className: "ecx-scroller-arrow is-prev", "aria-label": "\u2190", onClick: () => go(-1), children: _jsx("svg", { viewBox: "0 0 24 24", width: 20, height: 20, fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: _jsx("path", { d: "m15 18-6-6 6-6" }) }) }), arrows && !edge.end && _jsx("button", { type: "button", className: "ecx-scroller-arrow is-next", "aria-label": "\u2192", onClick: () => go(1), children: _jsx("svg", { viewBox: "0 0 24 24", width: 20, height: 20, fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: _jsx("path", { d: "m9 18 6-6-6-6" }) }) })] }));
423
+ }
424
+ const BURGER = _jsx("svg", { viewBox: "0 0 24 24", width: 24, height: 24, fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinecap: "round", "aria-hidden": "true", focusable: "false", children: _jsx("path", { d: "M4 7h16M4 12h16M4 17h16" }) });
425
+ const CLOSE = _jsx("svg", { viewBox: "0 0 24 24", width: 22, height: 22, fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinecap: "round", "aria-hidden": "true", focusable: "false", children: _jsx("path", { d: "M18 6 6 18M6 6l12 12" }) });
426
+ /**
427
+ * Menu di động của khối Menu: nút burger mở ngăn trượt từ trái (nền mờ, nút đóng, khoá cuộn trang, Esc / bấm nền / bấm liên kết để đóng,
428
+ * trả focus về nút). Menu con hiện thụt vào ngay dưới mục cha. Khác NavToggle (giữ nguyên cho theme cũ dùng <details>).
429
+ */
430
+ export function NavDrawer({ label, closeLabel, children }) {
431
+ const [open, setOpen] = useState(false);
432
+ const [mounted, setMounted] = useState(false);
433
+ useEffect(() => setMounted(true), []);
434
+ const id = useId();
435
+ const button = useRef(null);
436
+ const close = useCallback(() => { setOpen(false); button.current?.focus(); }, []);
437
+ useEffect(() => {
438
+ if (!open)
439
+ return;
440
+ const prev = document.body.style.overflow;
441
+ document.body.style.overflow = "hidden";
442
+ const onKey = (e) => { if (e.key === "Escape")
443
+ close(); };
444
+ document.addEventListener("keydown", onKey);
445
+ return () => { document.body.style.overflow = prev; document.removeEventListener("keydown", onKey); };
446
+ }, [open, close]);
447
+ return (_jsxs("div", { className: cx("ecx-nav-drawer", open && "is-open"), children: [_jsx("button", { ref: button, type: "button", className: "ecx-nav-burger", "aria-label": label, "aria-expanded": open, "aria-controls": id, onClick: () => setOpen(true), children: BURGER }), mounted && createPortal(_jsxs("div", { className: cx("ecx-nav-drawer", "is-portal", open && "is-open"), children: [_jsx("div", { className: "ecx-nav-backdrop", onClick: close, "aria-hidden": "true" }), _jsxs("div", { id: id, className: "ecx-nav-panel", role: "dialog", "aria-modal": "true", "aria-label": label, "aria-hidden": !open, ...(!open ? { inert: true } : {}), children: [_jsx("button", { type: "button", className: "ecx-nav-close", "aria-label": closeLabel, onClick: close, children: CLOSE }), _jsx("div", { className: "ecx-nav-panel-body", onClick: (e) => { if (e.target.closest("a"))
448
+ setOpen(false); }, children: children })] })] }), document.body)] }));
449
+ }
450
+ /**
451
+ * Thanh lọc của khối Query (GET): ô tìm, mục phân loại (liên kết tới trang mục / nút lọc / ô chọn), sắp xếp.
452
+ * Giá trị lên URL dạng ?fq_s, ?fq_sort, ?fq_<phân loại>; khối Query bật "Nhận bộ lọc từ thanh lọc" đọc lại. Ô chọn tự gửi khi đổi.
453
+ */
454
+ export function QueryFilterBar({ action, taxonomy, termStyle, terms, currentTerm, values, showSearch, showSort, sorts, labels }) {
455
+ const formRef = useRef(null);
456
+ const termKey = taxonomy ? `fq_${taxonomy}` : "";
457
+ const picked = termKey ? values[termKey] ?? "" : "";
458
+ const submit = () => formRef.current?.requestSubmit();
459
+ return (_jsxs(NextForm, { ref: formRef, action: action, className: "ecx-query-filter", role: "search", children: [termStyle === "links" && terms.length > 0 && (_jsxs("nav", { className: "ecx-filter-terms", "aria-label": taxonomy, children: [_jsx(NextLink, { href: action, className: !currentTerm ? "is-active" : undefined, "aria-current": !currentTerm ? "true" : undefined, children: labels.all }), terms.map((t) => _jsx(NextLink, { href: t.link, className: t.slug === currentTerm ? "is-active" : undefined, "aria-current": t.slug === currentTerm ? "true" : undefined, children: t.name }, t.slug))] })), termStyle === "chips" && terms.length > 0 && (_jsxs("fieldset", { className: "ecx-filter-terms", children: [_jsx("legend", { className: "ecx-visually-hidden", children: taxonomy }), _jsxs("label", { className: !picked ? "is-active" : undefined, children: [_jsx("input", { type: "radio", name: termKey, value: "", defaultChecked: !picked, onChange: submit }), labels.all] }), terms.map((t) => _jsxs("label", { className: picked === t.slug ? "is-active" : undefined, children: [_jsx("input", { type: "radio", name: termKey, value: t.slug, defaultChecked: picked === t.slug, onChange: submit }), t.name] }, t.slug))] })), termStyle === "select" && terms.length > 0 && (_jsxs("select", { name: termKey, "aria-label": taxonomy, defaultValue: picked, onChange: submit, children: [_jsx("option", { value: "", children: labels.all }), terms.map((t) => _jsx("option", { value: t.slug, children: t.name }, t.slug))] })), showSearch && _jsx("input", { type: "search", name: "fq_s", defaultValue: values.fq_s ?? "", placeholder: labels.placeholder, "aria-label": labels.search }), showSort && sorts.length > 0 && _jsx("select", { name: "fq_sort", "aria-label": labels.sort, defaultValue: values.fq_sort ?? sorts[0].value, onChange: submit, children: sorts.map((s) => _jsx("option", { value: s.value, children: s.label }, s.value)) }), (showSearch || termStyle === "chips") && _jsx("button", { type: "submit", children: labels.submit })] }));
460
+ }
@@ -24,7 +24,13 @@ export declare function Slot<P = any>({ name, data, props, fallback, className,
24
24
  className?: string;
25
25
  }): Promise<import("react").JSX.Element>;
26
26
  /** Ô tìm kiếm — gửi về trang chủ của ngôn ngữ hiện tại (/?s= hoặc /en?s=). */
27
- export declare function SearchForm({ defaultValue, placeholder, buttonLabel, postType, showLabel, buttonPosition, buttonIcon }: {
27
+ export declare function SearchForm({ defaultValue, placeholder, buttonLabel, postType, showLabel, buttonPosition, buttonIcon, scopes, scopeType, collapse }: {
28
+ collapse?: "tablet" | "mobile";
29
+ scopes?: Array<{
30
+ value: string;
31
+ label: string;
32
+ }>;
33
+ scopeType?: string;
28
34
  buttonIcon?: boolean;
29
35
  defaultValue?: string | null;
30
36
  placeholder?: string;
@@ -104,9 +104,9 @@ export async function Slot({ name, data, props, fallback, className, }) {
104
104
  // Tiện ích hiển thị
105
105
  // ---------------------------------------------------------------------------
106
106
  /** Ô tìm kiếm — gửi về trang chủ của ngôn ngữ hiện tại (/?s= hoặc /en?s=). */
107
- export async function SearchForm({ defaultValue, placeholder, buttonLabel, postType, showLabel, buttonPosition, buttonIcon }) {
107
+ export async function SearchForm({ defaultValue, placeholder, buttonLabel, postType, showLabel, buttonPosition, buttonIcon, scopes, scopeType, collapse }) {
108
108
  const [t, site] = await Promise.all([getT(), getSite()]);
109
- 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, buttonIcon: buttonIcon, buttonPosition: buttonPosition });
109
+ 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, buttonIcon: buttonIcon, buttonPosition: buttonPosition, scopes: scopes, scopeAllLabel: t("search.all"), scopeLabel: t("search.scope"), scopeValue: scopeType, collapse: collapse });
110
110
  }
111
111
  function paramLink(data, param, p) {
112
112
  const q = new URLSearchParams(Object.entries(data.query ?? {}).filter(([k]) => k !== param));
package/dist/dynamic.js CHANGED
@@ -1,13 +1,15 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
2
  import { Fragment } from "react";
3
3
  import { getAdjacentPost, getArchives, getPosts, getTerms } from "./api.js";
4
- import { Link, LoginOutLink, NavToggle } from "./client.js";
4
+ import { Link, LoginOutLink, NavDrawer, QueryFilterBar, ScrollRow } from "./client.js";
5
+ import { buildPostQuery, SORTS } from "./query-filters.js";
5
6
  import { Comments, FeaturedImage, LanguageSwitcher, Menu, Pagination, PostDate, SearchForm, TermLinks } from "./components.js";
6
7
  import { getT } from "./i18n.js";
7
8
  import { applyFilters } from "./runtime.js";
8
9
  import { localeHref } from "./locale.js";
9
10
  import { renderContent } from "./rich.js";
10
11
  import { cx } from "./utils.js";
12
+ import { spacingValue } from "@ecomcx/ecomweb-content";
11
13
  const align = (a) => (a.textAlign && a.textAlign !== "left" ? { textAlign: a.textAlign } : undefined);
12
14
  const ASPECT = { "16/9": "16 / 9", "4/3": "4 / 3", "1/1": "1 / 1", "3/4": "3 / 4" };
13
15
  /**
@@ -37,12 +39,12 @@ export async function renderDynamic(node, key, ctx, children) {
37
39
  const location = String(a.location ?? "primary");
38
40
  const menu = _jsx(Menu, { location: location, className: "ecx-navigation-menu" });
39
41
  const t = await getT();
40
- // next: overlayMenu never|mobile|always; thiếu thì theo `mobile` cũ
41
- const overlay = ["never", "mobile", "always"].includes(a.overlayMenu) ? a.overlayMenu : a.mobile === false ? "never" : "mobile";
42
- 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" && _jsx(NavToggle, { label: t("navigation.menu"), children: menu })] }, key));
42
+ // overlayMenu never | mobile (≤640px) | tablet (≤1024px) | always; thiếu thì theo `mobile` cũ
43
+ const overlay = ["never", "mobile", "tablet", "always"].includes(a.overlayMenu) ? a.overlayMenu : a.mobile === false ? "never" : "mobile";
44
+ return (_jsxs("div", { className: cx("ecx-navigation", `ecx-navigation-${a.orientation ?? "horizontal"}`, overlay !== "never" && "has-mobile", overlay === "tablet" && "bp-tablet", overlay === "always" && "overlay-always"), children: [overlay !== "always" && _jsx("div", { className: "ecx-navigation-items", children: menu }), overlay !== "never" && _jsx(NavDrawer, { label: t("navigation.menu"), closeLabel: t("navigation.close"), children: menu })] }, key));
43
45
  }
44
46
  case "search":
45
- 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", buttonIcon: a.buttonStyle === "icon" }) }, key);
47
+ 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", buttonIcon: a.buttonStyle === "icon", scopes: a.scopeSelect === true ? parseScopes(a.scopes) : undefined, scopeType: ctx.data?.query?.type, collapse: a.collapse === "tablet" || a.collapse === "mobile" ? a.collapse : undefined }) }, key);
46
48
  case "languageSwitcher":
47
49
  return _jsx(LanguageSwitcher, { className: "ecx-language-switcher", variant: a.display === "dropdown" ? "select" : "list" }, key);
48
50
  case "copyright":
@@ -67,7 +69,7 @@ export async function renderDynamic(node, key, ctx, children) {
67
69
  if (!post?.featuredMedia)
68
70
  return null;
69
71
  const ratio = ASPECT[a.aspect];
70
- 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, label: post.title }) }, key);
72
+ return _jsx("div", { className: "ecx-featured-image", style: ratio ? { "--ecx-ar": ratio, overflow: "hidden" } : undefined, children: _jsx(FeaturedImage, { media: post.featuredMedia, size: a.size ?? "large", link: a.link ? post.link : undefined, label: post.title }) }, key);
71
73
  }
72
74
  case "postDate":
73
75
  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;
@@ -197,37 +199,51 @@ export async function renderDynamic(node, key, ctx, children) {
197
199
  let posts;
198
200
  let data;
199
201
  let pageParam;
200
- if (a.inherit !== false && ctx.data?.posts) {
202
+ const hasUrlFilter = a.urlFilters === true && Object.keys(ctx.data?.query ?? {}).some((k) => k.startsWith("fq_"));
203
+ if (a.inherit !== false && ctx.data?.posts && !hasUrlFilter) {
201
204
  posts = ctx.data.posts;
202
205
  data = ctx.data;
203
206
  }
204
207
  else {
205
- const taxonomy = a.category ? "category" : a.tag ? "post_tag" : undefined;
206
- const exclude = String(a.exclude ?? "").split(",").map((x) => Number(x.trim())).filter((x) => Number.isInteger(x) && x > 0);
207
- // 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)
208
- const paginate = a.paginate === true && !!ctx.data;
209
- const page = paginate ? Math.max(1, Math.floor(Number(ctx.data?.query?.qpage)) || 1) : 1;
210
- const res = await getPosts({ page, type: a.postType ?? "post", perPage: a.perPage ?? 10, taxonomy, term: a.category || a.tag || undefined,
211
- orderBy: a.orderBy ?? "date", order: a.order ?? "desc",
212
- authorId: typeof a.authorId === "number" ? a.authorId : undefined, search: a.search || undefined, exclude: exclude.length ? exclude : undefined,
213
- sticky: a.sticky === "only" ? true : a.sticky === "exclude" ? false : undefined, orderByMeta: a.orderByMeta || undefined }).catch(() => null);
208
+ const fromContext = a.inherit !== false && !!ctx.data;
209
+ // 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); trang lưu trữ lọc theo URL giữ /page/N
210
+ const paginate = a.paginate === true && !!ctx.data && !fromContext;
211
+ const page = fromContext ? Math.max(1, ctx.data?.page ?? 1) : paginate ? Math.max(1, Math.floor(Number(ctx.data?.query?.qpage)) || 1) : 1;
212
+ const res = await getPosts({ ...buildPostQuery(a, { post: ctx.post ?? ctx.data?.post, data: ctx.data, fromContext }), page }).catch(() => null);
214
213
  posts = res?.items ?? [];
215
- if (paginate && res && ctx.data) {
214
+ if ((paginate || fromContext) && res && ctx.data) {
216
215
  data = { ...ctx.data, page: res.page, totalPages: res.totalPages, total: res.total };
217
- pageParam = "qpage";
216
+ pageParam = fromContext ? undefined : "qpage";
218
217
  }
219
218
  }
220
219
  return _jsx("div", { className: "ecx-query", children: await children({ ...ctx, query: { posts, data, pageParam } }) }, key);
221
220
  }
221
+ case "queryFilter": {
222
+ const taxonomy = /^[a-z0-9_-]{1,64}$/i.test(String(a.taxonomy ?? "")) ? String(a.taxonomy) : undefined;
223
+ const style = ["none", "links", "chips", "select"].includes(a.termStyle) ? a.termStyle : "links";
224
+ const [t, terms] = await Promise.all([getT(), taxonomy && style !== "none" ? getTerms({ taxonomy, hideEmpty: true }).catch(() => []) : Promise.resolve([])]);
225
+ const sorts = String(a.sortOptions ?? "date_desc,date_asc,title_asc,title_desc").split(",").map((x) => x.trim()).filter((x) => SORTS[x]);
226
+ return _jsx(QueryFilterBar, { action: String(a.action || ctx.data?.basePath || "/"), taxonomy: taxonomy, termStyle: style, terms: terms.map((x) => ({ slug: x.slug, name: x.name, link: x.link })), currentTerm: ctx.data?.term?.slug, values: ctx.data?.query ?? {}, showSearch: a.showSearch === true, showSort: a.showSort === true, sorts: sorts.map((x) => ({ value: x, label: t(`filter.sort.${x}`) })), labels: { all: String(a.allLabel || t("filter.all")), search: t("search.label"), placeholder: String(a.placeholder || t("filter.search")), submit: String(a.submitText || t("filter.apply")), sort: t("filter.sort") } }, key);
227
+ }
222
228
  case "postTemplate": {
223
229
  const posts = ctx.query?.posts ?? [];
224
230
  if (!posts.length)
225
231
  return null;
226
232
  const grid = a.layout === "grid";
233
+ const carousel = a.layout === "carousel";
234
+ const per = Math.min(6, Math.max(1, Math.round(Number(a.columns)) || 3));
235
+ const gap = spacingValue(a.gap) ?? "1.5rem";
227
236
  // Đúng N cột khi đủ chỗ (như canvas), ít cột hơn khi hẹp (mỗi cột tối thiểu 12rem) — trước đây N chỉ là gợi ý nên 3 cột thành 2
228
- const style = grid ? { display: "grid", gap: "1.5rem", gridTemplateColumns: `repeat(auto-fill, minmax(max(12rem, calc((100% - ${(a.columns ?? 3) - 1} * 1.5rem) / ${a.columns ?? 3})), 1fr))`, listStyle: "none", padding: 0 } : { listStyle: "none", padding: 0 };
237
+ // Đặt số cột riêng cho tablet / điện thoại → lưới theo biến CSS (is-responsive); không thì như cũ: tự giảm cột khi hẹp (mỗi cột tối thiểu 12rem)
238
+ const tablet = Math.round(Number(a.columnsTablet)) || 0, mobile = Math.round(Number(a.columnsMobile)) || 0;
239
+ const responsive = grid && (tablet > 0 || mobile > 0);
240
+ const style = responsive ? { "--per": per, "--per-tablet": tablet || Math.min(per, 3), "--per-mobile": mobile || Math.min(per, 2), "--gap": gap }
241
+ : grid ? { display: "grid", gap, gridTemplateColumns: `repeat(auto-fill, minmax(max(12rem, calc((100% - ${per - 1} * ${gap}) / ${per})), 1fr))`, listStyle: "none", padding: 0 }
242
+ : carousel ? { "--per": per, "--per-tablet": Math.min(per, 3), "--per-mobile": Math.min(per, 2), "--gap": gap }
243
+ : { listStyle: "none", padding: 0 };
229
244
  const items = await Promise.all(posts.map(async (p) => _jsx("li", { className: "ecx-post", children: await children({ ...ctx, post: p }) }, p.id)));
230
- return _jsx("ul", { className: cx("ecx-post-template", grid && "is-grid"), style: style, children: items }, key);
245
+ const list = _jsx("ul", { className: cx("ecx-post-template", grid && "is-grid", responsive && "is-responsive", carousel && "is-carousel"), style: style, children: items }, key);
246
+ return carousel ? _jsx(ScrollRow, { arrows: a.arrows !== false, children: list }, key) : list;
231
247
  }
232
248
  case "pagination":
233
249
  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;
@@ -253,3 +269,12 @@ export async function renderDynamic(node, key, ctx, children) {
253
269
  }
254
270
  return null;
255
271
  }
272
+ /** "product:Sản phẩm, post:Tin tức" → tuỳ chọn của ô chọn phạm vi tìm kiếm (loại không hợp lệ bị bỏ; không ghi nhãn thì lấy chính tên loại). */
273
+ function parseScopes(v) {
274
+ if (typeof v !== "string")
275
+ return [];
276
+ return v.split(",").map((x) => x.trim()).filter(Boolean).slice(0, 10).flatMap((x) => {
277
+ const [value, ...rest] = x.split(":");
278
+ return /^[a-z0-9_-]{1,64}$/i.test(value.trim()) ? [{ value: value.trim(), label: rest.join(":").trim() || value.trim() }] : [];
279
+ });
280
+ }
package/dist/i18n.js CHANGED
@@ -5,7 +5,7 @@ import { formatMessage } from "./i18n-format.js";
5
5
  /** Chữ mặc định của các component trong SDK (theme có thể ghi đè trong locales/{code}.json). */
6
6
  export const BUILTIN = {
7
7
  vi: {
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",
8
+ "search.placeholder": "Tìm kiếm…", "search.button": "Tìm", "search.label": "Từ khoá", "filter.all": "Tất cả", "filter.search": "Tìm trong danh sách…", "filter.apply": "Lọc", "filter.sort": "Sắp xếp", "filter.sort.date_desc": "Mới nhất", "filter.sort.date_asc": "Cũ nhất", "filter.sort.title_asc": "Tên A → Z", "filter.sort.title_desc": "Tên Z → A", "filter.sort.modified_desc": "Mới cập nhật", "filter.sort.rand": "Ngẫu nhiên", "search.scope": "Phạm vi tìm kiếm", "search.all": "Tất cả", "navigation.menu": "Menu", "navigation.close": "Đóng 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
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.", "countdown.d": "ngày", "countdown.h": "giờ", "countdown.m": "phút", "countdown.s": "giây",
11
11
  "comments.form.title": "Để lại bình luận", "comments.form.content": "Bình luận", "comments.form.name": "Tên",
@@ -31,7 +31,7 @@ export const BUILTIN = {
31
31
  "styleBook.title": "Mẫu kiểu dáng", "styleBook.h": "Tiêu đề", "styleBook.para": "Đoạn văn mẫu: chữ của bài viết trên website hiển thị như thế này.", "styleBook.bold": "chữ đậm", "styleBook.italic": "chữ nghiêng", "styleBook.link": "liên kết", "styleBook.item": "Mục", "styleBook.quote": "Trích dẫn mẫu: một câu đáng nhớ.", "styleBook.cite": "Tác giả", "styleBook.button": "Nút bấm", "styleBook.callout": "Hộp lưu ý: thông tin cần chú ý.", "styleBook.group": "Nhóm có nền", "styleBook.column": "Cột", "styleBook.details": "Bấm để xem thêm", "styleBook.cover": "Ảnh bìa",
32
32
  },
33
33
  en: {
34
- "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
+ "search.placeholder": "Search…", "search.button": "Search", "search.label": "Keyword", "filter.all": "All", "filter.search": "Search this list…", "filter.apply": "Filter", "filter.sort": "Sort by", "filter.sort.date_desc": "Newest", "filter.sort.date_asc": "Oldest", "filter.sort.title_asc": "Name A → Z", "filter.sort.title_desc": "Name Z → A", "filter.sort.modified_desc": "Recently updated", "filter.sort.rand": "Random", "search.scope": "Search in", "search.all": "All", "navigation.menu": "Menu", "navigation.close": "Close 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",
35
35
  "post.read_more": "Read more", "pagination.prev": "« Previous", "pagination.next": "Next »", "pagination.label": "Pagination",
36
36
  "comments.title": "Comments", "comments.closed": "Comments are closed.", "countdown.d": "d", "countdown.h": "h", "countdown.m": "m", "countdown.s": "s",
37
37
  "comments.form.title": "Leave a comment", "comments.form.content": "Comment", "comments.form.name": "Name",
@@ -0,0 +1,16 @@
1
+ import type { PostQuery } from "./api.js";
2
+ import type { Post, ResolveResult } from "./types.js";
3
+ /** Cách xếp của thanh lọc (?fq_sort=…) → tham số getPosts. */
4
+ export declare const SORTS: Record<string, Pick<PostQuery, "orderBy" | "order">>;
5
+ type Attrs = Record<string, any>;
6
+ /**
7
+ * Thuộc tính khối Query (bộ lọc 1.27) → tham số getPosts. Hàm thuần để thử được; `now` để cố định ngày trong test.
8
+ * `fromContext`: Query "theo trang đang xem" nhưng có nhận bộ lọc URL → lấy loại bài / mục phân loại của trang lưu trữ rồi lọc thêm.
9
+ */
10
+ export declare function buildPostQuery(a: Attrs, env: {
11
+ post?: Post | null;
12
+ data?: ResolveResult | null;
13
+ now?: Date;
14
+ fromContext?: boolean;
15
+ }): PostQuery;
16
+ export {};
@@ -0,0 +1,110 @@
1
+ /** Cách xếp của thanh lọc (?fq_sort=…) → tham số getPosts. */
2
+ export const SORTS = {
3
+ date_desc: { orderBy: "date", order: "desc" }, date_asc: { orderBy: "date", order: "asc" },
4
+ title_asc: { orderBy: "title", order: "asc" }, title_desc: { orderBy: "title", order: "desc" },
5
+ modified_desc: { orderBy: "modified", order: "desc" }, rand: { orderBy: "rand" },
6
+ };
7
+ const SLUG = /^[a-z0-9_-]{1,64}$/i;
8
+ const ids = (v) => String(v ?? "").split(",").map((x) => Number(x.trim())).filter((x) => Number.isInteger(x) && x > 0).slice(0, 100);
9
+ const slugs = (v) => String(v ?? "").split(",").map((x) => x.trim()).filter((x) => SLUG.test(x)).slice(0, 50);
10
+ const scalar = (v) => (v.trim() !== "" && Number.isFinite(Number(v)) ? Number(v) : v === "true" ? true : v === "false" ? false : v);
11
+ /**
12
+ * Thuộc tính khối Query (bộ lọc 1.27) → tham số getPosts. Hàm thuần để thử được; `now` để cố định ngày trong test.
13
+ * `fromContext`: Query "theo trang đang xem" nhưng có nhận bộ lọc URL → lấy loại bài / mục phân loại của trang lưu trữ rồi lọc thêm.
14
+ */
15
+ export function buildPostQuery(a, env) {
16
+ const data = env.data ?? null, cur = env.post ?? data?.post ?? null;
17
+ const url = a.urlFilters === true ? (data?.query ?? {}) : {};
18
+ const q = { type: env.fromContext ? data?.postType ?? a.postType ?? "post" : a.postType ?? "post", perPage: a.perPage ?? 10, orderBy: a.orderBy ?? "date", order: a.order ?? "desc" };
19
+ const tax = [];
20
+ // Phân loại: ngữ cảnh (trang mục) + ô Phân loại / Mục + category / tag cũ
21
+ if (env.fromContext && data?.term && SLUG.test(data.term.taxonomy))
22
+ tax.push({ taxonomy: data.term.taxonomy, terms: [data.term.slug] });
23
+ const taxonomy = SLUG.test(String(a.taxonomy ?? "")) ? String(a.taxonomy) : undefined;
24
+ const picked = [...slugs(a.terms), ...(a.term && SLUG.test(String(a.term)) ? [String(a.term)] : [])];
25
+ if (taxonomy && picked.length) {
26
+ if (a.termMode === "all")
27
+ for (const t of picked)
28
+ tax.push({ taxonomy, terms: [t] });
29
+ else
30
+ tax.push({ taxonomy, terms: picked, operator: a.termMode === "none" ? "NOT IN" : "IN" });
31
+ }
32
+ if (a.category)
33
+ tax.push({ taxonomy: "category", terms: [String(a.category)] });
34
+ if (a.tag)
35
+ tax.push({ taxonomy: "post_tag", terms: [String(a.tag)] });
36
+ // Nguồn
37
+ if (a.source === "manual") {
38
+ const inc = ids(a.include);
39
+ q.include = inc.length ? inc : [0];
40
+ if (!a.orderBy || a.orderBy === "date") {
41
+ q.orderBy = "include";
42
+ delete q.order;
43
+ }
44
+ }
45
+ if (a.source === "related" && cur) {
46
+ const tn = taxonomy ?? (cur.type === "post" ? "category" : Object.keys(cur.terms ?? {})[0]);
47
+ const mine = tn ? (cur.terms?.[tn] ?? []).map((t) => t.slug) : [];
48
+ if (tn && mine.length)
49
+ tax.push({ taxonomy: tn, terms: mine });
50
+ q.exclude = [...(q.exclude ?? []), cur.id];
51
+ }
52
+ else if (a.excludeCurrent !== false && cur && (q.type === cur.type || !q.type))
53
+ q.exclude = [...(q.exclude ?? []), cur.id];
54
+ const ex = ids(a.exclude);
55
+ if (ex.length)
56
+ q.exclude = [...(q.exclude ?? []), ...ex];
57
+ // Trường tuỳ biến (một điều kiện)
58
+ if (typeof a.metaKey === "string" && a.metaKey.trim()) {
59
+ const compare = (["=", "!=", ">", ">=", "<", "<=", "LIKE", "EXISTS", "NOT EXISTS"].includes(a.metaCompare) ? a.metaCompare : "=");
60
+ const clause = { key: a.metaKey.trim(), compare };
61
+ if (compare !== "EXISTS" && compare !== "NOT EXISTS")
62
+ clause.value = compare === "LIKE" ? String(a.metaValue ?? "") : scalar(String(a.metaValue ?? ""));
63
+ q.metaQuery = { clauses: [clause] };
64
+ }
65
+ // Ngày
66
+ const days = Number(a.dateRange);
67
+ if (days > 0)
68
+ q.after = new Date((env.now ?? new Date()).getTime() - days * 86_400_000);
69
+ if (a.after)
70
+ q.after = String(a.after);
71
+ if (a.before)
72
+ q.before = String(a.before);
73
+ if (typeof a.parent === "number")
74
+ q.parentId = a.parent;
75
+ if (typeof a.offset === "number" && a.offset > 0)
76
+ q.offset = a.offset;
77
+ if (typeof a.authorId === "number")
78
+ q.authorId = a.authorId;
79
+ if (a.authorCurrent === true && cur?.author?.id)
80
+ q.authorId = cur.author.id;
81
+ if (a.search)
82
+ q.search = String(a.search);
83
+ if (a.sticky === "only")
84
+ q.sticky = true;
85
+ else if (a.sticky === "exclude")
86
+ q.sticky = false;
87
+ if (a.orderByMeta)
88
+ q.orderByMeta = String(a.orderByMeta);
89
+ // Bộ lọc người đọc chọn trên URL (?fq_s, ?fq_sort, ?fq_<phân loại>)
90
+ if (a.urlFilters === true) {
91
+ if (url.fq_s?.trim())
92
+ q.search = url.fq_s.trim().slice(0, 100);
93
+ if (SORTS[url.fq_sort]) {
94
+ delete q.order;
95
+ Object.assign(q, SORTS[url.fq_sort]);
96
+ }
97
+ const tn = taxonomy;
98
+ if (tn && SLUG.test(url[`fq_${tn}`] ?? ""))
99
+ tax.push({ taxonomy: tn, terms: [url[`fq_${tn}`]] });
100
+ }
101
+ if (tax.length)
102
+ q.taxQuery = tax;
103
+ // Mọi ?fq_… còn lại chuyển cho plugin đọc (vd giá, giảm giá, còn hàng của plugin bán hàng)
104
+ if (a.urlFilters === true) {
105
+ const extra = Object.fromEntries(Object.entries(url).filter(([k, v]) => /^fq_[a-z0-9_-]{1,40}$/i.test(k) && typeof v === "string" && v.length <= 100 && k !== "fq_s"));
106
+ if (Object.keys(extra).length)
107
+ q.extra = extra;
108
+ }
109
+ return q;
110
+ }
package/dist/rich.js CHANGED
@@ -224,8 +224,11 @@ async function applyBindings(node, ctx) {
224
224
  console.warn(`[cms] binding ${b.source} lỗi:`, e.message);
225
225
  continue;
226
226
  }
227
- if (v === null || v === undefined || v === "")
227
+ if (v === null || v === undefined || v === "") {
228
+ if (b.args?.hideIfEmpty === true)
229
+ return null; // "Ẩn khi rỗng": khối không có giá trị thì không vẽ (vd % giảm khi không giảm giá)
228
230
  continue;
231
+ }
229
232
  const text = String(v);
230
233
  if (attr === "content")
231
234
  out = { ...out, content: [{ type: "text", text }] };
@@ -240,8 +243,12 @@ async function applyBindings(node, ctx) {
240
243
  return out;
241
244
  }
242
245
  async function renderNode(node, key, ctx) {
243
- if (node.attrs?.bindings)
244
- node = await applyBindings(node, ctx);
246
+ if (node.attrs?.bindings) {
247
+ const bound = await applyBindings(node, ctx);
248
+ if (!bound)
249
+ return null;
250
+ node = bound;
251
+ }
245
252
  let el = await renderNodeInner(node, key, ctx);
246
253
  if (ctx.filterBlock && node.type !== "text" && node.type !== "doc")
247
254
  el = await ctx.filterBlock(node, el);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ecomcx/ecomweb-theme-sdk",
3
- "version": "2.0.0",
3
+ "version": "2.1.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",
@@ -36,7 +36,7 @@
36
36
  "API.md"
37
37
  ],
38
38
  "dependencies": {
39
- "@ecomcx/ecomweb-content": "^1.26.0",
39
+ "@ecomcx/ecomweb-content": "^1.27.0",
40
40
  "intl-messageformat": "12.1.3",
41
41
  "server-only": "0.0.1"
42
42
  },