<template>
  <section class="AiFitView">
    <div class="view" :style="viewStyle">
      <slot/>
    </div>
  </section>
</template>
<script>
export default {
  name: "AiFitView",
  data() {
    return {
      origin: {
        width: 1920,
        height: 1080
      },
      width: 0,
      height: 0,
      observer: null
    }
  },
  computed: {
    scale: v => `scale(${Math.min(v.width / v.origin.width, v.height / v.origin.height) || 1})`,
    viewStyle: v => {
      let {width, height} = v.origin
      width += 'px'
      height += 'px'
      return {
        width, height, transform: v.scale
      }
    }
  },
  methods: {
    initSize() {
      this.width = this.$el.offsetWidth
      this.height = this.$el.offsetHeight
    }
  },
  mounted() {
    this.$nextTick(this.initSize)
    this.observer = new ResizeObserver(this.initSize)
    this.observer.observe(this.$el)
  },
  beforeDestroy() {
    this.observer?.disconnect()
  }
}
</script>
<style scoped lang="scss">
.AiFitView {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f3f6f9;
  background-image: linear-gradient(90deg, #eee 10%, transparent 0),
  linear-gradient(#eee 10%, transparent 0);
  background-size: 10px 10px;

  .view {
    flex-shrink: 0;
    background-color: #fff;
  }
}
</style>
