useComponentScale.ts 2.19 KB
import { CSSProperties, computed, unref, watch } from 'vue';
import { ComponentPropsConfigType } from '../index.type';
import { componentOptionsInitConfig } from '../publicConfig';

export const useComponentScale = (props: { config: ComponentPropsConfigType }, onScale?: Fn) => {
  const getContainerSize = computed(() => {
    const { option } = props.config;
    const { widthPx, heightPx } = option;
    return {
      width: widthPx,
      height: heightPx,
    };
  });

  const getRatio = computed(() => {
    try {
      const { option, attr } = props.config;
      const { w, h } = attr;
      const { widthPx, heightPx, itemWidthRatio, itemHeightRatio } = option;

      const currentW = (widthPx * itemWidthRatio) / 100;
      const currentH = (heightPx * itemHeightRatio) / 100;

      const widthScaleRatio = currentW / w;
      const heightScaleRatio = currentH / h;

      return Math.min(widthScaleRatio, heightScaleRatio);
    } catch (error) {
      return 1;
    }
  });

  // 数值列表等多个数据源使用的getRatios
  const getRatios = computed(() => {
    try {
      const { option, attr } = props.config;
      const { w, h } = attr;
      const { widthPx, heightPx, itemHeightRatio } = option;

      const currentW = (widthPx * 100) / 100;
      const currentH = (heightPx * itemHeightRatio) / 100;

      const widthScaleRatio = currentW / w;
      const heightScaleRatio = currentH / h;

      return Math.min(widthScaleRatio, heightScaleRatio);
    } catch (error) {
      return 1;
    }
  });

  const getScaleRadio = computed(() => {
    try {
      const { persetOption = {} } = props.config;
      const {
        maxScale = componentOptionsInitConfig.maxScale,
        minScale = componentOptionsInitConfig.minScale,
      } = persetOption;

      let ratio = unref(getRatio);
      ratio = ratio > maxScale! ? maxScale! : ratio < minScale! ? minScale! : ratio;

      return ratio;
    } catch (error) {
      return 1;
    }
  });

  const getScale = computed<CSSProperties>(() => {
    return { transform: `scale(${unref(getScaleRadio)})` };
  });

  onScale &&
    watch(getRatio, () => {
      onScale?.();
    });

  return { getScale, getScaleRadio, getRatio, getContainerSize, getRatios };
};