mikebronner / laravel-caffeine

Keeping Your Laravel Forms Awake.
https://genealabs.com/docs/laravel-caffeine/
MIT License
913 stars 83 forks source link

Accumulation of drip calls with wire:navigate #152

Open mauritskorse opened 3 months ago

mauritskorse commented 3 months ago

Expected Behavior

Regular drip calls to the server set by the config.

Actual Behavior

When using livewire with wire:navigate the number of drip calls start to increase after having visited a couple of pages. The script is apparently initiated again after navigating.

Environment

Stack Trace

mauritskorse commented 3 months ago

It would be nice if the script.bade.php could be published to /resources/view/vendor to customize the javascript behaviour. For now I have adjusted the script to this:

    window.timers = window.timers || [];

    function startInterval(key, callback, delay) {
        // If an interval with the same key already exists, clear it
        if (window.timers[key]) {
            clearInterval(window.timers[key]);
        }
        // Start a new interval and store its ID in the timers object
        window.timers[key] = setInterval(callback, delay);
    }

    var lastCheck = new Date();

    var caffeineSendDrip = function () {
        var ajax = window.XMLHttpRequest
            ? new XMLHttpRequest
            : new ActiveXObject('Microsoft.XMLHTTP');

        ajax.onreadystatechange = function () {
            if (ajax.readyState === 4 && ajax.status === 204) {
                lastCheck = new Date();
            }
        };

        ajax.open('GET', '{{ $url }}');
        ajax.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        ajax.send();
    };

    var caffeineReload = function () {
        if (new Date() - lastCheck >= {{ $ageCheckInterval + $ageThreshold }}) {
            setTimeout(function () {
                location.reload(true);
            },  Math.max(0, {{ $ageCheckInterval }} - 500) )
        }
    };

    startInterval('dripTimer', caffeineSendDrip, {{ $interval }});

    if ({{ $ageCheckInterval }} > 0) {
        startInterval('ageTimer', caffeineReload, {{ $ageCheckInterval }});
    }

see https://github.com/mikebronner/laravel-caffeine/compare/master...mauritskorse:laravel-caffeine:fix/livewire-navigate