import { IDocument , NodeType } from 'svg-vdom' ; import { IRegularAttr , IRegularTag , IRuleOption } from '../../typings' ; import { ITag } from '../../typings/node' ; import { ariaAttributes , eventAttributes } from '../const/definitions' ; import { regularAttr } from '../const/regular-attr' ; import { regularTag } from '../const/regular-tag' ; import { hasProp } from '../utils/has-prop' ; import { legalValue } from '../validate/legal-value' ; import { attrIsEqual } from '../xml/attr-is-equal' ; import { parseStyleTree } from '../xml/parse-style-tree' ; export const rmAttribute = async ( dom , { option : { keepEvent , keepAria , } , params : { rmAttrEqDefault , } , } ) : Promise < void > => new Promise ( resolve => { const tags = dom . querySelectorAll ( NodeType . Tag ) as ITag [ ] ; tags . forEach ( node => { const tagDefine = regularTag [ node . nodeName ] ; if ( node . hasAttribute ( 'href' ) && node . hasAttribute ( 'xlink:href' ) ) { node . removeAttribute ( 'xlink:href' ) ; } for ( let i = node . attributes . length ; i -- ; ) { const attr = node . attributes [ i ] ; const attrDefine = regularAttr [ attr . fullname ] ; const value = attr . value ; if ( attrDefine . isUndef ) { let isUndef = true ; if ( ( keepEvent && eventAttributes . includes ( attr . fullname ) ) || ( keepAria && ariaAttributes . includes ( attr . fullname ) ) ) { isUndef = false ; } if ( isUndef ) { node . removeAttribute ( attr . fullname ) ; continue ; } } else { if ( ! value || ( ! attrDefine . couldBeStyle && ! attr . fullname . includes ( 'xmlns' ) && ! tagDefine . ownAttributes . includes ( attr . fullname ) ) || ! legalValue ( attrDefine , attr , node . nodeName ) ) { node . removeAttribute ( attr . fullname ) ; continue ; } } if ( rmAttrEqDefault ) { parseStyleTree ( dom ) ; if ( attrDefine . couldBeStyle && ( ! tagDefine . onlyAttr || ! tagDefine . onlyAttr . includes ( attr . fullname ) ) ) { const parentStyle = ( node . parentNode as ITag ) . styles ; if ( ! attrDefine . inherited || ! parentStyle || ! hasProp ( parentStyle , attr . fullname ) ) { if ( attrIsEqual ( attrDefine , attr . value , node . nodeName ) ) { node . removeAttribute ( attr . fullname ) ; continue ; } } } else { if ( attrIsEqual ( attrDefine , attr . value , node . nodeName ) ) { node . removeAttribute ( attr . fullname ) ; continue ; } } } if ( node . nodeName === 'use' ) { if ( attr . fullname === 'width' || attr . fullname === 'height' ) { if ( + value < 0 ) { node . removeAttribute ( attr . fullname ) ; } } } } } ) ; resolve ( ) ; } ) ;