<template>
  <div v-if="isExternal" :style="styleExternalIcon" class="svg-external-icon svg-icon" />
  <svg v-else :class="svgClass" aria-hidden="true" :style="styleSize()">
    <use :xlink:href="iconName" />
    <title v-if="title">{{ title }}</title>
  </svg>
</template>

<script setup name="svg-icon">
import { computed } from 'vue';
import { setPx } from '@/utils';

const props = defineProps({
  // svg图片名称
  name: {
    type: String,
    required: true,
  },
  size: {
    type: [Number, String],
    default: 16,
  },
  // class样式名称,如果svg标签需要添加class样式,那么就需要该属性来添加svg的样式
  className: {
    type: String,
    default: '',
  },
  title: {
    type: String,
    default: '',
  },
});

//是否外部链接
const isExternal = computed(() => {
  return /^(https?:|mailto:|tel:)/.test(props.name);
});

//svg图片名称计算属性
const iconName = computed(() => {
  return `#icon-${props.name}`;
});

//svg样式名称计算属性
const svgClass = computed(() => {
  if (props.className) {
    return 'svg-icon ' + props.className;
  } else {
    return 'svg-icon';
  }
});

const styleSize = () => {
  return {
    fontSize: setPx(props.size),
  };
};

const styleExternalIcon = computed(() => {
  return {
    mask: `url(${props.name}) no-repeat 50% 50%`,
    '-webkit-mask': `url(${props.name}) no-repeat 50% 50%`,
  };
});
</script>

<style scoped>
.svg-icon {
  overflow: hidden;
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentcolor;
}
.svg-external-icon {
  display: inline-block;
  background-color: currentcolor;
  mask-size: cover !important;
}
</style>
