import { App , Directive , h , render , VNodeArrayChildren } from 'vue' ; import { SvgSpriteOptions , SvgSpritePluginOptions } from './defs' ; import { checkClass , defaultOptions , getAttributes , getHref } from './utils' ; const options = { ... defaultOptions , } ; export const svgSpriteDirective = { beforeMount ( el , binding , vnode ) { const id = binding . value || vnode . props ! . symbol ; const { size , url } = ( vnode . props || { } ) as { size : string ; url : string ; } ; const attrs = getAttributes ( size ) ; attrs . viewBox && el . setAttribute ( 'viewBox' , attrs . viewBox ) ; attrs . width && el . setAttribute ( 'width' , attrs . width ) ; attrs . height && el . setAttribute ( 'height' , attrs . height ) ; id && el . removeAttribute ( 'symbol' ) ; size && el . removeAttribute ( 'size' ) ; const classes = el . getAttribute ( 'class' ) ; const hasClass = checkClass ( classes , options ) ; if ( ! hasClass ) { el . setAttribute ( 'class' , classes ? `${ classes } ${ options . class }` : options . class ) ; } const hasUseNode = el && el . querySelector ( 'use' ) !== null ; if ( ! hasUseNode ) { const href = getHref ( id , { ... options , url : url === undefined ? options . url : url , } ) ; const use = document . createElementNS ( 'http://www.w3.org/2000/svg' , 'use' ) ; use . setAttributeNS ( 'http://www.w3.org/1999/xlink' , 'xlink:href' , href ) ; use . setAttribute ( 'href' , href ) ; el . appendChild ( use ) ; } } , updated ( el , binding , vnode ) { const id = binding . value || vnode . props ! . symbol ; const { url } = ( vnode . props || { } ) as { url : string ; } ; const href = getHref ( id , { ... options , url : url === undefined ? options . url : url , } ) ; const useNode = el && el . querySelector ( 'use' ) ; if ( useNode ) { if ( ( useNode as Element ) . getAttribute ( 'href' ) === href ) { return ; } useNode . setAttribute ( 'href' , href ) ; useNode . setAttribute ( 'xlink-href' , href ) ; } } , } ; export const svgSpriteDirectivePlugin = { install ( app , opts = { } ) { options . class = opts . class === undefined ? defaultOptions . class : opts . class ; options . url = opts . url === undefined ? defaultOptions . url : opts . url ; app . directive ( 'svg' , svgSpriteDirective ) ; } , } ;