Docs /Variflow Tokens

Developers: the Integration API

This page is for developers of other ExpressionEngine add-ons (page builders, block editors, anything with its own editor or storage) who want to:

  1. offer Variflow's picker for a value in their own editor;
  2. output that value in templates exactly as a Tokens field would; and
  3. have Variflow's usage tracking, build guard, renames, remaps and Undo cover the token references they store in their own tables.

You need none of Variflow's internals for this. Everything public lives in the BisonDigital\Variflow\EE\Integration namespace:

ee('variflow:Integration') The service: readiness, settings, the picker, validation, template output, the build query, usage.
ContentSource The interface your storage implements so Variflow can find and rewrite your references.
CellKey, SourceCell Where a reference lives, and what's stored there.
Registrar What the variflow_content_sources hook hands you to register a source.
FieldOptions, PickerConfig A picker's validated settings, and what <vf-picker> needs to draw one value.

The stability promise

The hook, ContentSource, the value objects and the Integration service are public from Variflow 1.2.0 and follow semantic versioning: nothing in them changes incompatibly before 2.0. New methods and constants may be added; Integration::API_VERSION (an int: 1 in 1.2.0; 2 in 1.3.0 with grid(); 3 in 1.3.0 with component variants; 4 in 1.3.0 with hidden tokens; 5 in 1.3.0 with named assets) goes up when they are, so you can check for what you use. Constructors marked @internal are Variflow's to call; get objects from the service. Anything outside the namespace may change in any release.

The API never throws at you. When Variflow can't serve a site, it answers with empty results and reason() says why; whatever your source throws is caught, logged and shown by variflow:doctor. Licensing doesn't change anything here: the picker and template output work whatever the site's licence, as Tokens fields do.

Getting the service

Variflow is optional for your add-on, so check it's installed first:

$addon = ee('Addon')->get('variflow');
if ($addon !== null && $addon->isInstalled()) {
    $variflow = ee('variflow:Integration');
    $siteId = (int) ee()->config->item('site_id');
    if ($variflow::API_VERSION >= 1 && $variflow->ready($siteId)) {
        // Offer tokens.
    } else {
        $why = $variflow->reason($siteId); // "Variflow has no live build for site 1 yet. …"
    }
}

ready($siteId) is true when Variflow is installed, its tables are there and the site has a live build. reason($siteId) is null then, or a sentence you can show.

Embedding the picker

Settings

A picker's settings mean the same as a Tokens field's (The Tokens fieldtype): mode (scheme, token or, from API 3, variant), allowed schemes, tier, type and group filters, an explicit list, the component (variant mode), a default, the display style and whether deprecated tokens are offered.

options($settings, $siteId) validates them with the fieldtype's own rules and returns FieldOptions. Its problems list says what doesn't fit the live build; store toArray():

$options = $variflow->options(['mode' => 'token', 'types' => ['color'], 'groups' => ['color.surface']], $siteId);
if (! $options->valid()) {
    // $options->problems: ['"color.nope" isn't a token in the live build.', …]
}
$stored = $options->toArray(); // mode, allowed_schemes, tiers, types, groups, explicit, default, display, hide_deprecated

// API 3: a picker of a component's variants ("button: Primary / Outline")
$style = $variflow->options(['mode' => 'variant', 'component' => 'component.button', 'default' => 'button:primary'], $siteId);
$style->toArray()['component']; // "component.button" (only variant pickers have the key)

To let site builders choose these settings in your own settings screen, settingsForm($current) gives you EE shared-form rows, the same controls and live "N tokens match" preview a Tokens field has. The inputs are named variflow[mode], variflow[tiers][] and so on, so what's posted goes straight back into options():

// Your settings page
$vars['sections'][] = $variflow->settingsForm($savedSettings);

// On save
$options = $variflow->options((array) ee()->input->post('variflow'), $siteId);

Assets and markup

picker($options, $value, $inputName, $label) returns a PickerConfig; render($config) turns it into the <vf-picker> element, with a no-JavaScript fallback (radios or a select) that posts the value by itself:

$config = $variflow->picker($options, $storedValue, 'my_field[accent]', 'Accent colour');
echo $variflow->render($config);

In the control panel, render() also adds the components script to the page. Anywhere else, load assets() yourself:

['scripts' => $scripts, 'styles' => $styles] = $variflow->assets();
foreach ($scripts as $url) {
    echo '<script type="module" src="' . htmlspecialchars($url) . '"></script>';
}

styles is empty today (the picker styles itself), but load it if it isn't. The script URLs change with each Variflow release, so don't hard-code them.

Two optional arguments: $compact (the one-line picker Grid and Fluid use) and $readOnly.

