km-card-layout-core 0.1.10 → 0.1.12

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/index.ts CHANGED
@@ -1,513 +1,21 @@
1
- /**
2
- * CardMaster 布局 JSON 渲染核心。
3
- *
4
- * - 平台无关:不依赖 DOM/小程序 API,方便在 Web/小程序/Node 复用。
5
- * - 职责:将布局 Schema 与业务数据合成为带内联样式的渲染树,外层只需将节点映射到各端组件。
6
- */
7
-
8
- import type {
9
- AbsoluteLayoutDefinition,
10
- CardElement,
11
- CardElementType,
12
- IconElement,
13
- ImageElement,
14
- LayoutPanelElement,
15
- TextElement,
16
- } from './interface/elements';
17
- import type { CardLayoutInput, CardLayoutSchema } from './interface/layout';
18
- import type {
19
- BindingContext,
20
- RenderNode,
21
- RenderPageResult,
22
- RenderResult,
23
- } from './interface/render';
24
-
25
- export * from './interface/index';
26
-
27
- /** ---------- 常量 ---------- */
28
-
29
- const DEFAULT_CARD_WIDTH = 343; // 默认卡片宽度(像素)
30
- const DEFAULT_CARD_HEIGHT = 210; // 默认卡片高度(像素)
31
-
32
- const DIMENSION_PROPS = new Set<string>([
33
- 'width',
34
- 'height',
35
- 'top',
36
- 'right',
37
- 'bottom',
38
- 'left',
39
- 'padding',
40
- 'paddingTop',
41
- 'paddingBottom',
42
- 'paddingLeft',
43
- 'paddingRight',
44
- 'margin',
45
- 'marginTop',
46
- 'marginBottom',
47
- 'marginLeft',
48
- 'marginRight',
49
- 'fontSize',
50
- 'lineHeight',
51
- 'borderRadius',
52
- 'borderWidth',
53
- 'letterSpacing',
54
- 'gap',
55
- 'rowGap',
56
- 'columnGap',
57
- ]);
58
-
59
- /** ---------- 基础工具 ---------- */
60
- /**
61
- * 安全转 number,非数值或 NaN 返回 undefined。
62
- */
63
- const toNumber = (value: unknown): number | undefined => {
64
- const num = Number(value);
65
- return Number.isFinite(num) ? num : undefined;
66
- };
67
- /**
68
- * camelCase 转 kebab-case(用于内联样式 key)。
69
- */
70
- const toKebab = (key: string): string =>
71
- key.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
72
- /**
73
- * 数字追加单位,非数字原样转字符串。
74
- * 数字追加单位,非数字原样转字符串。
75
- */
76
- export const addUnit = (
77
- value: string | number | undefined | null,
78
- unit: 'px' | 'rpx'
79
- ): string | undefined => {
80
- if (value === undefined || value === null || value === '') return undefined;
81
- if (typeof value === 'number') {
82
- const ratio = unit === 'rpx' ? 2 : 1;
83
- return `${value * ratio}${unit}`;
84
- }
85
- if (typeof value === 'string') {
86
- const parsed = Number(value);
87
- if (Number.isFinite(parsed)) {
88
- const ratio = unit === 'rpx' ? 2 : 1;
89
- return `${parsed * ratio}${unit}`;
90
- }
91
- }
92
- return `${value}`;
93
- };
94
- /**
95
- * 样式对象转内联样式字符串,对需要单位的字段自动补单位。
96
- */
97
- export const styleObjectToString = (
98
- style?: Record<string, any>,
99
- unit: 'px' | 'rpx' = 'px'
100
- ): string => {
101
- if (!style) return '';
102
- const pairs: string[] = [];
103
- Object.keys(style).forEach(key => {
104
- const value = style[key];
105
- if (value === undefined || value === null || value === '') return;
106
- const useUnit = DIMENSION_PROPS.has(key)
107
- ? addUnit(value as any, unit)
108
- : value;
109
- if (useUnit === undefined || useUnit === null || useUnit === '') return;
110
- pairs.push(`${toKebab(key)}:${useUnit}`);
111
- });
112
- return pairs.join(';');
113
- };
114
-
115
- /**
116
- * 容错 JSON 解析:字符串用 JSON.parse,其他保持原样或返回 null。
117
- */
118
- const parseJson = (input: unknown): any | null => {
119
- if (typeof input !== 'string') return input ?? null;
120
- try {
121
- return JSON.parse(input);
122
- } catch (err) {
123
- console.warn('[km-card-layout-core] JSON parse failed', err);
124
- return null;
125
- }
126
- };
127
-
128
- const isObject = (val: unknown): val is Record<string, any> | any[] =>
129
- Boolean(val) && typeof val === 'object';
130
-
131
- const getAbsLayout = (el: CardElement): AbsoluteLayoutDefinition | null =>
132
- el.layout && el.layout.mode === 'absolute'
133
- ? (el.layout as AbsoluteLayoutDefinition)
134
- : null;
135
-
136
- /** ---------- 布局与数据解析 ---------- */
137
-
138
- /**
139
- * 归一化布局输入(对象或 JSON 字符串),补齐宽高/容器/children 默认值。
140
- */
141
- export const normalizeLayout = (
142
- layout: CardLayoutInput
143
- ): CardLayoutSchema[] => {
144
- if (!Array.isArray(layout)) return [];
145
- return layout
146
- .map(item => {
147
- if (!item || typeof item !== 'object') return null;
148
- const parsed = item as CardLayoutSchema;
149
- return {
150
- ...parsed,
151
- width: toNumber((parsed as any).width) ?? DEFAULT_CARD_WIDTH,
152
- height: toNumber((parsed as any).height) ?? DEFAULT_CARD_HEIGHT,
153
- container: (parsed as any).container || { mode: 'absolute' },
154
- children: Array.isArray((parsed as any).children)
155
- ? ((parsed as any).children as CardElement[])
156
- : [],
157
- };
158
- })
159
- .filter((v): v is CardLayoutSchema => Boolean(v));
160
- };
161
-
162
- /**
163
- * 将绑定路径拆分为片段,支持点语法与数组下标。
164
- */
165
- const pathToSegments = (path: string): string[] =>
166
- `${path || ''}`
167
- .replace(/\[(\d+)\]/g, '.$1')
168
- .split('.')
169
- .map(p => p.trim())
170
- .filter(Boolean);
171
-
172
- /**
173
- * 按路径访问对象/数组,缺失时返回 undefined/null。
174
- */
175
- const readByPath = (data: any, path: string): any => {
176
- if (path === undefined || path === null || path === '') return data;
177
- const segments = pathToSegments(path);
178
- let cursor: any = data;
179
- for (let i = 0; i < segments.length; i += 1) {
180
- if (!isObject(cursor) && !Array.isArray(cursor)) return undefined;
181
- const key = segments[i];
182
- if (Array.isArray(cursor)) {
183
- const idx = Number(key);
184
- cursor = Number.isNaN(idx) ? undefined : cursor[idx];
185
- } else {
186
- cursor = (cursor as Record<string, any>)[key];
187
- }
188
- if (cursor === undefined || cursor === null) {
189
- return cursor;
190
- }
191
- }
192
- return cursor;
193
- };
194
- /**
195
- * Resolve element binding against provided data.
196
- */
197
- export const resolveBindingValue = (
198
- binding: string | undefined,
199
- rootData: Record<string, any>,
200
- context?: BindingContext
201
- ): any => {
202
- if (!binding) return undefined;
203
- const value = readByPath(rootData, binding);
204
- return value === undefined ? undefined : value;
205
- };
206
-
207
- /** ---------- 样式构建 ---------- */
208
-
209
- const buildCardStyle = (
210
- layout: CardLayoutSchema,
211
- unit: 'px' | 'rpx'
212
- ): string =>
213
- styleObjectToString(
214
- {
215
- width: addUnit(layout.width, unit),
216
- height: addUnit(layout.height, unit),
217
- color: layout.fontColor,
218
- borderRadius:
219
- layout.borderRadius !== undefined
220
- ? addUnit(layout.borderRadius, unit)
221
- : undefined,
222
- padding:
223
- layout.padding !== undefined ? addUnit(layout.padding, unit) : undefined,
224
- position: 'relative',
225
- overflow: 'hidden',
226
- boxSizing: 'border-box',
227
- backgroundColor: 'transparent',
228
- },
229
- unit
230
- );
231
-
232
- const buildBackgroundStyle = (
233
- layout: CardLayoutSchema,
234
- unit: 'px' | 'rpx'
235
- ): string =>
236
- styleObjectToString(
237
- {
238
- zIndex: layout.backgroundZIndex,
239
- borderRadius:
240
- layout.borderRadius !== undefined
241
- ? addUnit(layout.borderRadius, unit)
242
- : undefined,
243
- width: '100%',
244
- height: '100%',
245
- position: 'absolute',
246
- left: 0,
247
- top: 0,
248
- },
249
- unit
250
- );
251
-
252
- /**
253
- * 生成元素外层样式(绝对/弹性布局),始终返回内联样式字符串。
254
- */
255
- const buildWrapperStyle = (el: CardElement, unit: 'px' | 'rpx'): string => {
256
- const abs = getAbsLayout(el);
257
- if (!abs) return '';
258
-
259
- return styleObjectToString(
260
- {
261
- position: 'absolute',
262
- left: addUnit(abs.x, unit),
263
- top: addUnit(abs.y, unit),
264
- width: addUnit(abs.width, unit),
265
- height: addUnit(abs.height, unit),
266
- zIndex: abs.zIndex,
267
- boxSizing: 'border-box',
268
- },
269
- unit
270
- );
271
- };
272
- const buildPanelContentStyle = (
273
- el: LayoutPanelElement,
274
- unit: 'px' | 'rpx'
275
- ): string =>
276
- styleObjectToString(
277
- {
278
- position: 'relative',
279
- width: '100%',
280
- height: '100%',
281
- display: 'block',
282
- boxSizing: 'border-box',
283
- ...(el.style || {}),
284
- },
285
- unit
286
- );
287
-
288
- const buildTextContentStyle = (el: TextElement, unit: 'px' | 'rpx') => {
289
- const textAlign =
290
- (el.style?.textAlign as string | undefined) || el.align || undefined;
291
- const style: Record<string, any> = {
292
- ...(el.style || {}),
293
- whiteSpace: 'pre-wrap',
294
- wordBreak: 'break-word',
295
- lineHeight:
296
- el.style?.lineHeight !== undefined && el.style?.lineHeight !== null
297
- ? el.style.lineHeight
298
- : '1.2',
299
- display: 'inline-flex',
300
- alignItems: 'center',
301
- };
302
- if (textAlign) style.textAlign = textAlign;
303
- return styleObjectToString(style, unit);
304
- };
305
-
306
- const buildBaseContentStyle = (
307
- el: CardElement,
308
- unit: 'px' | 'rpx'
309
- ): string =>
310
- styleObjectToString(
311
- {
312
- ...(el.style || {}),
313
- boxSizing: 'border-box',
314
- },
315
- unit
316
- );
317
-
318
- const buildImageContentStyle = (
319
- el: ImageElement,
320
- unit: 'px' | 'rpx'
321
- ): string => {
322
- const style: Record<string, any> = { ...(el.style || {}) };
323
- const borderWidth = Number(style.borderWidth);
324
- if (Number.isFinite(borderWidth) && borderWidth > 0) {
325
- if (!style.borderStyle) style.borderStyle = 'solid';
326
- if (!style.borderColor) style.borderColor = '#000000';
327
- }
328
- return styleObjectToString(style, unit);
329
- };
330
-
331
- const buildTextIcon = (
332
- el: TextElement,
333
- unit: 'px' | 'rpx'
334
- ): RenderNode['icon'] | undefined => {
335
- const icon = el.icon;
336
- if (!icon || icon.enable === false) return undefined;
337
-
338
- const style = icon.style || 'fill';
339
- const baseName = el.key || el.binding || el.id;
340
- let name: string | undefined;
341
- if (style === 'dot') name = 'round';
342
- else if (style === 'line') name = baseName ? `${baseName}-line` : undefined;
343
- else name = baseName || undefined;
344
- if (!name) return undefined;
345
-
346
- const size =
347
- icon.size !== undefined && icon.size !== null
348
- ? icon.size
349
- : (el.style?.fontSize as any);
350
- const gap =
351
- icon.gap !== undefined && icon.gap !== null ? icon.gap : 4;
352
- const color =
353
- icon.color ??
354
- ((typeof el.style?.color === 'string' ? el.style.color : undefined) as
355
- | string
356
- | undefined);
357
-
358
- return {
359
- name: `${name}`,
360
- text: `${name}`,
361
- size: addUnit(size as any, unit),
362
- gap: addUnit(gap as any, unit),
363
- color: color as any,
364
- align: icon.align || 'left',
365
- wrapperStyle: styleObjectToString(
366
- {
367
- display: 'inline-flex',
368
- alignItems: 'center',
369
- height: el.style?.lineHeight || 'auto',
370
- },
371
- unit
372
- ),
373
- };
374
- };
375
-
376
- /** ---------- 渲染树构建 ---------- */
377
- /**
378
- * 将 children 展开为渲染节点。
379
- */
380
- export const buildRenderNodes = (
381
- children: CardElement[],
382
- rootData: Record<string, any>,
383
- unit: 'px' | 'rpx' = 'px',
384
- context: BindingContext = {}
385
- ): RenderNode[] => {
386
- if (!Array.isArray(children)) return [];
387
-
388
- const nodes: RenderNode[] = [];
389
- children.forEach(el => {
390
- if (!el || el.visible === false) return;
391
- const node = buildNode(el, rootData, unit, context);
392
- if (node) nodes.push(node);
393
- });
394
-
395
- return nodes;
396
- };
397
- /**
398
- * 构建单个渲染节点(layout-panel 递归处理子元素)。
399
- */
400
- const buildNode = (
401
- el: CardElement,
402
- rootData: Record<string, any>,
403
- unit: 'px' | 'rpx',
404
- context: BindingContext
405
- ): RenderNode | null => {
406
- if (!el || el.visible === false) return null;
407
- const wrapperStyle = buildWrapperStyle(el, unit);
408
-
409
- if (el.type === 'layout-panel') {
410
- return {
411
- id: el.id,
412
- type: el.type,
413
- visible: el.visible,
414
- wrapperStyle,
415
- contentStyle: buildPanelContentStyle(el as LayoutPanelElement, unit),
416
- children: buildRenderNodes(el.children || [], rootData, unit, context),
417
- };
418
- }
419
-
420
- const baseStyle = buildBaseContentStyle(el, unit);
421
- if (el.type === 'text') {
422
- const value =
423
- resolveBindingValue(el.binding, rootData, context) ??
424
- el.defaultValue ??
425
- '';
426
- return {
427
- id: el.id,
428
- type: el.type,
429
- wrapperStyle,
430
- contentStyle: buildTextContentStyle(el as TextElement, unit),
431
- text: `${value}`,
432
- visible: el.visible,
433
- icon: buildTextIcon(el as TextElement, unit),
434
- };
435
- }
436
-
437
- if (el.type === 'image') {
438
- const src =
439
- resolveBindingValue(el.binding, rootData, context) ??
440
- (el as ImageElement).defaultUrl ??
441
- el.defaultValue ??
442
- '';
443
- const mode =
444
- (el as ImageElement).fit === 'contain' ? 'aspectFit' : 'aspectFill';
445
- return {
446
- id: el.id,
447
- type: el.type,
448
- wrapperStyle,
449
- contentStyle: buildImageContentStyle(el as ImageElement, unit),
450
- src,
451
- mode,
452
- visible: el.visible,
453
- };
454
- }
455
-
456
- if (el.type === 'icon') {
457
- const name =
458
- resolveBindingValue(el.binding, rootData, context) ??
459
- (el as IconElement).name ??
460
- el.defaultValue ??
461
- '';
462
- return {
463
- id: el.id,
464
- type: el.type,
465
- wrapperStyle,
466
- contentStyle: baseStyle,
467
- name: `${name}`,
468
- text: `${name}`,
469
- visible: el.visible,
470
- };
471
- }
472
-
473
- if (el.type === 'custom') {
474
- return {
475
- id: el.id,
476
- type: el.type,
477
- wrapperStyle,
478
- contentStyle: baseStyle,
479
- visible: el.visible,
480
- };
481
- }
482
-
483
- return null;
484
- };
485
- /**
486
- * 主入口:合并布局 Schema 与数据,生成供前端使用的渲染结果。
487
- */
488
- export const buildRenderResult = (
489
- layoutInput: CardLayoutInput,
490
- dataInput: Record<string, any>,
491
- unit: 'px' | 'rpx' = 'px'
492
- ): RenderResult => {
493
- const layouts = normalizeLayout(layoutInput);
494
- return layouts.map(layout => {
495
- const cardStyle = buildCardStyle(layout, unit);
496
- const bgStyle = buildBackgroundStyle(layout, unit);
497
-
498
- const renderTree = buildRenderNodes(
499
- layout.children || [],
500
- dataInput || {},
501
- unit
502
- );
503
-
504
- return {
505
- renderTree,
506
- cardStyle,
507
- backgroundImage: layout.backgroundImage || '',
508
- backgroundStyle: bgStyle,
509
- };
510
- });
511
- };
512
-
513
- export * from './utils';
1
+ /**
2
+ * CardMaster 布局 JSON 渲染核心
3
+ *
4
+ * - 平台无关:不依赖 DOM/小程序 API,方便在 Web/小程序/Node 复用。
5
+ * - 职责:将布局 Schema 与业务数据合成可渲染树,外层只需将节点映射到各端组件。
6
+ */
7
+
8
+ export * from './interface/index';
9
+ export * from './helpers';
10
+ export * from './layout';
11
+ export * from './data';
12
+ export * from './bindings';
13
+ export {
14
+ backgroundChange,
15
+ DEFAULT_DECOR_COLOR,
16
+ resolveSpecialStyle,
17
+ applySpecialStyle,
18
+ applyBackground,
19
+ updateElementsStyle,
20
+ } from './ops/changeBackground';
21
+ export * from './render/builder';
package/layout.ts ADDED
@@ -0,0 +1,129 @@
1
+ import type {
2
+ AbsoluteLayoutDefinition,
3
+ CardElement,
4
+ LayoutPanelElement,
5
+ } from './interface/elements';
6
+ import type { CardLayoutInput, CardLayoutSchema } from './interface/layout';
7
+ import { toNumber, isObject } from './helpers';
8
+
9
+ const DEFAULT_CARD_WIDTH = 343;
10
+ const DEFAULT_CARD_HEIGHT = 210;
11
+
12
+ export const roundToInt = (value: number): number =>
13
+ Number.isFinite(value) ? Math.round(value) : value;
14
+
15
+ export const getAbsLayout = (
16
+ el: CardElement
17
+ ): AbsoluteLayoutDefinition | null =>
18
+ el.layout && el.layout.mode === 'absolute'
19
+ ? (el.layout as AbsoluteLayoutDefinition)
20
+ : null;
21
+
22
+ const roundAbsLayout = (
23
+ layout: AbsoluteLayoutDefinition
24
+ ): AbsoluteLayoutDefinition => ({
25
+ ...layout,
26
+ x: roundToInt(layout.x),
27
+ y: roundToInt(layout.y),
28
+ width: roundToInt(layout.width),
29
+ height: roundToInt(layout.height),
30
+ zIndex:
31
+ layout.zIndex !== undefined ? roundToInt(layout.zIndex) : layout.zIndex,
32
+ });
33
+
34
+ export const sanitizeElement = (el: CardElement): CardElement => {
35
+ const layout = getAbsLayout(el);
36
+ const base = layout ? { ...el, layout: roundAbsLayout(layout) } : el;
37
+ if (el.type === 'layout-panel' && el.children) {
38
+ return {
39
+ ...(base as CardElement),
40
+ children: el.children.map(child => sanitizeElement(child)),
41
+ } as LayoutPanelElement;
42
+ }
43
+ return base;
44
+ };
45
+
46
+ export const sanitizeLayout = (layout: CardLayoutSchema): CardLayoutSchema => ({
47
+ ...layout,
48
+ width: roundToInt(layout.width),
49
+ height: roundToInt(layout.height),
50
+ backgroundZIndex:
51
+ layout.backgroundZIndex !== undefined
52
+ ? roundToInt(layout.backgroundZIndex)
53
+ : layout.backgroundZIndex,
54
+ children: (layout.children || []).map(child => sanitizeElement(child)),
55
+ });
56
+
57
+ export const collectBindings = (elements: CardElement[] = []): string[] => {
58
+ const result: string[] = [];
59
+ elements.forEach(el => {
60
+ if (el.binding) result.push(el.binding);
61
+ if (el.type === 'layout-panel' && el.children) {
62
+ result.push(...collectBindings(el.children));
63
+ }
64
+ });
65
+ return Array.from(new Set(result));
66
+ };
67
+
68
+ export const normalizeId = (id?: string | number | null) => {
69
+ if (id === undefined || id === null) return undefined;
70
+ const num = Number(id);
71
+ return Number.isFinite(num) ? num : id;
72
+ };
73
+
74
+ const safeParseJson = (input: string): any | null => {
75
+ try {
76
+ return JSON.parse(input);
77
+ } catch (err) {
78
+ console.warn('[km-card-layout-core] parseLayout failed', err);
79
+ return null;
80
+ }
81
+ };
82
+
83
+ const parseSingleLayout = (value: any): CardLayoutSchema | null => {
84
+ if (!value) return null;
85
+ if (Array.isArray(value)) return parseSingleLayout(value[0]);
86
+ if (typeof value === 'string') {
87
+ return parseSingleLayout(safeParseJson(value));
88
+ }
89
+ if (isObject(value)) {
90
+ const content = (value as any).content;
91
+ if (content !== undefined) {
92
+ const nested = parseSingleLayout(content);
93
+ if (nested) return nested;
94
+ }
95
+ return sanitizeLayout(value as CardLayoutSchema);
96
+ }
97
+ return null;
98
+ };
99
+
100
+ export const parseLayout = (input: unknown): CardLayoutSchema | null =>
101
+ parseSingleLayout(input);
102
+
103
+ export const normalizeLayout = (
104
+ layout: CardLayoutInput
105
+ ): CardLayoutSchema[] => {
106
+ if (!Array.isArray(layout)) return [];
107
+ return layout
108
+ .map(item => {
109
+ if (!item || typeof item !== 'object') return null;
110
+ const parsed = item as CardLayoutSchema;
111
+ return {
112
+ ...parsed,
113
+ width: toNumber(parsed.width) ?? DEFAULT_CARD_WIDTH,
114
+ height: toNumber(parsed.height) ?? DEFAULT_CARD_HEIGHT,
115
+ container: (parsed as any).container || { mode: 'absolute' },
116
+ children: Array.isArray((parsed as any).children)
117
+ ? ((parsed as any).children as CardElement[])
118
+ : [],
119
+ };
120
+ })
121
+ .filter((value): value is CardLayoutSchema => Boolean(value));
122
+ };
123
+
124
+ export const areChildrenEqual = (
125
+ a?: CardLayoutSchema | null,
126
+ b?: CardLayoutSchema | null
127
+ ): boolean => {
128
+ return JSON.stringify(a?.children) === JSON.stringify(b?.children);
129
+ };