@ecomcx/ecomweb-theme-sdk 2.0.0 → 2.2.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/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 { applyPatternOverrides, 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", "checks"].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, range: a.showRange === true && /^[a-z][a-z0-9_]{0,30}$/.test(String(a.rangeParam ?? "")) ? { param: String(a.rangeParam), label: a.rangeLabel ? String(a.rangeLabel) : undefined, max: Number(a.rangeMax) > 0 ? Number(a.rangeMax) : undefined } : undefined, showYear: a.showYear === true, showReset: a.showReset === true, years: a.showYear === true ? Array.from({ length: 8 }, (_, i) => new Date().getUTCFullYear() - i) : [], 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"), year: t("filter.year"), reset: t("filter.reset"), from: t("filter.from"), to: t("filter.to") } }, 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;
@@ -236,9 +252,10 @@ export async function renderDynamic(node, key, ctx, children) {
236
252
  case "syncedPattern": {
237
253
  if (typeof a.ref !== "number" || !ctx.pattern || (ctx.partDepth ?? 0) >= 4)
238
254
  return null;
239
- const doc = await ctx.pattern(a.ref);
240
- if (!doc)
255
+ const base = await ctx.pattern(a.ref);
256
+ if (!base)
241
257
  return null;
258
+ const doc = applyPatternOverrides(base, a.overrides); // 1.32: chỗ dùng mẫu sửa riêng vài ô (khối có overrideKey trong mẫu)
242
259
  return _jsx(Fragment, { children: await renderContent(doc, { ...ctx, partDepth: (ctx.partDepth ?? 0) + 1, source: `pattern:${a.ref}` }) }, key);
243
260
  }
244
261
  case "templatePart": {
@@ -253,3 +270,12 @@ export async function renderDynamic(node, key, ctx, children) {
253
270
  }
254
271
  return null;
255
272
  }
273
+ /** "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). */
274
+ function parseScopes(v) {
275
+ if (typeof v !== "string")
276
+ return [];
277
+ return v.split(",").map((x) => x.trim()).filter(Boolean).slice(0, 10).flatMap((x) => {
278
+ const [value, ...rest] = x.split(":");
279
+ return /^[a-z0-9_-]{1,64}$/i.test(value.trim()) ? [{ value: value.trim(), label: rest.join(":").trim() || value.trim() }] : [];
280
+ });
281
+ }
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", "form.next": "Tiếp theo", "form.back": "Quay lại", "form.step": "Bước {n}/{total}", "filter.year": "Năm", "filter.from": "Từ", "filter.to": "Đến", "filter.reset": "Xoá bộ 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", "form.next": "Next", "form.back": "Back", "form.step": "Step {n}/{total}", "filter.year": "Year", "filter.from": "From", "filter.to": "To", "filter.reset": "Clear filters", "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,12 @@
1
+ import { type ReactNode } from "react";
2
+ /**
3
+ * Vẽ icon theo giá trị lưu (tên trong bảng / thư viện, hoặc SVG riêng `svg:…` đã lọc lại ở đây). Không có icon → null.
4
+ * Dùng cho khối Icon, icon của tab… (server và client).
5
+ */
6
+ export declare function iconSvg(value: unknown, o?: {
7
+ size?: number;
8
+ stroke?: number;
9
+ className?: string;
10
+ label?: string;
11
+ key?: string;
12
+ }): ReactNode;
@@ -0,0 +1,21 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { createElement } from "react";
3
+ import { resolveIcon } from "@ecomcx/ecomweb-content";
4
+ const camel = (props) => Object.fromEntries(Object.entries(props).map(([k, v]) => [k.replace(/-([a-z])/g, (_, c) => c.toUpperCase()), v]));
5
+ const node = (n, key) => createElement(n.tag, { key, ...camel(n.props) }, ...n.children.map(node));
6
+ /**
7
+ * Vẽ icon theo giá trị lưu (tên trong bảng / thư viện, hoặc SVG riêng `svg:…` đã lọc lại ở đây). Không có icon → null.
8
+ * Dùng cho khối Icon, icon của tab… (server và client).
9
+ */
10
+ export function iconSvg(value, o = {}) {
11
+ const r = resolveIcon(value);
12
+ if (!r)
13
+ return null;
14
+ const size = o.size ?? 24;
15
+ const a11y = o.label ? { role: "img", "aria-label": o.label } : { "aria-hidden": true, focusable: "false" };
16
+ if (r.kind === "svg") {
17
+ const root = camel(r.icon.root);
18
+ return _jsx("svg", { className: o.className, width: size, height: size, viewBox: r.icon.viewBox, fill: root.fill ?? "currentColor", ...(root.stroke ? { stroke: root.stroke } : {}), ...(root.strokeWidth ? { strokeWidth: root.strokeWidth } : {}), ...(root.strokeLinecap ? { strokeLinecap: root.strokeLinecap } : {}), ...(root.strokeLinejoin ? { strokeLinejoin: root.strokeLinejoin } : {}), ...a11y, children: r.icon.children.map(node) }, o.key);
19
+ }
20
+ return _jsx("svg", { className: o.className, width: size, height: size, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: o.stroke ?? 2, strokeLinecap: "round", strokeLinejoin: "round", ...a11y, children: _jsx("path", { d: r.d }) }, o.key);
21
+ }
@@ -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,118 @@
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 yr = Math.floor(Number(url.fq_year)), mo = Math.floor(Number(url.fq_month));
98
+ if (yr >= 1990 && yr <= 2100) {
99
+ q.year = yr;
100
+ if (mo >= 1 && mo <= 12)
101
+ q.month = mo;
102
+ }
103
+ const tn = taxonomy;
104
+ // ?fq_<phân loại>=a hoặc a,b,c (checkbox nhiều lựa chọn = bất kỳ mục nào)
105
+ const picked = tn ? slugs(url[`fq_${tn}`]).slice(0, 10) : [];
106
+ if (tn && picked.length)
107
+ tax.push({ taxonomy: tn, terms: picked });
108
+ }
109
+ if (tax.length)
110
+ q.taxQuery = tax;
111
+ // 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)
112
+ if (a.urlFilters === true) {
113
+ 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" && k !== "fq_year" && k !== "fq_month"));
114
+ if (Object.keys(extra).length)
115
+ q.extra = extra;
116
+ }
117
+ return q;
118
+ }
package/dist/rich.d.ts CHANGED
@@ -60,6 +60,8 @@ export interface RenderContext {
60
60
  styles?: Map<string, string>;
61
61
  /** Đang vẽ bên trong nhóm nút (`buttons`): nút không bọc thêm đoạn văn. */
62
62
  inButtons?: boolean;
63
+ /** Đang vẽ bên trong một liên kết (tiêu đề có link cả khối): link trong chữ chỉ giữ chữ — không lồng <a> trong <a>. */
64
+ inLink?: boolean;
63
65
  /** Lấy giá trị của nguồn gắn dữ liệu (attrs.bindings). Không có → bỏ qua bindings (giữ nội dung gõ tay). */
64
66
  binding?(source: string, args: Record<string, string | number | boolean>, ctx: RenderContext): Promise<unknown>;
65
67
  /** Tiêu đề của bài (khối mục lục) — renderContent ngoài cùng tính. */