<script lang="ts">
import { onScopeDispose, ref, watch } from 'vue';

export default {
  name: 'AppDialog',
  props: {
    open: { type: Boolean, required: true },
  },
  emits: ['update:open'],
  setup(props, { emit }) {
    const dialogElem = ref<HTMLDialogElement | null>(null);

    watch([dialogElem, () => props.open], () => {
      if(!dialogElem.value) return;
      if(props.open) {
        dialogElem.value.showModal();
      } else {
        dialogElem.value.close();
      }
    }, { immediate: true });

    function closeDialog() {
      emit('update:open', false);
    }

    onScopeDispose(() => {
      emit('update:open', false);
      dialogElem.value?.close();
    });

    return { dialogElem, closeDialog };
  }
}
</script>

<template>
<dialog ref="dialogElem" class="dialog">
  <div class="dialogwindow">
    <div class="topblock">
      <button type="button" @click="closeDialog()">×</button>
    </div>
    <slot></slot>
  </div>
</dialog>
</template>

<style scoped>
.topblock {
  text-align: end;
}
</style>
