@enyxs/wikex-components 0.11.45 → 0.11.47

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,300 @@
1
+ // src/shared/responsive-layout.ts
2
+ var CmsLayoutValidationError = class extends Error {
3
+ };
4
+ var CMS_DEVICES = ["desktop", "tablet", "mobile"];
5
+ var CMS_DEVICE_WIDTHS = { desktop: 1440, tablet: 768, mobile: 390 };
6
+ var CMS_DEVICE_MEDIA = { desktop: "(min-width:1024px)", tablet: "(min-width:768px) and (max-width:1023.98px)", mobile: "(max-width:767.98px)" };
7
+ var CMS_LAYOUT_KEYS = { desktop: "__cmsLayoutDesktop", tablet: "__cmsLayoutTablet", mobile: "__cmsLayoutMobile" };
8
+ var CMS_ITEM_ID = "__cmsItemId";
9
+ var own = (record, key) => Object.prototype.hasOwnProperty.call(record, key);
10
+ var unsafe = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
11
+ var fonts = ["Inter, sans-serif", "Arial, sans-serif", "Georgia, serif", '"Times New Roman", serif', '"Courier New", monospace', '"Public Sans Variable", Arial, sans-serif'];
12
+ function cmsDevice(width) {
13
+ return width < 768 ? "mobile" : width < 1024 ? "tablet" : "desktop";
14
+ }
15
+ function object(value) {
16
+ try {
17
+ const parsed = typeof value === "string" ? JSON.parse(value) : value;
18
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
19
+ } catch {
20
+ return {};
21
+ }
22
+ }
23
+ function array(value) {
24
+ if (typeof value !== "string" || !value.trimStart().startsWith("[")) return null;
25
+ try {
26
+ const parsed = JSON.parse(value);
27
+ return Array.isArray(parsed) && parsed.every((item) => item && typeof item === "object" && !Array.isArray(item)) ? parsed : null;
28
+ } catch {
29
+ return null;
30
+ }
31
+ }
32
+ function isCmsLayoutField(key) {
33
+ return !unsafe.has(key) && (/(?:TextLayout|ImageLayout|Color|BoxLayout)$/.test(key) || key === "sectionBackgroundColor" || key === "backgroundColor" || key === "__cmsBoxLayout");
34
+ }
35
+ var color = (value) => typeof value === "string" && /^#[0-9a-fA-F]{6}$/.test(value);
36
+ function number(value, min, max) {
37
+ return typeof value === "number" && Number.isFinite(value) && value >= min && value <= max;
38
+ }
39
+ function cmsVisualValue(key, value) {
40
+ if (key.endsWith("Color") || key === "backgroundColor") return color(value) ? String(value) : "";
41
+ const raw = object(value), result = {};
42
+ if (key.endsWith("TextLayout")) {
43
+ for (const prop of ["width", "height"]) if (number(raw[prop], 16, 1e4)) result[prop] = raw[prop];
44
+ if (number(raw.fontSize, 8, 300)) result.fontSize = raw.fontSize;
45
+ if (number(raw.lineHeight, 0.5, 5)) result.lineHeight = raw.lineHeight;
46
+ if (fonts.includes(String(raw.fontFamily))) result.fontFamily = raw.fontFamily;
47
+ if (["left", "center", "right"].includes(String(raw.textAlign))) result.textAlign = raw.textAlign;
48
+ } else if (key.endsWith("ImageLayout")) {
49
+ for (const prop of ["width", "height"]) if (number(raw[prop], 16, 8e3)) result[prop] = Math.round(Number(raw[prop]));
50
+ if (raw.auto === true) result.auto = true;
51
+ if (typeof raw.lockRatio === "boolean") result.lockRatio = raw.lockRatio;
52
+ if (["contain", "cover"].includes(String(raw.fit))) result.fit = raw.fit;
53
+ } else {
54
+ for (const prop of ["padding", "margin", "gap"]) if (number(raw[prop], 0, 300)) result[prop] = raw[prop];
55
+ if (number(raw.widthPercent, 1, 100)) result.widthPercent = raw.widthPercent;
56
+ if (number(raw.columns, 1, 12) && Number.isInteger(raw.columns)) result.columns = raw.columns;
57
+ if (number(raw.order, -1e3, 1e3) && Number.isInteger(raw.order)) result.order = raw.order;
58
+ if (typeof raw.hidden === "boolean") result.hidden = raw.hidden;
59
+ if (["left", "center", "right"].includes(String(raw.align))) result.align = raw.align;
60
+ }
61
+ return Object.keys(result).length ? JSON.stringify(result) : "";
62
+ }
63
+ var profileCache = /* @__PURE__ */ new WeakMap();
64
+ function readProfile(record, device) {
65
+ let cached = profileCache.get(record);
66
+ if (!cached) {
67
+ cached = /* @__PURE__ */ new Map();
68
+ profileCache.set(record, cached);
69
+ }
70
+ const source = record[CMS_LAYOUT_KEYS[device]];
71
+ const previous = cached.get(device);
72
+ if (previous && previous.source === source) return previous.value;
73
+ const value = Object.fromEntries(Object.entries(object(source)).filter(([key, value2]) => key.length <= 500 && isCmsLayoutField(key) && typeof value2 === "string").map(([key, value2]) => [key, cmsVisualValue(key, value2)]));
74
+ cached.set(device, { source, value });
75
+ return value;
76
+ }
77
+ function cmsLayoutProfile(record, device) {
78
+ return { ...readProfile(record, device) };
79
+ }
80
+ function cmsLayoutManaged(record, key) {
81
+ return CMS_DEVICES.some((device) => own(readProfile(record, device), key));
82
+ }
83
+ function cmsLayoutValue(record, key, device) {
84
+ const profile = readProfile(record, device);
85
+ return own(profile, key) ? profile[key] : cmsVisualValue(key, record[key]);
86
+ }
87
+ function semantic(value) {
88
+ const raw = object(value);
89
+ return Object.fromEntries(Object.entries(raw).filter(([key]) => ["richText", "blockType", "listType"].includes(key)));
90
+ }
91
+ function writeValue(record, key, value, device) {
92
+ const next = { ...record, __cmsLayoutVersion: 1 };
93
+ for (const mode of CMS_DEVICES) {
94
+ const profile = cmsLayoutProfile(record, mode);
95
+ if (!own(profile, key)) profile[key] = cmsVisualValue(key, record[key]);
96
+ if (mode === device) profile[key] = cmsVisualValue(key, value);
97
+ next[CMS_LAYOUT_KEYS[mode]] = JSON.stringify(profile);
98
+ }
99
+ if (key.endsWith("TextLayout")) next[key] = JSON.stringify({ ...semantic(record[key]), ...semantic(value) });
100
+ else delete next[key];
101
+ return next;
102
+ }
103
+ function stableId(path, index) {
104
+ return `legacy-${cmsLayoutHash(path)}-${index}`;
105
+ }
106
+ function projectRecord(record, device, path, depth, fields) {
107
+ if (depth > 10) return record;
108
+ const next = { ...record };
109
+ const keys = /* @__PURE__ */ new Set([...Object.keys(record), ...CMS_DEVICES.flatMap((mode) => Object.keys(cmsLayoutProfile(record, mode)))]);
110
+ for (const key of keys) {
111
+ if (isCmsLayoutField(key) && cmsLayoutManaged(record, key)) {
112
+ if (device) {
113
+ const active = cmsLayoutValue(record, key, device);
114
+ next[key] = key.endsWith("TextLayout") ? JSON.stringify({ ...semantic(record[key]), ...object(active) }) : active;
115
+ } else if (key.endsWith("BoxLayout") && key !== "__cmsBoxLayout" || key.endsWith("TextLayout") || key.endsWith("Color") && key !== "sectionBackgroundColor" && key !== "backgroundColor") {
116
+ const field = key.replace(/(?:TextLayout|Color|BoxLayout)$/, "");
117
+ const textKey = `${field}TextLayout`, colorKey = `${field}Color`, boxKey = `${field}BoxLayout`;
118
+ const profiles = Object.fromEntries(CMS_DEVICES.map((mode) => [mode, {
119
+ ...cmsLayoutManaged(record, textKey) ? object(cmsLayoutValue(record, textKey, mode)) : object(cmsVisualValue(textKey, record[textKey])),
120
+ ...cmsLayoutManaged(record, boxKey) ? { box: object(cmsLayoutValue(record, boxKey, mode)) } : {},
121
+ ...cmsLayoutManaged(record, colorKey) && cmsLayoutValue(record, colorKey, mode) ? { color: cmsLayoutValue(record, colorKey, mode) } : {}
122
+ }]));
123
+ next[textKey] = JSON.stringify({ ...semantic(record[textKey]), __responsive: profiles });
124
+ if (cmsLayoutManaged(record, colorKey)) delete next[colorKey];
125
+ } else delete next[key];
126
+ }
127
+ const list = fields && fields.find((field) => field.key === key)?.type !== "list" ? null : array(record[key]);
128
+ if (list) next[key] = JSON.stringify(list.map((item, index) => projectRecord({ ...item, [CMS_ITEM_ID]: item[CMS_ITEM_ID] ?? stableId(`${path}/${key}`, index) }, device, `${path}/${key}/${item[CMS_ITEM_ID] ?? stableId(`${path}/${key}`, index)}`, depth + 1, fields?.find((field) => field.key === key)?.itemFields)));
129
+ }
130
+ return next;
131
+ }
132
+ function projectCmsLayoutContent(content, device, fields) {
133
+ return projectRecord(content, device, "", 0, fields);
134
+ }
135
+ function captureRecord(raw, incoming, device, path, depth, complete = false, fields) {
136
+ if (depth > 10) return incoming;
137
+ let next = { ...raw };
138
+ const projected = projectRecord(raw, device, path, depth, fields);
139
+ const edits = { ...incoming };
140
+ if (complete) for (const key of Object.keys(projected)) {
141
+ if (isCmsLayoutField(key) && !(key in incoming)) edits[key] = "";
142
+ }
143
+ for (const [key, value] of Object.entries(edits)) {
144
+ if (unsafe.has(key) || Object.values(CMS_LAYOUT_KEYS).includes(key) || key === "__cmsLayoutVersion") continue;
145
+ if (isCmsLayoutField(key)) {
146
+ if (value !== projected[key]) next = writeValue(next, key, value, device);
147
+ continue;
148
+ }
149
+ const list = fields && fields.find((field) => field.key === key)?.type !== "list" ? null : array(value);
150
+ if (list) {
151
+ const previous = array(raw[key]) ?? [];
152
+ const byId = new Map(previous.map((item, index) => [item[CMS_ITEM_ID] ?? stableId(`${path}/${key}`, index), item]));
153
+ const seen = /* @__PURE__ */ new Set();
154
+ next[key] = JSON.stringify(list.map((item, index) => {
155
+ let id = item[CMS_ITEM_ID] ?? `item-${globalThis.crypto.randomUUID()}`;
156
+ if (seen.has(id)) id = `item-${globalThis.crypto.randomUUID()}`;
157
+ seen.add(id);
158
+ const before = byId.get(item[CMS_ITEM_ID]) ?? (item[CMS_ITEM_ID] ? void 0 : previous[index]);
159
+ const base = before ?? Object.fromEntries(Object.entries(item).filter(([name]) => !isCmsLayoutField(name)));
160
+ return { ...captureRecord(base, item, device, `${path}/${key}/${id}`, depth + 1, true, fields?.find((field) => field.key === key)?.itemFields), [CMS_ITEM_ID]: id };
161
+ }));
162
+ } else next[key] = value;
163
+ }
164
+ return next;
165
+ }
166
+ function applyCmsLayoutEdit(content, field, value, device, fields) {
167
+ return captureRecord(content, { [field]: value }, device, "", 0, false, fields);
168
+ }
169
+ function cmsLayoutHash(value) {
170
+ let a = 2166136261, b = 5381;
171
+ for (let i = 0; i < value.length; i++) {
172
+ a = Math.imul(a ^ value.charCodeAt(i), 16777619);
173
+ b = Math.imul(b, 33) ^ value.charCodeAt(i);
174
+ }
175
+ return `${(a >>> 0).toString(36)}${(b >>> 0).toString(36)}`;
176
+ }
177
+ function cmsTextLayoutId(value) {
178
+ const profiles = object(value).__responsive;
179
+ return profiles && typeof profiles === "object" ? `r${cmsLayoutHash(JSON.stringify(profiles))}` : void 0;
180
+ }
181
+ function cmsResponsiveTextCss(content) {
182
+ const styles = /* @__PURE__ */ new Map();
183
+ const walk = (record, depth) => {
184
+ if (depth > 10) return;
185
+ for (const [key, value] of Object.entries(record)) {
186
+ if (key.endsWith("TextLayout")) {
187
+ const id = cmsTextLayoutId(value);
188
+ if (!id || styles.has(id)) continue;
189
+ const profiles = object(object(value).__responsive);
190
+ styles.set(id, CMS_DEVICES.map((mode) => {
191
+ const raw = object(profiles[mode]), layout = object(cmsVisualValue("xTextLayout", JSON.stringify(raw)));
192
+ const declarations = [
193
+ ...layout.width ? [`width:${layout.width}px`, "max-width:100%", "box-sizing:border-box", "flex-shrink:1"] : [],
194
+ ...layout.height ? [`min-height:${layout.height}px`, "height:auto"] : [],
195
+ ...layout.fontSize ? [`font-size:${layout.fontSize}px`] : [],
196
+ ...layout.fontFamily ? [`font-family:${layout.fontFamily}`] : [],
197
+ ...layout.lineHeight ? [`line-height:${layout.lineHeight}`] : [],
198
+ ...layout.textAlign ? [`text-align:${layout.textAlign}`, `justify-content:${layout.textAlign === "center" ? "center" : layout.textAlign === "right" ? "flex-end" : "flex-start"}`] : [],
199
+ ...color(raw.color) ? [`color:${raw.color}`] : [],
200
+ ...Object.entries(cmsBoxStyle(JSON.stringify(raw.box))).map(([name, value2]) => `${name.replace(/[A-Z]/g, (letter) => "-" + letter.toLowerCase())}:${value2}`)
201
+ ];
202
+ const box = object(raw.box);
203
+ const inlineSize = (layout.width || layout.height || box.widthPercent) && !box.hidden && !box.columns ? `:is(span,a,strong,small,label)[data-cms-text-layout="${id}"]{display:${layout.textAlign ? "block" : "inline-block"}!important}` : "";
204
+ return declarations.length ? `@media ${CMS_DEVICE_MEDIA[mode]}{[data-cms-text-layout="${id}"]{${declarations.map((rule) => `${rule}!important`).join(";")}}${inlineSize}}` : "";
205
+ }).join(""));
206
+ }
207
+ const list = array(value);
208
+ if (list) list.forEach((item) => walk(item, depth + 1));
209
+ }
210
+ };
211
+ walk(content, 0);
212
+ return [...styles.values()].join("");
213
+ }
214
+ function validateCmsLayoutContent(content, depth = 0) {
215
+ if (depth > 10) throw new CmsLayoutValidationError("Layout l\u1ED3ng nhau v\u01B0\u1EE3t gi\u1EDBi h\u1EA1n.");
216
+ if (content.__cmsLayoutVersion !== void 0 && content.__cmsLayoutVersion !== 1) throw new CmsLayoutValidationError("Phi\xEAn b\u1EA3n layout kh\xF4ng \u0111\u01B0\u1EE3c h\u1ED7 tr\u1EE3.");
217
+ for (const [key, value] of Object.entries(content)) {
218
+ if (Object.values(CMS_LAYOUT_KEYS).includes(key)) {
219
+ if (typeof value !== "string" || value.length > 2e5) throw new CmsLayoutValidationError("C\u1EA5u h\xECnh layout kh\xF4ng h\u1EE3p l\u1EC7.");
220
+ let parsed;
221
+ try {
222
+ parsed = JSON.parse(value);
223
+ } catch {
224
+ throw new CmsLayoutValidationError("C\u1EA5u h\xECnh layout kh\xF4ng h\u1EE3p l\u1EC7.");
225
+ }
226
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || Object.keys(parsed).length > 2e3) throw new CmsLayoutValidationError("C\u1EA5u h\xECnh layout kh\xF4ng h\u1EE3p l\u1EC7.");
227
+ for (const [name, entry] of Object.entries(parsed)) {
228
+ if (name.length > 500 || !isCmsLayoutField(name) || typeof entry !== "string") throw new CmsLayoutValidationError("Thu\u1ED9c t\xEDnh layout kh\xF4ng h\u1EE3p l\u1EC7.");
229
+ if (entry && !(name.endsWith("Color") || name === "backgroundColor")) {
230
+ let parsedEntry;
231
+ try {
232
+ parsedEntry = JSON.parse(entry);
233
+ } catch {
234
+ throw new CmsLayoutValidationError("Gi\xE1 tr\u1ECB layout kh\xF4ng h\u1EE3p l\u1EC7.");
235
+ }
236
+ if (!parsedEntry || typeof parsedEntry !== "object" || Array.isArray(parsedEntry)) throw new CmsLayoutValidationError("Gi\xE1 tr\u1ECB layout kh\xF4ng h\u1EE3p l\u1EC7.");
237
+ }
238
+ if (entry && cmsVisualValue(name, entry) !== entry) {
239
+ const source = object(entry), safe = object(cmsVisualValue(name, entry));
240
+ if (name.endsWith("Color") || name === "backgroundColor" || JSON.stringify(Object.keys(source).sort()) !== JSON.stringify(Object.keys(safe).sort()) || Object.keys(source).some((prop) => source[prop] !== safe[prop])) throw new CmsLayoutValidationError("Gi\xE1 tr\u1ECB layout kh\xF4ng h\u1EE3p l\u1EC7.");
241
+ }
242
+ }
243
+ } else {
244
+ const list = array(value);
245
+ if (list) list.forEach((item) => validateCmsLayoutContent(item, depth + 1));
246
+ }
247
+ }
248
+ }
249
+ function cmsBoxStyle(value) {
250
+ const box = object(cmsVisualValue("xBoxLayout", value));
251
+ return {
252
+ ...box.widthPercent ? { width: `${box.widthPercent}%`, maxWidth: "100%", minWidth: 0 } : {},
253
+ ...box.padding !== void 0 ? { padding: `${box.padding}px`, boxSizing: "border-box" } : {},
254
+ ...box.margin !== void 0 ? { margin: `${box.margin}px` } : {},
255
+ ...box.gap !== void 0 ? { gap: `${box.gap}px` } : {},
256
+ ...box.columns ? { display: "grid", gridTemplateColumns: `repeat(${box.columns},minmax(0,1fr))` } : {},
257
+ ...box.order !== void 0 ? { order: Number(box.order) } : {},
258
+ ...box.align ? { textAlign: String(box.align), justifyItems: box.align === "left" ? "start" : box.align === "right" ? "end" : "center" } : {},
259
+ ...box.hidden === true ? { display: "none" } : {}
260
+ };
261
+ }
262
+ function changeCmsLayoutDevice(content, target, source, fields) {
263
+ const walk = (record, depth, schema) => {
264
+ if (depth > 10) return record;
265
+ let next = { ...record };
266
+ const keys = /* @__PURE__ */ new Set([...Object.keys(record).filter(isCmsLayoutField), ...CMS_DEVICES.flatMap((mode) => Object.keys(cmsLayoutProfile(record, mode)))]);
267
+ for (const key of keys) {
268
+ const value = source ? cmsLayoutValue(record, key, source) : "";
269
+ next = writeValue(next, key, key.endsWith("TextLayout") ? JSON.stringify({ ...semantic(record[key]), ...object(value) }) : value, target);
270
+ }
271
+ for (const [key, value] of Object.entries(record)) {
272
+ const list = schema && schema.find((field) => field.key === key)?.type !== "list" ? null : array(value);
273
+ if (list) next[key] = JSON.stringify(list.map((item) => walk(item, depth + 1, schema?.find((field) => field.key === key)?.itemFields)));
274
+ }
275
+ return next;
276
+ };
277
+ return walk(content, 0, fields);
278
+ }
279
+ export {
280
+ CMS_DEVICES,
281
+ CMS_DEVICE_MEDIA,
282
+ CMS_DEVICE_WIDTHS,
283
+ CMS_ITEM_ID,
284
+ CMS_LAYOUT_KEYS,
285
+ CmsLayoutValidationError,
286
+ applyCmsLayoutEdit,
287
+ changeCmsLayoutDevice,
288
+ cmsBoxStyle,
289
+ cmsDevice,
290
+ cmsLayoutHash,
291
+ cmsLayoutManaged,
292
+ cmsLayoutProfile,
293
+ cmsLayoutValue,
294
+ cmsResponsiveTextCss,
295
+ cmsTextLayoutId,
296
+ cmsVisualValue,
297
+ isCmsLayoutField,
298
+ projectCmsLayoutContent,
299
+ validateCmsLayoutContent
300
+ };