In a JavaScript editor (Vue, React, …), render the markup on the server and drop it into your component; <vf-picker> is a framework-free web component. Picking writes the reference to a hidden input named $inputName inside the element and fires a bubbling change event from it:

el.innerHTML = markupFromYourServer;
el.addEventListener('change', (event) => {
  if (event.target.matches('input[data-vf-hidden]')) {
    emit('update:value', event.target.value); // "color.surface.raised", or "" for the default
  }
});

PickerConfig::toArray() gives name, label and the payload (the JSON the element reads) if you want to draw your own summary of the value. Its stable keys: mode, display, value, state (default, selected, deprecated, unresolved, readonly), effective, default, choices (each ref, label, deprecated and preview) and messages.

Since API 4 (1.3.0): a token the file hides from editors is never among the choices, except the saved value, which is there with hidden: true so you can still show it (the picker pins it as the current value, and it saves unchanged). The optional groups key gives the headings the file sets for the choices' groups (path => label, description), which the picker uses when it groups a long list. If you draw your own picker from tokens(), leave out the ones with hidden set.

Validation and saving

Store the reference string the picker posts (scheme:dark, color.surface.raised), or an empty string for "use the default". Before saving, apply the fieldtype's rule:

$error = $variflow->validate($posted, $options, $previouslyStored);
if ($error !== null) {
    // "That choice isn't available for this field."
}

A new value must be one of the choices in the live build. An unchanged value always saves, even if it has since been deprecated or removed, so pass what's stored now as the third argument; an empty value always saves.

Template output

output($reference, $params, $siteId, $options) returns exactly what a Tokens field tag outputs (Templates). Pass your tag's parameters, plus modifier:

modifier Token value Scheme value Variant value (API 3)
(none) var(--vf-color-action-primary); typography needs part="font-size" data-vf-scheme="dark" button:outline
value #1e2420 (or one typography part) — —
class — vf-scheme-dark —
handle — dark outline
name color.action.primary (renames followed) scheme:dark button:outline
label Action primary Dark Outline

A variant outputs the value of the data-vf-variant attribute, not the attribute, so one element can carry several: data-vf-variant="{button_style} {card_style}". Renames are followed, and an empty or unresolvable value outputs $options' default (or nothing). Without $options, the mode comes from the value (scheme:…, a variant reference such as button:outline, or a token) and there's no default. Output never needs a licence and never throws; problems go to the template debugger.

public function accent()
{
    $params = ee()->TMPL->tagparams; // e.g. ['modifier' => 'value']
    return ee('variflow:Integration')->output($this->storedValue(), $params, $siteId, $options);
}

Remember to output the CSS too: {exp:variflow:css} in the page's <head>.

Checking your configuration against the build

If your add-on has configuration that names tokens or groups (a component schema that says "this slot takes a colour from color.surface"), check it against the live build:

$variflow->has($siteId, 'color.surface');            // a group, a token, "scheme:dark" or "button:outline"
$variflow->has($siteId, 'color.surface', 'color');   // …holding at least one colour token
$variflow->groups($siteId, 'color');                 // every group with colour tokens
$variflow->tokens($siteId, 'color.surface');         // the tokens in a group, at any depth

groups() returns each group's path, label, count (tokens at any depth), types and tier (null when its tokens' tiers differ). tokens() returns each token's path, type, label, tier, value (what :root shows) and deprecated. has() follows renames.

The grid and layout presets

From Variflow 1.3.0 (API_VERSION 2), a token file can define a page grid and layout presets (Grid and layout presets). A page builder lays pages out from them: editors pick a preset ("8 / 4", "Three across"), never column spans.

if ($variflow::API_VERSION >= 2 && ($grid = $variflow->grid($siteId)) !== null) {
    foreach ($grid['presets'] as $preset) {
        if ($preset['minSlot'] <= $slotColumns) {
            $choices[$preset['name']] = $preset['label'];   // "8/4" => "8 / 4"
        }
    }
}

grid($siteId) returns null when the site's token file has no grid (or there's no live build). Otherwise:

Key
columns int, the column count
minSpan int, the narrowest an item may be, in columns
gutter token, cssName and value: grid.gutter, --vf-grid-gutter, 24px (as :root has it; schemes may change it, so use the variable)
containers name => token, cssName, value, for default and wide when the file has them
breakpoints name => token, cssName, value, narrowest first (sm, md, lg, …). value is the literal for a media or container query, which can't read variables
presets list of name, label, spans, stackBelow, tablet, minSlot, in the file's order
presetsDefault true when the file lists no presets and these are Variflow's defaults

