return function () {
    $self = url('/@object/@action/' . urlencode('form/tom_select'));
    $countries = [
        'at' => 'Austria', 'be' => 'Belgium', 'ca' => 'Canada', 'de' => 'Germany', 'dk' => 'Denmark', 'es' => 'Spain', 'fr' => 'France',
        'ge' => 'Georgia', 'gh' => 'Ghana', 'gr' => 'Greece', 'it' => 'Italy', 'jp' => 'Japan', 'nl' => 'Netherlands', 'no' => 'Norway',
        'pl' => 'Poland', 'pt' => 'Portugal', 'se' => 'Sweden', 'ua' => 'Ukraine', 'gb' => 'United Kingdom', 'us' => 'United States',
        // a label with markup: the widget shows it as text, the handler never runs
        'xa' => '<img src=x onerror="window.__yfXss=1"> Atlantis & Co',
    ];

    // The remote search endpoint: a GET that only reads (no CSRF token needed; anything that writes is a POST with the token). A site
    // checks access here as for its page. The query is visitor input: cut (tom_select_query) and escaped for the DB, LIKE wildcards
    // included (addcslashes + es()). The demo searches an SQLite copy in memory, never the site database; on a site:
    // db()->get_all('SELECT code AS value, name AS text FROM ' . db('countries') . ' WHERE name LIKE "%' . _es(addcslashes($q, '\\%_')) . '%" ORDER BY name LIMIT 20')
    if (isset($_GET['ts_search'])) {
        $q = html()->tom_select_query('q', 50);
        $rows = [];
        if ($q !== '' && extension_loaded('pdo_sqlite')) {
            $db = clone db();
            $db->DB_TYPE = 'pdo_sqlite';
            $db->DB_PREFIX = '';
            $db->LOG_ALL_QUERIES = false;
            $db->LOG_SLOW_QUERIES = false;
            $db->ERROR_AUTO_REPAIR = false;
            $class = main()->load_class_file('db_driver_pdo_sqlite', 'classes/db/');
            $db->db = new $class(['name' => ':memory:']);
            $db->_connected = true;
            $db->_tried_to_connect = true;
            $pdo = $db->db->db_connect_id;
            $pdo->exec('CREATE TABLE countries (code TEXT PRIMARY KEY, name TEXT)');
            $insert = $pdo->prepare('INSERT INTO countries (code, name) VALUES (?, ?)');
            foreach ($countries as $code => $name) {
                $insert->execute([$code, $name]);
            }
            $rows = $db->get_all("SELECT code AS value, name AS text FROM countries WHERE name LIKE '%" . $db->es(addcslashes($q, '\\%_')) . "%' ESCAPE '\\' ORDER BY name LIMIT 20");
        } elseif ($q !== '') {
            foreach ($countries as $code => $name) {
                mb_stripos($name, $q) !== false && $rows[] = ['value' => $code, 'text' => $name];
            }
        }
        html()->tom_select_send($rows, 20);
    }

    $intro = '<p class="docs-demo-intro">Select, search and tags on Tom Select, without jQuery: <code>tom_select_box()</code> with local
        options (single, <code>multiple</code>, which posts an array <code>name[]</code>) or a remote search (<code>ajax_url</code>: a GET
        that answers <code>[{"value": ..., "text": ...}]</code>, written with <code>html()->tom_select_query()</code> and
        <code>html()->tom_select_send()</code>; its source is at the top of this demo), and <code>tags_box()</code>, which posts one
        comma-separated string. The fields start with stored values (an edit page); the remote one gets the label of its stored value
        from <code>ajax_labels</code>. Labels are always text: search <code>atl</code> for a label with markup. Below, the server shows
        what it received. The demo stores nothing and searches a copy of its list in memory. Classes: <code>yf_form2</code>,
        <code>yf_html_tom_select</code>; asset <code>yf_select</code>.</p>';
    $colors = ['red' => 'Red', 'green' => 'Green', 'blue' => 'Blue', 'black' => 'Black', 'white' => 'White'];
    $sizes = ['Small' => ['xs' => 'XS', 's' => 'S'], 'Large' => ['l' => 'L', 'xl' => 'XL']];
    $form_id = 'docs_tom_select';
    $stored = ['ts_country' => 'ua', 'ts_size' => 's', 'ts_multi' => ['red'], 'ts_tags' => 'php,htmx'];
    $result = '';
    $form = form((array) $_POST + $stored, ['csrf' => true, '__form_id__' => $form_id, 'id' => 'ts_form', 'action' => $self])
        ->validate([
            '__form_id__' => $form_id,
            'ts_country' => 'trim|required',
            'ts_tags' => 'trim',
        ])
        ->on_validate_ok(function ($data) use (&$result, $countries, $colors, $sizes) {
            $multi = array_values(array_filter((array) ($data['ts_multi'] ?? []), fn ($v) => is_string($v) && isset($colors[$v])));
            $size = (string) ($data['ts_size'] ?? '');
            $out = [
                'ts_country' => (string) ($data['ts_country'] ?? ''),
                'country_known' => isset($countries[(string) ($data['ts_country'] ?? '')]),
                'ts_size' => $size,
                'size_known' => isset(array_merge(...array_values($sizes))[$size]),
                'ts_multi' => $multi,
                'ts_tags' => (string) ($data['ts_tags'] ?? ''),
                'tags' => html()->tom_select_tags($data['ts_tags'] ?? '', 5, 30),
            ];
            $json = json_encode($out, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
            $result = '<div class="alert alert-success" id="ts_result"><b>Received</b> (nothing stored):<pre>' . _prepare_html($json, 0) . '</pre></div>';
        })
        ->tom_select_box('ts_country', [], [
            'desc' => 'Country (remote search)', 'placeholder' => 'Type 2 letters', 'ajax_url' => $self . '?ts_search=1', 'ajax_min' => 2,
            'ajax_labels' => fn ($codes) => array_intersect_key($countries, array_flip($codes)),
        ])
        ->tom_select_box('ts_size', $sizes, ['desc' => 'Size (local, groups)', 'placeholder' => 'Pick a size', 'allow_clear' => 1])
        ->tom_select_box('ts_multi', $colors, ['desc' => 'Colours (multiple)', 'multiple' => 1, 'max_items' => 3])
        ->tags_box('ts_tags', ['php', 'htmx', 'mysql', 'redis', 'bootstrap'], ['desc' => 'Tags', 'max_tags' => 5, 'tag_max_length' => 30, 'placeholder' => 'Add tags'])
        ->save();
    // A failed CSRF check logs into the log_csrf_errors table; the demo writes no rows
    $guard = _class('csrf_guard');
    $log_errors = $guard->LOG_ERRORS;
    $guard->LOG_ERRORS = false;
    try {
        $html = (string) $form;
    } finally {
        $guard->LOG_ERRORS = $log_errors;
    }
    return $intro . $result . $html;
};

Select, search and tags on Tom Select, without jQuery: tom_select_box() with local options (single, multiple, which posts an array name[]) or a remote search (ajax_url: a GET that answers [{"value": ..., "text": ...}], written with html()->tom_select_query() and html()->tom_select_send(); its source is at the top of this demo), and tags_box(), which posts one comma-separated string. The fields start with stored values (an edit page); the remote one gets the label of its stored value from ajax_labels. Labels are always text: search atl for a label with markup. Below, the server shows what it received. The demo stores nothing and searches a copy of its list in memory. Classes: yf_form2, yf_html_tom_select; asset yf_select.