import { StyleSheet } from 'react-native'; import type { StyleProp } from 'react-native'; import type { NormalizedThumbnailDimensions, SanitizedThumbnailImageStyle, ThumbnailImageStyle, } from './types'; import { RESERVED_IMAGE_STYLE_KEYS, THUMBNAIL_DIMENSIONS } from './constants'; export function normalizeThumbnailDimensions( size: unknown ): NormalizedThumbnailDimensions { if (size === undefined || size === 'sm' || size === 'md' || size === 'lg') { return { dimensions: THUMBNAIL_DIMENSIONS[size ?? 'md'], diagnostics: [] }; } if (typeof size === 'object' && size !== null && !Array.isArray(size)) { const { width, height, borderRadius } = size as Record; if ( typeof width === 'number' && Number.isFinite(width) && width > 0 && typeof height === 'number' && Number.isFinite(height) && height > 0 && (borderRadius === undefined || (typeof borderRadius === 'number' && Number.isFinite(borderRadius) && borderRadius >= 0)) ) { return { dimensions: { width, height, borderRadius: borderRadius ?? THUMBNAIL_DIMENSIONS.md.borderRadius, }, diagnostics: [], }; } } return { dimensions: THUMBNAIL_DIMENSIONS.md, diagnostics: ['size'] }; } function invalidStyle(): SanitizedThumbnailImageStyle { return { style: {}, diagnostics: ['style'] }; } function isEmptyStyleInput(value: unknown): boolean { if (value === undefined || value === null || value === false) return true; if (!Array.isArray(value)) return false; return value.every(isEmptyStyleInput); } /** * 先 flatten 再复制允许字段,兼容 registered / array style,同时不修改 caller。 * 任意异常或非对象产物都失败关闭,避免宽类型 JS 值穿透到原生 Image。 */ export function sanitizeThumbnailImageStyle( style: StyleProp | undefined ): SanitizedThumbnailImageStyle { try { if (isEmptyStyleInput(style)) { return { style: {}, diagnostics: [] }; } if (typeof style !== 'object' && typeof style !== 'number') { return invalidStyle(); } const flattened = StyleSheet.flatten(style) as unknown; if (flattened === undefined || flattened === null || flattened === false) { return invalidStyle(); } // RN StyleSheet.flatten returns an object for object/array inputs and // undefined for non-objects (handled above); it never returns an array. const source = flattened as Record; const reserved = new Set(RESERVED_IMAGE_STYLE_KEYS); const foundReserved = new Set(); const sanitized: Record = {}; for (const [key, value] of Object.entries(source)) { if (reserved.has(key)) { foundReserved.add(key); } else { sanitized[key] = value; } } return { style: sanitized as ThumbnailImageStyle, diagnostics: RESERVED_IMAGE_STYLE_KEYS.filter((key) => foundReserved.has(key) ), }; } catch { return invalidStyle(); } }