A preset's spans add up to columns. Below stackBelow (a breakpoint name) its items stack; with tablet spans (otherwise null) they use those from sm until stackBelow. minSlot is its fit width: the narrowest slot, in columns of the page grid, it fits in when nested, so no item gets narrower than minSpan. With 12 columns and minSpan 3, a 4-across needs the full 12 and a 6/6 needs 6. Offer a preset in a slot only when minSlot is at most the slot's span.

To render a preset, output the layout stylesheet and the attributes (Layouts):

{exp:variflow:layout_css}
<div data-vf-layout="8/4"><div>…</div><div>…</div></div>

Component variants

From API 3 (Variflow 1.3.0), a token file can give a component group named variants (Component variants): component.button with Primary, Outline and Ghost. An inspector offers "button: Primary / Outline" from them, and the editor picks a name, never a colour.

if ($variflow::API_VERSION >= 3) {
    foreach ($variflow->variants($siteId, 'button') as $group) {   // "button" or "component.button"
        foreach ($group['variants'] as $v) {
            $choices[$v['ref']] = $v['label'];   // "button:outline" => "Outline"
        }
        $default = $group['key'] . ':' . $group['default'];   // "button:primary"
    }
}

variants($siteId, $group = null) returns every group with variants (sorted by path), or only $group; [] when there are none or there's no live build. Each group:

Key
group, key, label component.button, button, Button
default the default variant's name: the group's own values, what an element without the attribute shows
tokens the tokens its variants change: the ones they override, and what depends on them (a derived hover)
variants in the file's order, each with name, ref (button:outline: store this), label, description (or null), default (bool), preview and colours

A variant's preview lists the tokens whose value differs from the default variant's, as :root shows them: token, label, type, value and the default's value as default. colours is what the Tokens field's cards draw (surface, fill, text, border, shadow, each a CSS value or null), for a swatch of your own.

Store the reference and render it in the attribute, with the token CSS loaded. Every variant's values are right under every scheme, whichever is nested in which:

<a class="btn" data-vf-variant="{exp:my_addon:style}">Book now</a>   <!-- button:outline -->
<div data-vf-variant="button:outline card:flat">…</div>              <!-- several components -->

Variant references are content like token references. Report them from your content source as they're stored (button:outline): usage counts them, the build guard refuses a token file that drops a variant your content uses, and a remap can replace one (find() and replace() get button:ghost → button:outline).

Assets

From Variflow 1.3.0 (API_VERSION 5), namedAssets($siteId) lists the site's assets: the logos and other files the token file and the Assets page name. Offer them in your own image picker, store asset:<name>, and resolve it with namedAsset() when you output, so a file replaced on the Assets page follows on every page that uses it:

if ($variflow::API_VERSION >= 5 && ($logo = $variflow->namedAsset($siteId, 'asset:logo')) !== null) {
    echo '<img src="' . htmlspecialchars($logo['url']) . '" alt="' . htmlspecialchars((string) $logo['alt']) . '">';
}

alt is "" for a decorative asset and null when none is given. schemes lists the files of the schemes that swap one (an <img> can't follow data-vf-scheme; the CSS variable cssName can).

Writing a content source

Your add-on stores token references in its own format: a table, or a JSON document in a field. Variflow can't read that, so you tell it how, with a content source. Once registered, your content is covered like a Tokens field:

  • usage: the token page's Usage list shows it, and variflow:usage:rebuild reads it;
  • the build guard: a build can't remove a token, scheme or (API 3) component variant your content uses;
  • renames with rewrite, deprecate-and-swap and remaps rewrite your values through your source, and Undo puts them back the same way.

Variflow never reads or writes your storage itself.

The interface

interface ContentSource
{
    public function name(): string;                                    // "token_notes"
    public function available(): bool;                                 // your tables are there
    public function cells(int $siteId): iterable;                      // every SourceCell on a site
    public function cellsFor(int $siteId, int $entryId): iterable;     // one entry's cells
    public function find(int $siteId, string $reference): iterable;    // cells holding exactly $reference
    public function replace(CellKey $key, string $from, ?string $to): bool;
}

Each SourceCell has a CellKey (where), the stored value, a description for the control panel ("Token Notes › Spring sale") and an optional editUrl, a CP path such as addons/settings/token_notes/edit?id=4 (not a compiled URL: those can carry the session). A CellKey is your source's name(), the site, the entry (0 for content that isn't part of a channel entry), an itemId only you understand (up to 191 characters; a row ID, 12:hero.accent, …) and optionally the EE fieldId holding it, which the CP names.

