1- import { VALID_UNITS } from '../constants' ;
2- import { LayoutBox , CssUnit , ParsedLength , FlexibleLength } from '../types' ;
3- import { sanitizeDomString } from './security' ;
4-
5- /**
6- * Convert the length input into a sanitized ParsedLength
7- *
8- * @param input - The raw length input.
9- * @returns A sanitized ParsedLength.
10- */
11- export function parseLength ( input : FlexibleLength | undefined ) : ParsedLength | undefined {
12- // 1. 处理空值或无效值
13- if ( input == null ) {
14- return undefined ;
15- }
16-
17- // 2. 处理 ParsedLength 对象
18- if ( typeof input === 'object' && 'unit' in input && 'value' in input ) {
19- return sanitizeParsedLength ( input ) ;
20- }
21-
22- // 3. 处理纯数字:默认 px
23- if ( typeof input === 'number' ) {
24- return {
25- value : Number . isFinite ( input ) ? input : 0 ,
26- unit : 'px' ,
27- } ;
28- }
29-
30- // 4. 处理字符串
31- const val = input . trim ( ) . toLowerCase ( ) ;
32- const numericPart = parseFloat ( val ) ;
33-
34- // 检查数字部分是否有效
35- if ( isNaN ( numericPart ) ) {
36- return { value : 0 , unit : 'px' } ;
37- }
38-
39- // 直接截取剩下的所有内容作为单位
40- const unitPart = val . slice ( String ( numericPart ) . length ) . trim ( ) ;
41-
42- return sanitizeParsedLength ( { value : numericPart , unit : unitPart as CssUnit } ) ;
43- }
44-
45- /**
46- * Check the whitelist of verification units and sanitize ParsedLength.
47- */
48- export const sanitizeParsedLength = ( parsed : ParsedLength ) : ParsedLength => {
49- const { value, unit } = parsed ;
50-
51- if ( ! isNaN ( value ) && ( VALID_UNITS as readonly string [ ] ) . includes ( unit ) ) {
52- return { value, unit } ;
53- }
54-
55- // 非法单位,降级为 px
56- console . warn ( `[OmniPad-Core] Blocked invalid CSS unit: ${ unit } ` ) ;
57- return { value : isNaN ( value ) ? 0 : value , unit : 'px' } ;
58- } ;
1+ import { LayoutBox , ParsedLength } from '../types' ;
592
603/**
614 * Convert the ParsedLength back to a CSS string
@@ -64,23 +7,6 @@ export const lengthToCss = (parsed: ParsedLength | undefined): string | undefine
647 return parsed == null ? undefined : `${ parsed . value } ${ parsed . unit } ` ;
658} ;
669
67- /**
68- * Validate a raw LayoutBox config.
69- */
70- export function validateLayoutBox ( raw : LayoutBox ) : LayoutBox {
71- return {
72- ...raw ,
73- left : parseLength ( raw . left ) ,
74- top : parseLength ( raw . top ) ,
75- right : parseLength ( raw . right ) ,
76- bottom : parseLength ( raw . bottom ) ,
77- width : parseLength ( raw . width ) ,
78- height : parseLength ( raw . height ) ,
79- // 关键:对选择器和类名进行脱毒处理 / Critical: Sanitize selector and class names
80- stickySelector : sanitizeDomString ( raw . stickySelector ) ,
81- } ;
82- }
83-
8410/**
8511 * Compress layout properties into css strings.
8612 */
0 commit comments