import { css } from "@emotion/react" ; import { ContextValue , getContextValue } from "../context" ; import { CSSObject , CSSProperties } from "@emotion/serialize" ; /**
 * 匹配所有的CSS数值类型的值
 */ export const CSSValueReg = /^((?:\-)?(?:\d+\.?|\.\d+|\d+\.\d+))([a-zA-Z%]*)$/ ; param value param defaultUnit export function normalizeUnit ( value ? , defaultUnit = "px" ) { if ( typeof value === "number" ) { return value + defaultUnit ; } if ( typeof value === "string" ) { const result = value . match ( CSSValueReg ) ; if ( Array . isArray ( result ) ) { return result [ 2 ] ? parseFloat ( value ) + result [ 2 ] : parseFloat ( value ) + defaultUnit ; } } return value ; } /**
 * CSS值的对象表示
 */ export interface SplitedValue { num : number ; unit : string ; } param value param defaultUnit export function splitValue ( value , defaultUnit = "px" ) { if ( typeof value === "number" ) { return { num : value , unit : defaultUnit } ; } if ( typeof value === "string" ) { const result = value . match ( CSSValueReg ) ; if ( Array . isArray ( result ) ) { return { num : parseFloat ( result [ 1 ] ) , unit : result [ 2 ] || defaultUnit } ; } } throw new Error ( "Invalid numeric format" ) ; } param style returns export function adaptive ( style ) { const ctx = getContextValue ( ) as ContextValue ; const max = { } ; const min = { } ; const normal = { } ; for ( let name in style ) { let value = style [ name as keyof CSSProperties ] ! ; if ( typeof value !== "number" ) { normal [ name ] = value ; } else { normal [ name ] = ( value * 100 ) / 750 + "vw" ; max [ name ] = ( value * ctx . maxDocWidth ) / 750 + "px" ; min [ name ] = ( value * ctx . minDocWidth ) / 750 + "px" ; } } return css ( { ... normal , [ `@media (min-width: ${ ctx . maxDocWidth }px)` ] : max , [ `@media (max-width: ${ ctx . minDocWidth }px)` ] : min , } ) ; }