Цю сторінку ще не перекладено українською, тому нижче англійська версія.

Refresh control htmx

A quick-settings button for live parts of a page: 5, 10, 30 s or Off, kept per account and page in a cookie; here it drives an htmx poll.

Опції

ОпціяЗначення
_class('refresh_control')->render($key, $opt)options (seconds, 0 = off), default (10), title, class; $key names the page.
->value($key)The chosen seconds (0 = off), for the server to render the page with.
yf-refresh-changeEvent bubbling from the control, detail = {key, seconds}: restart your timer or poll. A live control adds live (true while the realtime hub is connected, when seconds is the longer safety interval).
'live' => trueOption of render(): the page can refresh on demand. While the site has realtime on, the control shows Live and fires yf-refresh-now; with realtime off it changes nothing.
yf-refresh-nowEvent bubbling from a live control, detail = {key, channel}: the data changed, refresh now (at most once a second, never while Off).
->notify($key)Server side: tells the open pages of $key that their data changed (a change notice, sent at the end of the request; false while realtime is off).

Приклад

Updated at 03:38:43

Код

$hx = _class('htmx');
if ($hx->_wants_fragment() && ($_GET['hx'] ?? '') === 'tick') {
    return $hx->_result('Updated at ' . date('H:i:s'));
}
asset('htmx');
$rc = _class('refresh_control');
$seconds = $rc->value('docs_ref_poll', 10);
// the poll follows the control without a reload: a copy of the element with the new hx-trigger replaces it
js('document.addEventListener("yf-refresh-change", function (e) {
    var el = document.getElementById("docs-ref-poll");
    if ( ! el || e.detail.key !== "docs_ref_poll") { return; }
    var copy = el.cloneNode(true);
    if (e.detail.seconds > 0) { copy.setAttribute("hx-trigger", "every " + e.detail.seconds + "s"); } else { copy.removeAttribute("hx-trigger"); }
    el.replaceWith(copy);
    window.htmx && window.htmx.process(copy);
});');
return $rc->render('docs_ref_poll', ['options' => [5, 10, 30, 0], 'default' => 10])
    . ' <span id="docs-ref-poll" hx-get="' . _prepare_html(url('/@object/htmx/refresh_control')) . '" hx-vals=\'{"hx": "tick"}\''
    . ($seconds > 0 ? ' hx-trigger="every ' . $seconds . 's"' : '') . '>Updated at ' . date('H:i:s') . '</span>';

Примітки

  • Asset yf_refresh_control, no jQuery; the menu is a .dropdown-menu, so Bootstrap 3 / 5, the themes and dark mode colour it; keyboard: arrows, Escape, Tab.
  • The admin uses it on the live log view and the cards of Cron jobs, Debug sessions, Kafka, OPcache, Manticore and Online users, which are live when the site has realtime on.

Див. також: htmx/fragment