The rules:

  • Name: lower case letters, digits and _, starting with a letter, up to 32 characters. Usually your add-on's short name. channel and bloqs are taken.
  • Cells carry your name, and the site (and entry) asked for. Others are ignored and reported.
  • Item IDs are stable: the same location gives the same key on every read.
  • find() returns exactly the cells whose value, ignoring surrounding whitespace, is $reference, read from your storage.
  • replace() writes $to only where the value is still $from (ignoring surrounding whitespace) and returns whether it wrote. A null or empty $to means "nothing stored". Return false for another source's key, a location that's gone, or a value you won't change: the rewrite then counts it as skipped and its note in the control panel says so ("Skipped 2 references in token_notes: that add-on didn't write them").
  • Don't throw. If you do, Variflow catches it, logs it, lists it in variflow:doctor and treats the call as returning nothing.

Registering: the hook

Variflow fires the variflow_content_sources extension hook once per request, the first time it needs its sources. Add an extension method for it ($methods in your installer, or a migration) and register your source:

public function variflow_content_sources($registrar)
{
    $registrar->add(new \Example\TokenNotes\NotesSource());
}

add() returns false when the source is skipped: an invalid name, a name another source has, or a name() that throws. Skipped sources are logged and variflow:doctor lists them; nothing else is affected.

Keeping usage current

Variflow learns about changes three ways:

  • When you save: call recordUsage($source, $siteId, $entryId, $cells) with the cells you just stored. For an entry, it replaces every row your source has for that entry (pass [] when the entry no longer holds any). For content outside entries ($entryId 0), it replaces only the items your cells name; a cell with an empty value clears its item.
  • After an entry saves: Variflow re-reads cellsFor() for that entry anyway, from EE's after_channel_entry_save hook and again once EE has written an updated entry's field data (1.3.0), so entry content stays current even if you don't call recordUsage(), and cellsFor() can read the entry's saved field data.
  • When content goes: deleting an entry deletes every source's rows for it. For content outside entries, call forget($source, $itemId) when you delete it (and for each item when your add-on is uninstalled).

variflow:usage:rebuild replaces everything from cells().

Contract tests

Variflow's own sources are tested against one contract: ContentSourceContract, a PHPUnit test case printed in full at the end of this page. Copy it into your tests and extend it:

final class NotesSourceTest extends ContentSourceContract
{
    protected function source(): ContentSource
    {
        return new NotesSource(/* fresh fixture storage with two or more values on site 1 */);
    }
}

It checks the name, that cells are yours and on the right site, stable item IDs, cellsFor(), exact find(), and that replace() writes only where the value is still $from, refuses keys it doesn't own, and clears with null.

A complete example: Token Notes

A tiny add-on that stores a colour token per note in its own table, with a CP page that uses Variflow's picker, a template tag, and a content source. Copy these files into system/user/addons/token_notes/, install Token Notes in Add-Ons, and open it. Variflow's own tests install it as written.

Notes aren't part of entries, so their cells have entry 0, saving calls recordUsage(), and deleting calls forget().

token_notes/addon.setup.php

The add-on.

<?php

return [
    'name'           => 'Token Notes',
    'description'    => 'Notes that each store a colour token, through Variflow Tokens.',
    'version'        => '1.0.0',
    'author'         => 'Example',
    'author_url'     => 'https://example.com',
    'namespace'      => 'Example\TokenNotes',
    'settings_exist' => true,
];

token_notes/upd.token_notes.php

Install: the table, and the extension row for Variflow's hook. Uninstall tells Variflow the notes are gone.

<?php

use ExpressionEngine\Service\Addon\Installer;

class Token_notes_upd extends Installer
{
    public $has_cp_backend = 'y';

    // The extension hook Variflow fires to collect content sources.
    public $methods = [['hook' => 'variflow_content_sources']];

    public function install()
    {
        parent::install();
        ee()->load->dbforge();
        ee()->dbforge->add_field([
            'note_id' => ['type' => 'int', 'unsigned' => true, 'auto_increment' => true],
            'site_id' => ['type' => 'int', 'unsigned' => true],
            'title'   => ['type' => 'varchar', 'constraint' => 100],
            'token'   => ['type' => 'varchar', 'constraint' => 191, 'default' => ''],
        ]);
        ee()->dbforge->add_key('note_id', true);
        ee()->dbforge->create_table('token_notes', true);

        return true;
    }

    public function uninstall()
    {
        // Tell Variflow the notes are gone, so its usage index doesn't keep them.
        if (ee()->db->table_exists('token_notes') && ee('Addon')->get('variflow')?->isInstalled()) {
            foreach (ee()->db->select('note_id')->get('token_notes')->result_array() as $row) {
                ee('variflow:Integration')->forget('token_notes', (string) $row['note_id']);
            }
        }
        parent::uninstall();
        ee()->load->dbforge();
        ee()->dbforge->drop_table('token_notes', true);

        return true;
    }
}

