import { domEach , isTag } from '../utils' ; import type { Element , Node } from 'domhandler' ; import type { Cheerio } from '../cheerio' ; category param names returns see https export function css < T extends Node > ( this , names ? ) ; category param names returns see https export function css < T extends Node > ( this , name ) ; category param prop param val returns see https export function css < T extends Node > ( this , prop , val ) ; category param prop param val returns see https export function css < T extends Node > ( this , prop ) ; export function css < T extends Node > ( this , prop ? , val ? ) { if ( ( prop != null && val != null ) || ( typeof prop === 'object' && ! Array . isArray ( prop ) ) ) { return domEach ( this , ( el , i ) => { if ( isTag ( el ) ) { setCss ( el , prop as string , val , i ) ; } } ) ; } return getCss ( this [ 0 ] , prop as string ) ; } private param el param prop param value param idx function setCss ( el , prop , value , idx ) { if ( typeof prop === 'string' ) { const styles = getCss ( el ) ; const val = typeof value === 'function' ? value . call ( el , idx , styles [ prop ] ) : value ; if ( val === '' ) { delete styles [ prop ] ; } else if ( val != null ) { styles [ prop ] = val ; } el . attribs . style = stringify ( styles ) ; } else if ( typeof prop === 'object' ) { Object . keys ( prop ) . forEach ( ( k , i ) => { setCss ( el , k , prop [ k ] , i ) ; } ) ; } } private category param el param props returns function getCss ( el ? , props ? ) ; private category param el param prop returns function getCss ( el , prop ) ; function getCss ( el ? , prop ? ) { if ( ! el || ! isTag ( el ) ) return ; const styles = parse ( el . attribs . style ) ; if ( typeof prop === 'string' ) { return styles [ prop ] ; } if ( Array . isArray ( prop ) ) { const newStyles = { } ; prop . forEach ( ( item ) => { if ( styles [ item ] != null ) { newStyles [ item ] = styles [ item ] ; } } ) ; return newStyles ; } return styles ; } private category param obj returns function stringify ( obj ) { return Object . keys ( obj ) . reduce ( ( str , prop ) => `${ str }${ str ? ' ' : '' }${ prop }: ${ obj [ prop ] };` , '' ) ; } private category param styles returns function parse ( styles ) { styles = ( styles || '' ) . trim ( ) ; if ( ! styles ) return { } ; return styles . split ( ';' ) . reduce < Record < string , string > > ( ( obj , str ) => { const n = str . indexOf ( ':' ) ; if ( n < 1 || n === str . length - 1 ) return obj ; obj [ str . slice ( 0 , n ) . trim ( ) ] = str . slice ( n + 1 ) . trim ( ) ; return obj ; } , { } ) ; }