<script setup lang="ts">
import { onMounted } from 'vue';
import Konva from 'konva/lib';
import { useWindowSize } from '@vueuse/core';

const { width, height } = useWindowSize();
const MIN_WIDTH = 100;

const initial = () => {
	const stage = new Konva.Stage({ container: 'container', width: width.value, height: height.value });
	const layer = new Konva.Layer();
	stage.add(layer);

	const text = new Konva.Text({
		x: 50,
		y: 60,
		fontSize: 20,
		text: 'Hello from the Konva framework. Try to resize me.',
		draggable: true,
	});
	layer.add(text);

	const tr = new Konva.Transformer({
		nodes: [text],
		padding: 5,
		flipEnabled: false,
		enabledAnchors: ['middle-left', 'middle-right'],
		boundBoxFunc(oldBox, newBox) {
			if (Math.abs(newBox.width) < MIN_WIDTH) {
				return oldBox;
			}
			return newBox;
		},
	});

	layer.add(tr);

	text.on('transform', () => {
		text.setAttrs({
			width: Math.max(text.width() * text.scaleX(), MIN_WIDTH),
			scaleX: 1,
			scaleY: 1,
		});
	});
};

onMounted(() => {
	initial();
});
</script>

<template>
	<div id="container"></div>
</template>