token_notes/ext.token_notes.php

The hook: register the source.

<?php

class Token_notes_ext
{
    public $version = '1.0.0';

    /** Variflow's variflow_content_sources hook: register where the notes keep their tokens. */
    public function variflow_content_sources($registrar)
    {
        $registrar->add(new \Example\TokenNotes\NotesSource());
    }
}

token_notes/NotesSource.php

Where the notes keep their tokens.

<?php

namespace Example\TokenNotes;

use BisonDigital\Variflow\EE\Integration\CellKey;
use BisonDigital\Variflow\EE\Integration\ContentSource;
use BisonDigital\Variflow\EE\Integration\SourceCell;

/** Where the notes keep their tokens: one cell per note, outside entries (entry 0). */
final class NotesSource implements ContentSource
{
    public function name(): string
    {
        return Notes::SOURCE;
    }

    public function available(): bool
    {
        return ee()->db->table_exists('token_notes');
    }

    public function cells(int $siteId): iterable
    {
        foreach (ee()->db->where('site_id', $siteId)->get('token_notes')->result_array() as $row) {
            yield self::cell($row);
        }
    }

    public function cellsFor(int $siteId, int $entryId): iterable
    {
        return []; // Notes aren't part of channel entries.
    }

    public function find(int $siteId, string $reference): iterable
    {
        $rows = ee()->db->where('site_id', $siteId)
            ->where('TRIM(token) = ' . ee()->db->escape($reference), null, false)
            ->get('token_notes')->result_array();

        return array_map([self::class, 'cell'], $rows);
    }

    public function replace(CellKey $key, string $from, ?string $to): bool
    {
        if ($key->source !== Notes::SOURCE || ! ctype_digit($key->itemId)) {
            return false;
        }
        ee()->db->where('note_id', (int) $key->itemId)
            ->where('TRIM(token) = ' . ee()->db->escape(trim($from)), null, false)
            ->update('token_notes', ['token' => trim((string) $to)]);

        return ee()->db->affected_rows() > 0;
    }

    /** @param array{note_id: int|string, site_id: int|string, title: string, token: string} $row */
    public static function cell(array $row): SourceCell
    {
        return new SourceCell(
            new CellKey(Notes::SOURCE, (int) $row['site_id'], 0, (string) $row['note_id']),
            (string) $row['token'],
            'Token Notes › ' . $row['title'],
            'addons/settings/token_notes/edit?id=' . $row['note_id'],
        );
    }
}

token_notes/Notes.php

Saving and deleting, with validation and recordUsage() / forget().

<?php

namespace Example\TokenNotes;

use BisonDigital\Variflow\EE\Integration\FieldOptions;

/** Reading and saving notes, keeping Variflow's usage index current as they change. */
final class Notes
{
    public const SOURCE = 'token_notes';

    /** What a note's picker offers: colour tokens, as swatches. */
    public static function options(int $siteId): FieldOptions
    {
        return ee('variflow:Integration')->options(['mode' => 'token', 'types' => ['color'], 'display' => 'swatches'], $siteId);
    }

    /** @return array{note_id: string, site_id: string, title: string, token: string}|null */
    public static function find(int $id): ?array
    {
        $row = ee()->db->where('note_id', $id)->get('token_notes')->row_array();

        return $row === [] ? null : $row;
    }

    /** Save a note (a new one when $id is 0). Returns its ID; throws with the editor's message when the token isn't allowed. */
    public static function save(int $siteId, int $id, string $title, string $token): int
    {
        $variflow = ee('variflow:Integration');
        $previous = $id > 0 ? (string) (self::find($id)['token'] ?? '') : '';
        $error = $variflow->validate($token, self::options($siteId), $previous);
        if ($error !== null) {
            throw new \InvalidArgumentException($error);
        }

        $row = ['site_id' => $siteId, 'title' => $title, 'token' => trim($token)];
        if ($id > 0) {
            ee()->db->where('note_id', $id)->update('token_notes', $row);
        } else {
            ee()->db->insert('token_notes', $row);
            $id = (int) ee()->db->insert_id();
        }

        // Notes live outside entries (entry 0): this replaces the usage row for this note only.
        $variflow->recordUsage(self::SOURCE, $siteId, 0, [NotesSource::cell(['note_id' => $id] + $row)]);

        return $id;
    }

    public static function delete(int $id): void
    {
        ee()->db->where('note_id', $id)->delete('token_notes');
        ee('variflow:Integration')->forget(self::SOURCE, (string) $id);
    }
}

token_notes/mcp.token_notes.php

The CP page: the list, and the form with Variflow's picker.

<?php

