Svelte – Pannable Actions

1 min read


Hi people .. welcome back to our channel.. karena masih di Svelte jadi kita masuk ke materi Actions yang terakhir… okay langsung gas aja yakan…

file ini sebagai source kita… pannable.js

export function pannable(node) {
let x;
let y;

function handleMousedown(event) {
    x = event.clientX;
    y = event.clientY;

    node.dispatchEvent(new CustomEvent('panstart', {
        detail: { x, y }
    }));

    window.addEventListener('mousemove', handleMousemove);
    window.addEventListener('mouseup', handleMouseup);
}

function handleMousemove(event) {
    const dx = event.clientX - x;
    const dy = event.clientY - y;
    x = event.clientX;
    y = event.clientY;

    node.dispatchEvent(new CustomEvent('panmove', {
        detail: { x, y, dx, dy }
    }));
}

function handleMouseup(event) {
    x = event.clientX;
    y = event.clientY;

    node.dispatchEvent(new CustomEvent('panend', {
        detail: { x, y }
    }));

    window.removeEventListener('mousemove', handleMousemove);
    window.removeEventListener('mouseup', handleMouseup);
}

node.addEventListener('mousedown', handleMousedown);

return {
    destroy() {
        node.removeEventListener('mousedown', handleMousedown);
    }
};

dan buat file PannableActions.svelte

<script>
	import { spring } from 'svelte/motion';
	import { pannable } from './source/pannable';

	const coords = spring({ x: 0, y: 0 }, {
		stiffness: 0.2,
		damping: 0.4
	});

	function handlePanStart() {
		coords.stiffness = coords.damping = 1;
	}

	function handlePanMove(event) {
		coords.update($coords => ({
			x: $coords.x + event.detail.dx,
			y: $coords.y + event.detail.dy
		}));
	}

	function handlePanEnd(event) {
		coords.stiffness = 0.2;
		coords.damping = 0.4;
		coords.set({ x: 0, y: 0 });
	}
</script>

<div class="box"
	use:pannable
	on:panstart={handlePanStart}
	on:panmove={handlePanMove}
	on:panend={handlePanEnd}
	style="transform:
		translate({$coords.x}px,{$coords.y}px)
		rotate({$coords.x * 0.2}deg)"
></div>

<style>
	.box {
		--width: 100px;
		--height: 100px;
		position: relative;
		width: var(--width);
		height: var(--height);
		left: calc(50% - var(--width) / 2);
		top: calc(50% - var(--height) / 2);
		border-radius: 4px;
		background-color: #ff3e00;
		cursor: move;
	}
</style>

dan import ke App.svelte

	<CustomTransition />
	<ClickOutside />
	<LongpressActions />
	<PannableActions />

</main>

sehingga menjadi seperti ini ya…

okay sudah berhasil… mantab… untuk link github ada disini… sampai jumpa di materi selanjutnya ya… cyaaa

Bima Sena

Leave a Reply

Your email address will not be published. Required fields are marked *