Files
iconfont-download/单文件拆分/sicon.vue
2023-08-21 11:48:31 +08:00

98 lines
2.8 KiB
Vue

<template>
<div ref="iconRef" style="display: inline-flex" :style="{ fontSize: `${size}px`, color: color as any }"></div>
</template>
<script lang="ts" setup>
import { FileUtil } from 'tools-vue3'
import { onMounted, onUnmounted, ref, watch } from 'vue'
const props = defineProps({
name: { default: 'wtyManager' },
type: {
default: 'up'
},
size: { default: '20' },
color: { default: undefined as any }
})
const w = watch(
() => [props.type, props.color],
() => {
init()
}
)
onUnmounted(() => {
w()
})
onMounted(() => {
init()
})
const iconRef = ref<HTMLDivElement>({} as any)
const viewBoxStr = '#{viewBox}'
const viewBoxDefault = '0 0 1024 1024'
const str = {
svg: [
`<svg style="width: 1em;height: 1em;vertical-align: middle;overflow: hidden;" viewBox="${viewBoxStr}" version="1.1" xmlns="http://www.w3.org/2000/svg">`,
'</svg>'
],
get0: (replacestr: string) => {
return str.svg[0].replace(viewBoxStr, replacestr)
},
getPath: (param: { d: string; fill?: string }) => {
return `<path d="${param.d}" fill="${param.fill ?? 'currentColor'}" />`
}
}
const init = async () => {
const color = ['color:black;', 'color:red;']
const filestr = (await FileUtil.getFile(`/static_res/sicon/${props.name}/${props.type}1.json`)) as string
if (!filestr) {
console.info(
`%c icon <%c${props.name}-${props.type}%c> 不存在`,
`${color[0]} font-size:12px`,
color[1],
color[0]
)
return
}
let res = ''
if (!filestr.startsWith('{')) {
res = `${str.get0(viewBoxDefault)}<path d="${filestr}" fill="currentColor" />${str.svg[1]}`
} else {
let objt: { d: string[]; fill: { [key: string]: number[] }; viewBox?: string } = JSON.parse(filestr)
res = str.get0(objt.viewBox ?? viewBoxDefault)
const getFill = (fill: { [key: string]: number[] }, index: number) => {
const fillkeys = Object.keys(fill)
const colors = props.color
for (let i = 0; i < fillkeys.length; i++) {
const key = fillkeys[i]
const nums = fill[key]
if (nums.includes(index)) {
if (colors) {
if (Array.isArray(colors)) return colors[i] ?? colors[colors.length - 1]
return colors
} else {
return key
}
}
}
return 'currentColor'
}
objt.d.forEach((item, index) => {
res += str.getPath({
d: item,
fill: getFill(objt.fill, index)
})
})
res += str.svg[1]
}
iconRef.value.innerHTML = res
}
</script>