use Example\TokenNotes\Notes;

class Token_notes_mcp
{
    /** The list of notes. */
    public function index()
    {
        $siteId = (int) ee()->config->item('site_id');
        $variflow = ee('variflow:Integration');
        $html = '<p><a class="button button--primary" href="' . ee('CP/URL')->make('addons/settings/token_notes/edit') . '">New note</a></p><ul>';
        foreach (ee()->db->where('site_id', $siteId)->get('token_notes')->result_array() as $row) {
            $url = ee('CP/URL')->make('addons/settings/token_notes/edit', ['id' => $row['note_id']]);
            $html .= '<li><a href="' . $url . '">' . htmlspecialchars($row['title']) . '</a>: <code>'
                . htmlspecialchars($variflow->output($row['token'], [], $siteId, Notes::options($siteId))) . '</code></li>';
        }

        return ['heading' => 'Token Notes', 'body' => $html . '</ul>'];
    }

    /** Add or edit a note: a title and Variflow's own picker. */
    public function edit()
    {
        $siteId = (int) ee()->config->item('site_id');
        $variflow = ee('variflow:Integration');
        if (! $variflow->ready($siteId)) {
            return ['heading' => 'Token Notes', 'body' => '<p>' . htmlspecialchars((string) $variflow->reason($siteId)) . '</p>'];
        }

        $id = (int) ee()->input->get('id');
        $note = Notes::find($id) ?? ['title' => '', 'token' => ''];
        $error = null;
        if (ee('Request')->isPost()) {
            $note = ['title' => (string) ee()->input->post('title', true), 'token' => (string) ee()->input->post('token')];
            try {
                Notes::save($siteId, $id, $note['title'], $note['token']);
                ee()->functions->redirect(ee('CP/URL')->make('addons/settings/token_notes'));
            } catch (\InvalidArgumentException $e) {
                $error = $e->getMessage();
            }
        }

        $picker = $variflow->picker(Notes::options($siteId), $note['token'], 'token', 'Colour');
        $html = '<form method="post" action="' . ee('CP/URL')->make('addons/settings/token_notes/edit', ['id' => $id]) . '">'
            . '<input type="hidden" name="csrf_token" value="' . CSRF_TOKEN . '">'
            . ($error === null ? '' : '<p class="alert alert--issue">' . htmlspecialchars($error) . '</p>')
            . '<fieldset><label>Title <input type="text" name="title" value="' . htmlspecialchars($note['title']) . '"></label></fieldset>'
            . '<fieldset>' . $variflow->render($picker) . '</fieldset>'
            . '<button class="button button--primary" type="submit">Save</button></form>';

        return ['heading' => $id > 0 ? 'Edit note' : 'New note', 'body' => $html];
    }
}

token_notes/mod.token_notes.php

The template tag: {exp:token_notes:value title="Spring sale" modifier="value"}.

<?php

use Example\TokenNotes\Notes;

class Token_notes
{
    /**
     * {exp:token_notes:value title="Spring sale"}               var(--vf-color-…)
     * {exp:token_notes:value title="Spring sale" modifier="value"}  #2f6b4f
     * Takes the same parameters and modifiers as a Tokens field tag.
     */
    public function value()
    {
        $siteId = (int) ee()->config->item('site_id');
        $row = ee()->db->where('site_id', $siteId)->where('title', (string) ee()->TMPL->fetch_param('title'))->get('token_notes')->row_array();
        $params = array_diff_key((array) ee()->TMPL->tagparams, ['title' => true]);

        return ee('variflow:Integration')->output((string) ($row['token'] ?? ''), $params, $siteId, Notes::options($siteId));
    }
}

In a template, with the CSS tag in the page's <head>:

<div style="background: {exp:token_notes:value title="Spring sale"}">…</div>

Rename the note's token with a rewrite, or remap it after removing it from the token file, and the note follows; the token's Usage list shows "Token Notes › Spring sale", linking to the note.

Reference

Everything public, all in BisonDigital\Variflow\EE\Integration. Stable until 2.0.

Integration (ee('variflow:Integration')), API_VERSION = 5

