<template>
  <canvas v-show="false" id="canvas_ruler"></canvas>
  <span :class="['adaptive_text', { wrap: wrap }]">{{ text }}</span>
</template>

<script setup lang="ts">
const props = withDefaults(
  defineProps<{
    text: string
    defaultFontSize?: number
    fontFamily: string
    wrap?: boolean
    lineWidth?: number
    maxNumRows?: number
  }>(),
  {
    lineWidth: 262,
    defaultFontSize: 32,
    wrap: false,
    maxNumRows: 2,
  },
)

const rem = 19.2
const fontSize = ref(props.defaultFontSize / rem)
const setUpFontSize = ref(props.defaultFontSize / rem)

function setFontSize() {
  const canvas = document.getElementById('canvas_ruler') as HTMLCanvasElement
  const ctx = canvas?.getContext('2d')
  const containerWidth = props.lineWidth / rem
  if (!ctx) return
  ctx.font = `${props.defaultFontSize}px ${props.fontFamily}`
  const textWidth = ctx.measureText(props.text || '').width
  const textOffsetWidth = (textWidth + 16) / rem // 文本宽度加上边距，16px 是左右内边距之和
  if (containerWidth < textOffsetWidth) {
    const newFontSize = fontSize.value * (containerWidth / textOffsetWidth)
    newFontSize < 12 / rem ? (setUpFontSize.value = 12 / rem) : (setUpFontSize.value = newFontSize)
  }
}

watch(
  () => props.text,
  nv => {
    setFontSize()
  },
)
onMounted(() => {
  setFontSize()
})
</script>
<style scoped lang="scss">
.adaptive_text {
  font-size: v-bind('setUpFontSize + "vw"');
  &.wrap {
    word-break: break-all;
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: v-bind('props.maxNumRows');
    -webkit-box-orient: vertical;
    text-align: center;
  }
}
</style>
