saadeghi / svelte-countup

21 stars 5 forks source link

Support svelte 5 #4

Open J4gQBqqR opened 3 months ago

J4gQBqqR commented 3 months ago

Svelte introduces runes and changes to event. I rewrote your component using svelte 5 and typescript. I do not know your opinion on typescript and therefore did not create pull request.

Here is the code for your reference:

<script lang="ts">
    import { inview } from "svelte-inview";

    let isInView: boolean = $state(false);

    let {
        value,
        initial = 0,
        duration = 3000,
        step = 1,
        roundto = 1,
        format = true,
    }: {
        value: number;
        initial?: number;
        duration?: number;
        step?: number;
        roundto?: number;
        format?: boolean;
    } = $props();

    function formatNumber(input: number) {
        if (format) {
            return Math.round(input).toLocaleString();
        }
        return input;
    }

    let counterResult: number = $state(initial);
    let timers: number;

    while (duration / ((value - initial) / step) < 2) {
        step++;
    }

    timers = setInterval(
        () => {
            if (isInView) {
                if (counterResult < value) {
                    counterResult += step;
                } else {
                    clearInterval(timers);
                    counterResult = Math.round(value / roundto) * roundto;
                }
            }
        },
        duration / ((value - initial) / step),
    );
</script>

<span
    use:inview
    oninview_change={(event: CustomEvent<ObserverEventDetails>) => {
        const { inView } = event.detail;
        isInView = inView;
    }}
>
    {formatNumber(counterResult)}
</span>
J4gQBqqR commented 3 months ago

BTW, the update interval is 2 milliseconds (while (duration / ((value - initial) / step) < 2) {) this is way too aggressive. I would suggest set something as 50ms.

saadeghi commented 3 months ago

Thank you.
Using runes is not backward compatible so the component will be incompatible with all Svelte 4 and Svelte 3 apps if we use runes.
I think it's still too soon. Especially when stable version of Svelte 5 is not released yet.