Method Returns
ready(int $siteId) bool: installed, tables there, a live build
reason(int $siteId) ?string: why not ready, or null
options(array $settings, int $siteId) FieldOptions, validated as a Tokens field's settings
settingsForm(array $current, int $siteId = 0) EE shared-form rows, inputs named variflow[…]
picker(FieldOptions $o, string $value, string $inputName, string $label = '', bool $compact = false, bool $readOnly = false) PickerConfig
render(PickerConfig $c) string: <vf-picker> with its no-JS fallback
assets() ['scripts' => list<string>, 'styles' => list<string>]
validate(string $value, FieldOptions $o, string $previous = '') ?string: null when it may be saved
output(string $reference, array $params, int $siteId, ?FieldOptions $o = null) string: what a Tokens field tag outputs
groups(int $siteId, ?string $type = null) list of path, label, count, types, tier
tokens(int $siteId, string $group, ?string $type = null) list of path, type, label, tier, value, deprecated, hidden (API 4: true when the file keeps it from editors)
has(int $siteId, string $path, ?string $type = null) bool: a token, group, scheme:… or (API 3) variant reference
grid(int $siteId) ?array: columns, minSpan, gutter, containers, breakpoints, presets (with minSlot), presetsDefault; null without a grid. Since API 2 (1.3.0)
variants(int $siteId, ?string $group = null) list of groups: group, key, label, default, tokens, variants (each name, ref, label, description, default, preview, colours). Since API 3 (1.3.0)
namedAssets(int $siteId) list of assets (logos and other files): name, label, url, value, alt, description, cssName, schemes (scheme => URL). Since API 5 (1.3.0)
namedAsset(int $siteId, string $name) one of those by name (logo or asset:logo), or null. Since API 5 (1.3.0)
recordUsage(string $source, int $siteId, int $entryId, array $cells) int: rows written
forget(string $source, string $itemId) int: rows removed

ContentSource (interface): name(), available(), cells($siteId), cellsFor($siteId, $entryId), find($siteId, $reference), replace(CellKey $key, $from, $to).

CellKey: source, siteId, entryId, itemId, fieldId; validName(string), equals(CellKey).

SourceCell: key, value, description, editUrl.

Registrar: add(ContentSource): bool.

FieldOptions: siteId, mode, schemes, tiers, types, groups, explicit, default, display, hideDeprecated, problems, component (API 3); valid(), toArray().

PickerConfig: payload, inputName, label; value(), toArray().

The hook: variflow_content_sources, one argument, a Registrar.

The contract tests in full

ContentSourceContract, as Variflow runs it (PHPUnit 10 or later). Change the namespace to yours.

<?php

declare(strict_types=1);

namespace BisonDigital\Variflow\EE\Tests\Integration;

use BisonDigital\Variflow\EE\Integration\CellKey;
use BisonDigital\Variflow\EE\Integration\ContentSource;
use BisonDigital\Variflow\EE\Integration\SourceCell;
use PHPUnit\Framework\TestCase;

/**
 * The ContentSource contract, as tests. Variflow runs it against its own sources (channel,
 * Bloqs) and a fixture; copy it into your add-on's tests and extend it for yours:
 *
 *     final class NotesSourceTest extends ContentSourceContract
 *     {
 *         protected function source(): ContentSource
 *         {
 *             return new NotesSource(new InMemoryNotes([...]));   // fresh storage each time
 *         }
 *     }
 *
 * source() must return a source over fresh fixture storage (each test may write to it) holding,
 * on siteId(), at least two non-empty values, one of them in a channel entry (entry ID > 0) if
 * your content lives in entries. Only the ContentSource methods are used, so the tests don't
 * care how the source stores anything.
 */
abstract class ContentSourceContract extends TestCase
{
    /** A source over fresh fixture storage. */
    abstract protected function source(): ContentSource;

    /** The site the fixture content is on. */
    protected function siteId(): int
    {
        return 1;
    }

    /** @return list<SourceCell> */
    private function cells(ContentSource $source, ?int $site = null): array
    {
        $out = [];
        foreach ($source->cells($site ?? $this->siteId()) as $cell) {
            $out[] = $cell;
        }

        return $out;
    }

    /** A cell with a non-empty value. */
    private function sample(ContentSource $source): SourceCell
    {
        foreach ($this->cells($source) as $cell) {
            if (trim($cell->value) !== '') {
                return $cell;
            }
        }
        self::fail('The fixture needs at least one non-empty value on site ' . $this->siteId() . '.');
    }

    private static function id(CellKey $k): string
    {
        return implode('|', [$k->source, $k->siteId, $k->entryId, $k->itemId, $k->fieldId]);
    }

    /** @param iterable<SourceCell> $cells @return list<string> */
    private static function ids(iterable $cells): array
    {
        $out = [];
        foreach ($cells as $cell) {
            $out[] = self::id($cell->key);
        }
        sort($out);

        return $out;
    }

    public function testNameIsValidStableAndAvailable(): void
    {
        $source = $this->source();
        self::assertTrue(CellKey::validName($source->name()), 'lower case letters, digits and _, up to 32 characters');
        self::assertSame($source->name(), $source->name());
        self::assertTrue($source->available(), 'the fixture storage is there');
    }

    public function testCellsAreThisSourcesOnThisSite(): void
    {
        $source = $this->source();
        $cells = $this->cells($source);
        self::assertGreaterThanOrEqual(2, count(array_filter($cells, fn ($c) => $c instanceof SourceCell && trim($c->value) !== '')), 'the fixture holds two or more values');
        foreach ($cells as $cell) {
            self::assertInstanceOf(SourceCell::class, $cell);
            self::assertSame($source->name(), $cell->key->source);
            self::assertSame($this->siteId(), $cell->key->siteId);
            self::assertLessThanOrEqual(255, mb_strlen($cell->description), 'longer descriptions are cut');
        }
        foreach ($this->cells($source, $this->siteId() + 1000) as $cell) {
            self::assertSame($this->siteId() + 1000, $cell->key->siteId, 'another site\'s cells are that site\'s');
        }
    }

    public function testItemIdsAreStableAcrossReads(): void
    {
        $source = $this->source();
        self::assertSame(self::ids($this->cells($source)), self::ids($this->cells($source)));
    }

    public function testCellsForIsOneEntrysShare(): void
    {
        $source = $this->source();
        $cells = $this->cells($source);
        $entries = array_unique(array_map(fn (SourceCell $c) => $c->key->entryId, array_filter($cells, fn (SourceCell $c) => $c->key->entryId > 0)));
        foreach ($entries as $entryId) {
            $expected = self::ids(array_filter($cells, fn (SourceCell $c) => $c->key->entryId === $entryId));
            self::assertSame($expected, self::ids($source->cellsFor($this->siteId(), $entryId)), "entry {$entryId}");
        }
        self::assertSame([], self::ids($source->cellsFor($this->siteId(), 987654321)), 'an entry with no content');
    }

    public function testFindIsExactIgnoringWhitespace(): void
    {
        $source = $this->source();
        $value = trim($this->sample($source)->value);
        $expected = self::ids(array_filter($this->cells($source), fn (SourceCell $c) => trim($c->value) === $value));

        self::assertSame($expected, self::ids($source->find($this->siteId(), $value)));
        foreach ($source->find($this->siteId(), $value) as $cell) {
            self::assertSame($value, trim($cell->value));
        }
        self::assertSame([], self::ids($source->find($this->siteId(), $value . '-contract-nope')), 'never a prefix match');
        self::assertSame([], self::ids($source->find($this->siteId(), 'contract.no.such.token')));
    }

    public function testReplaceWritesOnlyWhereTheValueIsStillFrom(): void
    {
        $source = $this->source();
        $cell = $this->sample($source);
        $from = trim($cell->value);
        $id = self::id($cell->key);

        self::assertTrue($source->replace($cell->key, $from, 'contract.renamed'));
        self::assertContains($id, self::ids($source->find($this->siteId(), 'contract.renamed')), 'find() reads the storage, not a cache');
        self::assertNotContains($id, self::ids($source->find($this->siteId(), $from)));
        self::assertContains($id, self::ids($this->cells($source)), 'the same location keeps its key');

        self::assertFalse($source->replace($cell->key, $from, 'contract.other'), 'no longer the old value');
        self::assertTrue($source->replace($cell->key, 'contract.renamed', $from));
        self::assertContains($id, self::ids($source->find($this->siteId(), $from)), 'Undo puts it back');
    }

    public function testReplaceRefusesKeysItDoesntOwn(): void
    {
        $source = $this->source();
        $cell = $this->sample($source);
        $from = trim($cell->value);
        $k = $cell->key;
        $other = $source->name() === 'zz_contract_other' ? 'zz_contract_else' : 'zz_contract_other';

        self::assertFalse($source->replace(new CellKey($other, $k->siteId, $k->entryId, $k->itemId, $k->fieldId), $from, 'contract.x'), 'another source\'s key');
        self::assertFalse($source->replace(new CellKey($k->source, $k->siteId, $k->entryId, 'contract-missing-item', $k->fieldId), $from, 'contract.x'), 'a location that doesn\'t exist');
        self::assertContains(self::id($k), self::ids($source->find($this->siteId(), $from)), 'nothing changed');
    }

    public function testReplaceWithNothingClearsTheValue(): void
    {
        $source = $this->source();
        $cell = $this->sample($source);
        $from = trim($cell->value);

        self::assertTrue($source->replace($cell->key, $from, null));
        self::assertNotContains(self::id($cell->key), self::ids($source->find($this->siteId(), $from)));
        foreach ($this->cells($source) as $c) {
            if (self::id($c->key) === self::id($cell->key)) {
                self::assertSame('', trim($c->value), 'an empty value is no use of any token');
            }
        }
    }
}