Subtlyv0.1.1
Explore

Live playground

All demos below run the actual bundled package. Network requests are simulated locally. No external service or account required.

Menus & navigation

Submenus, keyboard menus, link preloading and returning to a previous list position.

Find a menu item by typing

typeahead()

Focus a destination, then type “p” to jump to Poland. Press “p” again to cycle to Portugal. Type “net” quickly to reach Netherlands. Arrow keys also work.

Live example

Focus a destination, then type its name.

<div id="your-component">
<div class="destination-list" role="toolbar" aria-label="Choose a destination"><button>Belgium</button><button>France</button><button>Netherlands</button><button>Poland</button><button>Portugal</button><button>Spain</button></div><p class="demo-status" role="status">Focus a destination, then type its name.</p>
</div>
import * as kit from 'subtly';

const el = document.querySelector('#your-component');
const listeners = new AbortController();
const { signal } = listeners;
const status = text => {
  el.querySelector('.demo-status').textContent = text;
};
// Local simulation only. Replace with your real data operation.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

function setup() {
  const list = el.querySelector('[role="toolbar"]');
          const focus = kit.rovingFocus(list, { selector: 'button', orientation: 'vertical' });
          const stop = kit.typeahead(list, { items: () => list.querySelectorAll('button') });
          list.addEventListener('focusin', event => status(event.target.textContent + ' focused'), { signal });
          list.addEventListener('click', event => {
            if (event.target.matches('button')) status(event.target.textContent + ' selected (demo)');
          }, { signal });
          return () => { stop(); focus.destroy(); };
}
const stop = setup();

// Call when this component is removed.
function cleanup() {
  listeners.abort();
  stop?.();
}

Implementation and API

Load a link when someone is likely to open it

intentPrefetch()

Hover or focus this documentation link for 120 ms. A same-origin prefetch hint is added. Your browser may skip the actual request when data saving or network conditions call for it.

Live example
Prefetch hint Not addedIntent delay 120 ms

Hover or focus the link.

<div id="your-component">
<nav class="prefetch-preview" aria-label="Prefetch demonstration"><span class="sample-label">Read next</span><a href="guide-vanilla.html" data-prefetch><strong>Use Subtly with vanilla JavaScript</strong><span>Learn how to initialize and clean up a component.</span></a></nav><div class="demo-metrics"><span>Prefetch hint <strong data-hint>Not added</strong></span><span>Intent delay <strong>120 ms</strong></span></div><p class="demo-status" role="status">Hover or focus the link.</p>
</div>
import * as kit from 'subtly';

const el = document.querySelector('#your-component');
const listeners = new AbortController();
const { signal } = listeners;
const status = text => {
  el.querySelector('.demo-status').textContent = text;
};
// Local simulation only. Replace with your real data operation.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

function setup() {
  const link = el.querySelector('a');
          const observer = new MutationObserver(() => {
            const added = [...document.head.querySelectorAll('link[rel="prefetch"]')]
              .some(hint => hint.href === link.href);
            if (added) {
              el.querySelector('[data-hint]').textContent = 'Added';
              status('Same-origin hint added. The browser decides whether to fetch.');
            }
          });
          observer.observe(document.head, { childList: true });
          const stop = kit.intentPrefetch(el.querySelector('nav'), { delay: 120 });
          return () => { stop(); observer.disconnect(); };
}
const stop = setup();

// Call when this component is removed.
function cleanup() {
  listeners.abort();
  stop?.();
}

Implementation and API

Hover & overlays

Hover previews, tooltips, popovers, outside clicks, scroll locking and dragging.

Open a preview after a deliberate hover

hoverIntent()

Move quickly across the project button, then rest on it. The project preview opens after 150 ms of deliberate hover. You can also focus or click the button.

Desktop check: The hover delay can only be checked with a desktop mouse or trackpad. Keyboard focus and click can also activate the example.

Live example

Preview closed. Hover, focus or click to open.

<div id="your-component">
<div class="preview-project">
          <button class="project-trigger" aria-expanded="false" aria-controls="project-preview">Website redesign <span class="muted">Project preview</span></button>
          <article id="project-preview" class="project-preview" hidden><span class="sample-art" aria-hidden="true"></span><strong>Website redesign</strong><p>A clearer home for your next release.</p><span class="tag">In progress</span></article>
        </div><p class="demo-status" role="status">Preview closed. Hover, focus or click to open.</p>
</div>
import * as kit from 'subtly';

const el = document.querySelector('#your-component');
const listeners = new AbortController();
const { signal } = listeners;
const status = text => {
  el.querySelector('.demo-status').textContent = text;
};
// Local simulation only. Replace with your real data operation.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

function setup() {
  const trigger = el.querySelector('button');
          const preview = el.querySelector('.project-preview');
          function show(open) {
            preview.hidden = !open;
            trigger.setAttribute('aria-expanded', String(open));
            status(open ? 'Project preview open' : 'Project preview closed');
          }
          const stop = kit.hoverIntent(trigger, {
            delay: 150,
            onEnter: () => show(true),
            onLeave: () => { if (document.activeElement !== trigger) show(false); }
          });
          trigger.addEventListener('focus', () => show(true), { signal });
          trigger.addEventListener('blur', () => show(false), { signal });
          trigger.addEventListener('click', () => show(true), { signal });
          trigger.addEventListener('keydown', event => {
            if (event.key === 'Escape') show(false);
          }, { signal });
          return stop;
}
const stop = setup();

// Call when this component is removed.
function cleanup() {
  listeners.abort();
  stop?.();
}

Implementation and API

Show hints on toolbar buttons

tooltipGroup()

Hover a formatting button. The first hint waits 500 ms; moving to a neighboring button shows its hint immediately. Keyboard focus always shows the hint immediately.

Desktop check: The hover timing can only be checked with a desktop mouse or trackpad. Keyboard focus can also reveal each toolbar hint.

Live example

Good writing starts with a small idea.

Hover or focus a formatting button.

<div id="your-component">
<div class="demo-toolbar" aria-label="Formatting actions">
          <span class="hint-wrap"><button aria-describedby="tip-bold">Bold</button><span id="tip-bold" role="tooltip" hidden>Make selected text bold</span></span>
          <span class="hint-wrap"><button aria-describedby="tip-italic">Italic</button><span id="tip-italic" role="tooltip" hidden>Emphasize selected text</span></span>
          <span class="hint-wrap"><button aria-describedby="tip-link">Link</button><span id="tip-link" role="tooltip" hidden>Insert a link</span></span>
        </div><p class="sample-document">Good writing starts with a small idea.</p><p class="demo-status" role="status">Hover or focus a formatting button.</p>
</div>
import * as kit from 'subtly';

const el = document.querySelector('#your-component');
const listeners = new AbortController();
const { signal } = listeners;
const status = text => {
  el.querySelector('.demo-status').textContent = text;
};
// Local simulation only. Replace with your real data operation.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

function setup() {
  const group = kit.tooltipGroup({ delay: 500, cooldown: 300 });
          for (const [key, wrapper] of [...el.querySelectorAll('.hint-wrap')].entries()) {
            const button = wrapper.querySelector('button');
            const tooltip = wrapper.querySelector('[role="tooltip"]');
            const hide = () => { tooltip.hidden = true; };
            const enter = immediate => group.enter(key, () => {
              tooltip.hidden = false;
              status(tooltip.textContent);
            }, hide, { immediate });
            button.addEventListener('pointerenter', e => {
              if (e.pointerType === 'mouse') enter(false);
            }, { signal });
            button.addEventListener('pointerleave', () => {
              if (document.activeElement !== button) group.leave(key);
            }, { signal });
            button.addEventListener('focus', () => enter(true), { signal });
            button.addEventListener('blur', () => group.leave(key), { signal });
            button.addEventListener('keydown', e => {
              if (e.key === 'Escape') group.leave(key);
            }, { signal });
            button.addEventListener('click', () => status(button.textContent + ' selected (demo)'), { signal });
          }
          return () => group.destroy();
}
const stop = setup();

// Call when this component is removed.
function cleanup() {
  listeners.abort();
  stop?.();
}

Implementation and API

Close a popover after an outside click

outsidePress()

Open the filters panel, change a checkbox, then click elsewhere. Inside interactions keep it open. Escape also closes the panel and returns focus to its trigger.

Live example

Filters closed.

<div id="your-component">
<button data-open aria-expanded="false" aria-controls="filters-panel">Filter projects</button><section id="filters-panel" class="filter-popover" hidden><strong>Show projects</strong><label class="check-label"><input type="checkbox" checked> In progress</label><label class="check-label"><input type="checkbox" checked> Planned</label><label class="check-label"><input type="checkbox"> Archived</label></section><p class="demo-status" role="status">Filters closed.</p>
</div>
import * as kit from 'subtly';

const el = document.querySelector('#your-component');
const listeners = new AbortController();
const { signal } = listeners;
const status = text => {
  el.querySelector('.demo-status').textContent = text;
};
// Local simulation only. Replace with your real data operation.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

function setup() {
  const trigger = el.querySelector('button');
          const panel = el.querySelector('section');
          function open(value) {
            panel.hidden = !value;
            trigger.setAttribute('aria-expanded', String(value));
            status(value ? 'Filters open. Interact inside or click elsewhere.' : 'Filters closed.');
          }
          trigger.addEventListener('click', () => open(panel.hidden), { signal });
          el.addEventListener('keydown', event => {
            if (event.key === 'Escape' && !panel.hidden) { open(false); trigger.focus(); }
          }, { signal });
          return kit.outsidePress(() => [trigger, panel], () => {
            if (!panel.hidden) open(false);
          });
}
const stop = setup();

// Call when this component is removed.
function cleanup() {
  listeners.abort();
  stop?.();
}

Implementation and API

Start dragging after clear movement

dragIntent()

Move the task handle slightly, then drag deliberately. Dragging starts after 8 px. Focus the same handle and use arrow keys to move it without dragging.

Live example

Move more than 8 px to start dragging.

<div id="your-component">
<div class="drag-track"><button class="drag-handle" aria-label="Move task card. Drag or use arrow keys."><span aria-hidden="true">⠿</span> Review design</button></div><p class="demo-status" role="status">Move more than 8 px to start dragging.</p>
</div>
import * as kit from 'subtly';

const el = document.querySelector('#your-component');
const listeners = new AbortController();
const { signal } = listeners;
const status = text => {
  el.querySelector('.demo-status').textContent = text;
};
// Local simulation only. Replace with your real data operation.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

function setup() {
  const handle = el.querySelector('button');
          let x = 0, y = 0, startX = 0, startY = 0;
          function move(nextX, nextY) {
            x = Math.max(-55, Math.min(55, nextX));
            y = Math.max(-35, Math.min(35, nextY));
            handle.style.transform = `translate(${x}px, ${y}px)`;
          }
          const stop = kit.dragIntent(handle, {
            threshold: 8,
            onStart() { startX = x; startY = y; status('Dragging the task.'); },
            onMove({ dx, dy }) { move(startX + dx, startY + dy); },
            onEnd() { status(`Task position: ${x}px across, ${y}px down.`); }
          });
          handle.addEventListener('keydown', event => {
            const delta = { ArrowLeft: [-5, 0], ArrowRight: [5, 0], ArrowUp: [0, -5], ArrowDown: [0, 5] }[event.key];
            if (!delta) return;
            event.preventDefault(); move(x + delta[0], y + delta[1]);
            status(`Task moved with keyboard: ${x}px across, ${y}px down.`);
          }, { signal });
          return stop;
}
const stop = setup();

// Call when this component is removed.
function cleanup() {
  listeners.abort();
  stop?.();
}

Implementation and API

Keep popovers inside the screen

floating()

Open the panel, change its preferred placement, then resize the browser or move the anchor close to an edge. The panel flips, shifts and shrinks to stay visible.

Live example

Panel closed

<div id="your-component">
<div class="floating-demo"><div class="floating-stage"><button class="floating-trigger" aria-haspopup="dialog" aria-expanded="false" aria-controls="floating-example-panel">Open anchored panel</button><section class="floating-panel" id="floating-example-panel" role="dialog" aria-label="Project actions" hidden><div class="floating-panel-heading"><strong>Project actions</strong><button class="floating-close" type="button" aria-label="Close panel">×</button></div><p>Save your work or invite someone to the project.</p><button type="button">Save changes</button><button type="button">Invite collaborator</button></section></div><label class="floating-placement">Preferred placement <select><option value="bottom-start">Bottom start</option><option value="top-start">Top start</option><option value="right-start">Right</option><option value="left-start">Left</option></select></label><p class="demo-status" aria-live="polite">Panel closed</p></div>
</div>
import { floating } from 'subtly/floating';

const el = document.querySelector('#your-component');
const listeners = new AbortController();
const { signal } = listeners;
const status = text => {
  el.querySelector('.demo-status').textContent = text;
};
// Local simulation only. Replace with your real data operation.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

function setup() {
  const trigger = el.querySelector('.floating-trigger');
  const panel = el.querySelector('.floating-panel');
  const placement = el.querySelector('select');
  const floatingReady=Promise.resolve({floating});
  let stop, closed = true;
  function close() {
    closed = true;
    stop?.(); stop = undefined;
    panel.hidden = true;
    trigger.setAttribute('aria-expanded', 'false');
    trigger.focus(); status('Panel closed');
  }
  function open() {
    closed = false;
    panel.hidden = false;
    trigger.setAttribute('aria-expanded', 'true');
    floatingReady.then(({ floating }) => {
      if (closed || signal.aborted) return;
      stop?.();
      stop = floating(trigger, panel, {
        placement: placement.value, gap: 8, padding: 12,
        onPlacement: value => status('Panel open · placed ' + value)
      });
    }).catch(() => status('The positioning module could not load.'));
  }
  trigger.addEventListener('click', () => panel.hidden ? open() : close(), { signal });
  el.querySelector('.floating-close').addEventListener('click', close, { signal });
  placement.addEventListener('change', () => { if (!panel.hidden) open(); }, { signal });
  el.addEventListener('keydown', event => {
    if (event.key === 'Escape' && !panel.hidden) close();
  }, { signal });
  return () => { closed = true; stop?.(); };
}
const stop = setup();

// Call when this component is removed.
function cleanup() {
  listeners.abort();
  stop?.();
}

Implementation and API

Stop the page moving behind a dialog

lockScroll()

Open the sample dialog and try scrolling the page behind it. Close the dialog to restore page scrolling. Escape also closes it.

Live example
Overlay behaviorKeep the page in place

Scroll the page a little before opening to check that its position is preserved.

A focused moment

The page behind this dialog is locked. The dialog uses native modal focus behavior.

Page scrolling is available.

<div id="your-component">
<div class="data-preview"><span class="muted">Overlay behavior</span><strong>Keep the page in place</strong><p>Scroll the page a little before opening to check that its position is preserved.</p></div><button data-open>Open sample dialog</button><dialog class="demo-dialog" aria-labelledby="scroll-dialog-title"><h3 id="scroll-dialog-title">A focused moment</h3><p>The page behind this dialog is locked. The dialog uses native modal focus behavior.</p><button data-close>Close dialog</button></dialog><p class="demo-status" role="status">Page scrolling is available.</p>
</div>
import * as kit from 'subtly';

const el = document.querySelector('#your-component');
const listeners = new AbortController();
const { signal } = listeners;
const status = text => {
  el.querySelector('.demo-status').textContent = text;
};
// Local simulation only. Replace with your real data operation.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

function setup() {
  const dialog = el.querySelector('dialog');
          let release;
          function unlock() {
            release?.(); release = undefined;
            status('Dialog closed. Page scrolling restored.');
          }
          el.querySelector('[data-open]').addEventListener('click', () => {
            release = kit.lockScroll();
            dialog.showModal();
            status('Dialog open. Page scrolling locked.');
          }, { signal });
          el.querySelector('[data-close]').addEventListener('click', () => dialog.close(), { signal });
          dialog.addEventListener('close', unlock, { signal });
          return () => { if (dialog.open) dialog.close(); unlock(); };
}
const stop = setup();

// Call when this component is removed.
function cleanup() {
  listeners.abort();
  stop?.();
}

Implementation and API

Forms & drafts

Field errors, input cleanup, draft recovery and unsaved-change warnings.

Show an error after someone edits a field

fieldValidation()

Enter “hello”, then move out of the email field. An error appears after blur. Correct it to “hello@example.com” and the error clears as you type.

Live example
Newsletter signup

A sample form. No email is sent.

Start typing, then leave the field.

<div id="your-component">
<form novalidate class="sample-form"><span class="sample-label">Newsletter signup</span><label>Email address<input type="email" required placeholder="you@example.com" aria-describedby="validation-hint validation-error" autocomplete="email"></label><p id="validation-hint" class="field-hint">A sample form. No email is sent.</p><p id="validation-error" class="field-error" aria-live="polite"></p><button type="submit">Subscribe</button></form><p class="demo-status" role="status">Start typing, then leave the field.</p>
</div>
import * as kit from 'subtly';

const el = document.querySelector('#your-component');
const listeners = new AbortController();
const { signal } = listeners;
const status = text => {
  el.querySelector('.demo-status').textContent = text;
};
// Local simulation only. Replace with your real data operation.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

function setup() {
  const form = el.querySelector('form');
          const input = el.querySelector('input');
          const error = el.querySelector('.field-error');
          const validation = kit.fieldValidation(input, {
            validate(value, field) {
              if (!value.trim()) return 'Enter your email address.';
              return field.validity.typeMismatch ? 'Use an email like you@example.com.' : '';
            },
            render(message, field) {
              error.textContent = message;
              field.setAttribute('aria-invalid', String(Boolean(message)));
            }
          });
          form.addEventListener('submit', event => {
            event.preventDefault();
            if (validation.check()) status('Email accepted in this local example. Nothing was sent.');
            else { input.focus(); status('Check your email address.'); }
          }, { signal });
          return () => validation.destroy();
}
const stop = setup();

// Call when this component is removed.
function cleanup() {
  listeners.abort();
  stop?.();
}

Implementation and API

Clean up common input formatting

normalize()

Choose a format, edit the sample value and normalize it. Compare the original with the output. Formatting cleanup does not verify that an address or phone number is valid.

Live example
Cleaned outputWaiting for input

Choose a format, then normalize.

<div id="your-component">
<label>Format<select><option value="whitespace">Whitespace</option><option value="email">Email</option><option value="phone">Phone</option></select></label><label>Original value<input value="  A small    idea  "></label><button>Normalize value</button><div class="data-preview"><span class="muted">Cleaned output</span><output data-output>Waiting for input</output></div><p class="demo-status" role="status">Choose a format, then normalize.</p>
</div>
import * as kit from 'subtly';

const el = document.querySelector('#your-component');
const listeners = new AbortController();
const { signal } = listeners;
const status = text => {
  el.querySelector('.demo-status').textContent = text;
};
// Local simulation only. Replace with your real data operation.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

function setup() {
  const input = el.querySelector('input');
          const format = el.querySelector('select');
          const samples = { whitespace: '  A small    idea  ', email: '  HELLO@EXAMPLE.COM  ', phone: '+31 (0) 6 1234 5678' };
          format.addEventListener('change', () => { input.value = samples[format.value]; }, { signal });
          el.querySelector('button').addEventListener('click', () => {
            el.querySelector('output').textContent = kit.normalize[format.value](input.value);
            status('Formatting cleaned. Validate this value separately before using it.');
          }, { signal });
}
const stop = setup();

// Call when this component is removed.
function cleanup() {
  listeners.abort();
  stop?.();
}

Implementation and API

Restore a form after an interruption

draftRecovery()

Write a sample project title and note, save the draft, then clear the editor. Restore brings your text back from this tab’s session storage. Delete draft removes the stored copy.

Live example
Project note

No changes saved in this example yet.

<div id="your-component">
<div class="sample-form"><span class="sample-label">Project note</span><label>Title<input name="title" placeholder="A new idea" autocomplete="off"></label><label>Note<textarea name="note" rows="3" placeholder="Use sample, non-sensitive text only."></textarea></label></div><div class="demo-row"><button data-save>Save draft</button><button data-empty>Clear editor</button><button data-load>Restore draft</button><button data-clear>Delete draft</button></div><p class="demo-status" role="status">No changes saved in this example yet.</p>
</div>
import * as kit from 'subtly';

const el = document.querySelector('#your-component');
const listeners = new AbortController();
const { signal } = listeners;
const status = text => {
  el.querySelector('.demo-status').textContent = text;
};
// Local simulation only. Replace with your real data operation.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

function setup() {
  const draft = kit.draftRecovery('docs:project-note:v2', {
            fields: ['title', 'note'], version: 1
          });
          const title = el.querySelector('[name="title"]');
          const note = el.querySelector('[name="note"]');
          el.querySelector('[data-save]').addEventListener('click', () => {
            draft.save({ title: title.value, note: note.value });
            draft.flush();
            status(draft.load() ? 'Draft saved in this tab.' : 'Storage unavailable. Draft could not be saved.');
          }, { signal });
          el.querySelector('[data-empty]').addEventListener('click', () => {
            title.value = ''; note.value = '';
            status('Editor cleared. Your saved draft is still available.');
          }, { signal });
          el.querySelector('[data-load]').addEventListener('click', () => {
            const value = draft.load();
            if (value) { title.value = value.title; note.value = value.note; }
            status(value ? 'Saved draft restored.' : 'No saved draft. Save one first.');
          }, { signal });
          el.querySelector('[data-clear]').addEventListener('click', () => {
            draft.clear(); status('Stored draft deleted. Editor text is unchanged.');
          }, { signal });
          return () => draft.destroy();
}
const stop = setup();

// Call when this component is removed.
function cleanup() {
  listeners.abort();
  stop?.();
}

Implementation and API

Move to the first invalid field

focusInvalid()

Submit the empty project form. Focus moves to the first missing field. Fill the title, submit again and focus moves to the email field.

Live example

Both fields are required. Nothing is submitted.

<div id="your-component">
<form novalidate class="sample-form"><label>Project title<input name="title" required aria-describedby="project-title-error"></label><p class="field-error" id="project-title-error"></p><label>Contact email<input name="email" type="email" required aria-describedby="project-email-error"></label><p class="field-error" id="project-email-error"></p><button type="submit">Create sample project</button></form><p class="demo-status" role="status">Both fields are required. Nothing is submitted.</p>
</div>
import * as kit from 'subtly';

const el = document.querySelector('#your-component');
const listeners = new AbortController();
const { signal } = listeners;
const status = text => {
  el.querySelector('.demo-status').textContent = text;
};
// Local simulation only. Replace with your real data operation.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

function setup() {
  const form = el.querySelector('form');
          form.addEventListener('submit', event => {
            event.preventDefault();
            for (const field of form.querySelectorAll('input')) {
              const invalid = !field.validity.valid;
              field.setAttribute('aria-invalid', String(invalid));
              const error = el.querySelector('#' + field.getAttribute('aria-describedby'));
              error.textContent = invalid ? (field.validity.valueMissing ? 'Complete this field.' : 'Enter a valid email address.') : '';
            }
            if (!form.checkValidity()) {
              kit.focusInvalid(form); status('Focus moved to the first field that needs attention.');
            } else status('Sample project is valid. No data was submitted.');
          }, { signal });
}
const stop = setup();

// Call when this component is removed.
function cleanup() {
  listeners.abort();
  stop?.();
}

Implementation and API

Warn before leaving unsaved edits

unsavedChanges()

Edit the project note to enable the guard, then save to disable it. After editing, you can use the test link to try leaving. Your browser chooses whether to show a confirmation.

Live example
All changes saved
Test leaving this page

The navigation guard is off.

<div id="your-component">
<label>Project note<textarea rows="3" placeholder="Write a sample note…"></textarea></label><div class="editor-state"><span data-state>All changes saved</span><button data-save>Save note</button></div><a class="text-link" href="install.html">Test leaving this page</a><p class="demo-status" role="status">The navigation guard is off.</p>
</div>
import * as kit from 'subtly';

const el = document.querySelector('#your-component');
const listeners = new AbortController();
const { signal } = listeners;
const status = text => {
  el.querySelector('.demo-status').textContent = text;
};
// Local simulation only. Replace with your real data operation.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

function setup() {
  const guard = kit.unsavedChanges();
          const note = el.querySelector('textarea');
          const state = el.querySelector('[data-state]');
          let saved = note.value;
          function update() {
            const dirty = note.value !== saved;
            guard.set(dirty);
            state.textContent = dirty ? 'Unsaved changes' : 'All changes saved';
            state.dataset.dirty = String(dirty);
            status(dirty ? 'Guard enabled. Try the test link or save first.' : 'The navigation guard is off.');
          }
          note.addEventListener('input', update, { signal });
          el.querySelector('[data-save]').addEventListener('click', () => {
            // In production, update the baseline only after a successful server save.
            saved = note.value; update(); status('Note saved locally for this demonstration.');
          }, { signal });
          return () => guard.destroy();
}
const stop = setup();

// Call when this component is removed.
function cleanup() {
  listeners.abort();
  stop?.();
}

Implementation and API

Search & loading

Responsive search, current results, useful loading states and deferred content.

Search after typing pauses

debounce()

Search this local reading list. Type “design” and watch the list update after you stop typing for 300 ms. The counter shows how much filtering actually ran.

Live example
  • Designing a useful empty state
  • Accessible menus from the start
  • Small details in product design
  • A guide to loading feedback

4 articles · 0 filter runs

<div id="your-component">
<label>Find an article<input type="search" placeholder="Try design or accessibility" autocomplete="off"></label>
        <ul class="result-list"><li>Designing a useful empty state</li><li>Accessible menus from the start</li><li>Small details in product design</li><li>A guide to loading feedback</li></ul>
        <p class="demo-status" role="status">4 articles · 0 filter runs</p>
</div>
import * as kit from 'subtly';

const el = document.querySelector('#your-component');
const listeners = new AbortController();
const { signal } = listeners;
const status = text => {
  el.querySelector('.demo-status').textContent = text;
};
// Local simulation only. Replace with your real data operation.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

function setup() {
  const input = el.querySelector('input');
          const articles = [...el.querySelectorAll('li')];
          let runs = 0;
          const filter = kit.debounce(query => {
            runs++;
            for (const article of articles) {
              article.hidden = !article.textContent.toLowerCase().includes(query.toLowerCase());
            }
            const count = articles.filter(article => !article.hidden).length;
            status(`${count} articles · ${runs} filter runs`);
          }, 300);
          input.addEventListener('input', () => filter(input.value), { signal });
          return () => filter.cancel();
}
const stop = setup();

// Call when this component is removed.
function cleanup() {
  listeners.abort();
  stop?.();
}

Implementation and API

Ignore outdated search responses

latestRequest()

Load Design, then immediately load Engineering. Design is deliberately slower. Only the most recently requested team can appear, even when the earlier request finishes later.

Live example
Selected teamNo team loaded

Older results will never replace your latest selection.

Choose a team.

<div id="your-component">
<div class="demo-row"><button data-team="Design" data-ms="1400">Load Design · slow</button><button data-team="Engineering" data-ms="200">Load Engineering · fast</button></div>
        <div class="data-preview" aria-busy="false"><span class="muted">Selected team</span><strong data-result>No team loaded</strong><p>Older results will never replace your latest selection.</p></div><p class="demo-status" role="status">Choose a team.</p>
</div>
import * as kit from 'subtly';

const el = document.querySelector('#your-component');
const listeners = new AbortController();
const { signal } = listeners;
const status = text => {
  el.querySelector('.demo-status').textContent = text;
};
// Local simulation only. Replace with your real data operation.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

function setup() {
  const panel = el.querySelector('.data-preview');
          const request = kit.latestRequest(async (_signal, team, delay) => {
            // This mock deliberately ignores cancellation to demonstrate race protection.
            await wait(delay);
            return team;
          });
          for (const button of el.querySelectorAll('button')) {
            button.addEventListener('click', async () => {
              panel.setAttribute('aria-busy', 'true');
              status('Loading ' + button.dataset.team + '…');
              const result = await request.run(button.dataset.team, Number(button.dataset.ms));
              if (signal.aborted || result.status === 'stale') return;
              panel.setAttribute('aria-busy', 'false');
              if (result.status === 'success') {
                el.querySelector('[data-result]').textContent = result.value;
                status(result.value + ' loaded. Earlier responses are ignored.');
              } else status('Could not load this team. Try again.');
            }, { signal });
          }
          return () => request.destroy();
}
const stop = setup();

// Call when this component is removed.
function cleanup() {
  listeners.abort();
  stop?.();
}

Implementation and API

Prevent repeat submissions while saving

singleFlight()

Click Save preferences several times during the one-second request. The button stays available so you can test repeated input, but the request counter increases only once.

Live example
Newsletter preferencesProduct updates, once a month

Repeated clicks share one pending save.

Requests started 0Save state Idle

Ready to save.

<div id="your-component">
<div class="data-preview"><span class="muted">Newsletter preferences</span><strong>Product updates, once a month</strong><p>Repeated clicks share one pending save.</p></div><button>Save preferences</button><div class="demo-metrics"><span>Requests started <strong data-count>0</strong></span><span>Save state <strong data-state>Idle</strong></span></div><p class="demo-status" role="status">Ready to save.</p>
</div>
import * as kit from 'subtly';

const el = document.querySelector('#your-component');
const listeners = new AbortController();
const { signal } = listeners;
const status = text => {
  el.querySelector('.demo-status').textContent = text;
};
// Local simulation only. Replace with your real data operation.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

function setup() {
  let calls = 0;
          const state = el.querySelector('[data-state]');
          const save = kit.singleFlight(async () => {
            el.querySelector('[data-count]').textContent = String(++calls);
            state.textContent = 'Saving';
            await wait(1000); // Replace with your authenticated request.
          });
          el.querySelector('button').addEventListener('click', async () => {
            try {
              const result = await save.run();
              if (signal.aborted) return;
              if (result.status === 'busy') { status('The existing save is still running.'); return; }
              state.textContent = 'Saved';
              status('Preferences saved. Only one request ran at a time.');
            } catch {
              state.textContent = 'Failed';
              status('Save failed. Please try again.');
            }
          }, { signal });
}
const stop = setup();

// Call when this component is removed.
function cleanup() {
  listeners.abort();
  stop?.();
}

Implementation and API

Avoid flashes from very short loading states

loadingIndicator()

Load the report with a fast or slow connection. Both requests show a busy state immediately, but only the longer request displays the spinner after 200 ms.

Live example
Activity report

Choose a request speed.

<div id="your-component">
<div class="demo-row"><button data-ms="100">Fast request · 100 ms</button><button data-ms="900">Slow request · 900 ms</button></div><div class="data-preview report-preview" aria-busy="false"><div class="report-heading"><strong>Activity report</strong><span class="spinner" hidden aria-hidden="true"></span></div><div class="report-bars" aria-hidden="true"><i></i><i></i><i></i><i></i><i></i><i></i><i></i></div></div><p class="demo-status" role="status">Choose a request speed.</p>
</div>
import * as kit from 'subtly';

const el = document.querySelector('#your-component');
const listeners = new AbortController();
const { signal } = listeners;
const status = text => {
  el.querySelector('.demo-status').textContent = text;
};
// Local simulation only. Replace with your real data operation.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

function setup() {
  const report = el.querySelector('.report-preview');
          const buttons = [...el.querySelectorAll('button')];
          const loader = kit.loadingIndicator(visible => {
            el.querySelector('.spinner').hidden = !visible;
          }, { delay: 200, minVisible: 300 });
          for (const button of buttons) button.addEventListener('click', async () => {
            buttons.forEach(button => { button.disabled = true; });
            report.setAttribute('aria-busy', 'true');
            status('Loading report…');
            loader.start();
            await wait(Number(button.dataset.ms));
            if (signal.aborted) return;
            loader.stop();
            report.setAttribute('aria-busy', 'false');
            buttons.forEach(button => { button.disabled = false; });
            status('Report loaded in ' + button.dataset.ms + ' ms.');
          }, { signal });
          return () => loader.destroy();
}
const stop = setup();

// Call when this component is removed.
function cleanup() {
  listeners.abort();
  stop?.();
}

Implementation and API

Show previous results while refreshing

staleCache()

Load the project summary twice within two seconds. The second read uses the cache. Wait longer and load again: the previous version appears while a fresh one is requested.

Live example
Project summaryNo summary loaded

Cache is empty.

Server reads 0Cache lifetime 2 seconds

Ready to load.

<div id="your-component">
<div class="data-preview"><span class="muted">Project summary</span><strong data-value>No summary loaded</strong><p data-freshness>Cache is empty.</p></div><button>Load project summary</button><div class="demo-metrics"><span>Server reads <strong data-count>0</strong></span><span>Cache lifetime <strong>2 seconds</strong></span></div><p class="demo-status" role="status">Ready to load.</p>
</div>
import * as kit from 'subtly';

const el = document.querySelector('#your-component');
const listeners = new AbortController();
const { signal } = listeners;
const status = text => {
  el.querySelector('.demo-status').textContent = text;
};
// Local simulation only. Replace with your real data operation.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

function setup() {
  const cache = kit.staleCache({ ttl: 2000 });
          let calls = 0;
          el.querySelector('button').addEventListener('click', async () => {
            status('Reading project summary…');
            try {
              await cache.read('project-summary', async () => {
                el.querySelector('[data-count]').textContent = String(++calls);
                await wait(800);
                return 'Website redesign · version ' + calls;
              }, (value, meta) => {
                el.querySelector('[data-value]').textContent = value;
                el.querySelector('[data-freshness]').textContent = meta.stale ? 'Cached copy visible. Refreshing…' : 'Current copy. Available from cache for 2 seconds.';
                status(meta.stale ? 'Showing previous data while a new version loads.' : 'Summary ready.');
              });
            } catch { status('Could not refresh. Try again.'); }
          }, { signal });
          return () => cache.clear();
}
const stop = setup();

// Call when this component is removed.
function cleanup() {
  listeners.abort();
  stop?.();
}

Implementation and API

Load content as it nears the screen

nearViewport()

Scroll inside the panel until the deferred report comes into view. It initializes once, when it reaches the visible area. The rest of the page stays usable throughout.

Live example
Project overview

Keep scrolling inside this panel to load the secondary report.

Report not initialized

Waiting for the report to enter view.

<div id="your-component">
<div class="deferred-scroll" tabindex="0" role="region" aria-label="Scroll to reveal the deferred report"><div class="deferred-intro"><strong>Project overview</strong><p>Keep scrolling inside this panel to load the secondary report.</p><span class="scroll-cue" aria-hidden="true">⋮</span></div><div data-deferred class="data-preview"><strong data-title>Report not initialized</strong><div class="report-bars" aria-hidden="true" hidden><i></i><i></i><i></i><i></i><i></i></div></div></div><p class="demo-status" role="status">Waiting for the report to enter view.</p>
</div>
import * as kit from 'subtly';

const el = document.querySelector('#your-component');
const listeners = new AbortController();
const { signal } = listeners;
const status = text => {
  el.querySelector('.demo-status').textContent = text;
};
// Local simulation only. Replace with your real data operation.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

function setup() {
  return kit.nearViewport(el.querySelector('[data-deferred]'), () => {
            el.querySelector('[data-title]').textContent = 'Report initialized';
            el.querySelector('.report-bars').hidden = false;
            status('Report initialized once when it entered the visible region.');
          }, { rootMargin: '0px' });
}
const stop = setup();

// Call when this component is removed.
function cleanup() {
  listeners.abort();
  stop?.();
}

Implementation and API

Feedback & undo

Instant updates, undo windows and screen-reader announcements.

Show a change before the server replies

optimistic()

Save this article. Its appearance changes immediately, before the simulated server confirms. Turn on “Simulate a failed save” to see the previous state restored.

Live example
5 minute readDesigning for the in-between

The details between an action and its result.

Article is not saved.

<div id="your-component">
<article class="article-preview"><span class="sample-art" aria-hidden="true"></span><div><span class="muted">5 minute read</span><strong>Designing for the in-between</strong><p>The details between an action and its result.</p></div><button aria-pressed="false">Save article</button></article><label class="check-label"><input type="checkbox"> Simulate a failed save</label><p class="demo-status" role="status">Article is not saved.</p>
</div>
import * as kit from 'subtly';

const el = document.querySelector('#your-component');
const listeners = new AbortController();
const { signal } = listeners;
const status = text => {
  el.querySelector('.demo-status').textContent = text;
};
// Local simulation only. Replace with your real data operation.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

function setup() {
  let saved = false;
          const button = el.querySelector('button');
          const task = kit.optimistic({
            read: () => saved,
            write(value) {
              saved = value;
              button.textContent = value ? 'Article saved' : 'Save article';
              button.setAttribute('aria-pressed', String(value));
            },
            async request() {
              await wait(900);
              if (el.querySelector('input').checked) throw new Error('Simulated failure');
            },
            onError: () => status('Save failed. The previous article state was restored.')
          });
          button.addEventListener('click', async () => {
            if (task.busy) return;
            status('Saving in the background…');
            button.disabled = true;
            const result = await task.run(!saved);
            if (signal.aborted) return;
            button.disabled = false;
            if (result.status === 'success') status(saved ? 'Saved and confirmed.' : 'Removed from saved articles.');
          }, { signal });
}
const stop = setup();

// Call when this component is removed.
function cleanup() {
  listeners.abort();
  stop?.();
}

Implementation and API

Let someone undo a recent change

undoAction()

Archive the sample task. It disappears immediately and you have five seconds to undo. The final commit here only updates this local demo.

Live example
Review the landing pageDesign · Today
To do

One task in your list.

<div id="your-component">
<div class="task-preview" data-item><span class="task-checkbox" aria-hidden="true"></span><div><strong>Review the landing page</strong><small>Design · Today</small></div><span class="tag">To do</span></div><div class="empty-task" hidden>Task archived.</div><div class="demo-row"><button data-remove>Archive task</button><button data-undo disabled>Undo archive</button><button data-reset hidden>Reset example</button></div><p class="demo-status" role="status">One task in your list.</p>
</div>
import * as kit from 'subtly';

const el = document.querySelector('#your-component');
const listeners = new AbortController();
const { signal } = listeners;
const status = text => {
  el.querySelector('.demo-status').textContent = text;
};
// Local simulation only. Replace with your real data operation.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

function setup() {
  let action;
          const item = el.querySelector('[data-item]');
          const empty = el.querySelector('.empty-task');
          const remove = el.querySelector('[data-remove]');
          const undo = el.querySelector('[data-undo]');
          const reset = el.querySelector('[data-reset]');
          function restore() {
            item.hidden = false; empty.hidden = true;
            remove.disabled = false; undo.disabled = true; reset.hidden = true;
            status('Task restored.');
          }
          remove.addEventListener('click', () => {
            action = kit.undoAction({
              duration: 5000,
              apply() {
                item.hidden = true; empty.hidden = false;
                remove.disabled = true; undo.disabled = false;
                status('Task archived. You have 5 seconds to undo.');
              },
              revert: restore,
              commit() {
                undo.disabled = true; reset.hidden = false;
                status('Archive confirmed in this demo.');
              }
            });
            action.start(() => status('Could not archive. Task restored.'));
          }, { signal });
          undo.addEventListener('click', () => action?.undo(), { signal });
          reset.addEventListener('click', restore, { signal });
          return () => action?.destroy();
}
const stop = setup();

// Call when this component is removed.
function cleanup() {
  listeners.abort();
  stop?.();
}

Implementation and API

Read updates aloud to screen readers

liveAnnouncer()

Add a sample item to the basket. The count updates visually and the same useful update is announced politely to a screen reader without moving your focus.

Live example
Sample productEveryday notebook

Illustrative basket. No purchase is made.

Basket 0 items
<div id="your-component">
<div class="article-preview"><span class="sample-art" aria-hidden="true"></span><div><span class="muted">Sample product</span><strong>Everyday notebook</strong><p>Illustrative basket. No purchase is made.</p></div><button>Add to basket</button></div><div class="basket-count">Basket <strong data-count>0 items</strong></div><p class="demo-status" aria-hidden="true">Ready to add an item.</p>
</div>
import * as kit from 'subtly';

const el = document.querySelector('#your-component');
const listeners = new AbortController();
const { signal } = listeners;
const status = text => {
  el.querySelector('.demo-status').textContent = text;
};
// Local simulation only. Replace with your real data operation.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

function setup() {
  const announcer = kit.liveAnnouncer({ parent: el });
          let count = 0;
          el.querySelector('button').addEventListener('click', () => {
            count++;
            const message = `Notebook added. Basket contains ${count} ${count === 1 ? 'item' : 'items'}.`;
            el.querySelector('[data-count]').textContent = count + (count === 1 ? ' item' : ' items');
            status(message);
            announcer.announce(message);
          }, { signal });
          return () => announcer.destroy();
}
const stop = setup();

// Call when this component is removed.
function cleanup() {
  listeners.abort();
  stop?.();
}

Implementation and API

Keyboard & motion

Keyboard focus, input type and motion preferences.

Move through a toolbar with arrow keys

rovingFocus()

Tab into the text alignment toolbar once, then use Left, Right, Home or End to move between controls. Activate a button to update the sample text.

Live example

Small details make a familiar interface feel easier to use.

Left alignment. Tab into the toolbar to begin.

<div id="your-component">
<div class="demo-toolbar" role="toolbar" aria-label="Text alignment" data-ix="roving-focus" data-ix-orientation="horizontal"><button data-align="left" data-ix-roving-item aria-pressed="true">Left</button><button data-align="center" data-ix-roving-item aria-pressed="false">Center</button><button data-align="right" data-ix-roving-item aria-pressed="false">Right</button></div><p class="sample-document" data-document>Small details make a familiar interface feel easier to use.</p><p class="demo-status" role="status">Left alignment. Tab into the toolbar to begin.</p>
</div>
import * as kit from 'subtly';
// Start once at application level.
const interactions = kit.createInteractions();
interactions.start();

const el = document.querySelector('#your-component');
const listeners = new AbortController();
const { signal } = listeners;
const status = text => {
  el.querySelector('.demo-status').textContent = text;
};
// Local simulation only. Replace with your real data operation.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

function setup() {
  const buttons = [...el.querySelectorAll('[data-align]')];
          for (const button of buttons) button.addEventListener('click', () => {
            for (const item of buttons) item.setAttribute('aria-pressed', String(item === button));
            el.querySelector('[data-document]').style.textAlign = button.dataset.align;
            status(button.textContent + ' alignment selected.');
          }, { signal });
          // data-ix="roving-focus" is initialized by createInteractions().
}
const stop = setup();

// Call when this component is removed.
function cleanup() {
  listeners.abort();
  stop?.();
  interactions.stop();
}

Implementation and API

Return focus to the dialog opener

captureFocus()

Open the project settings dialog and close it with its button or Escape. Notice the focus ring returning to the control that opened it.

Live example
Project settingsWebsite redesign

Open the dialog using the keyboard to follow the focus ring.

Project settings

This native dialog manages its own modal focus.

Ready. Focus will return to the opener.

<div id="your-component">
<div class="data-preview"><span class="muted">Project settings</span><strong>Website redesign</strong><p>Open the dialog using the keyboard to follow the focus ring.</p></div><button data-open>Open project settings</button><dialog class="demo-dialog" aria-labelledby="project-settings-title"><h3 id="project-settings-title">Project settings</h3><p>This native dialog manages its own modal focus.</p><label>Display name<input value="Website redesign"></label><button data-close>Close settings</button></dialog><p class="demo-status" role="status">Ready. Focus will return to the opener.</p>
</div>
import * as kit from 'subtly';

const el = document.querySelector('#your-component');
const listeners = new AbortController();
const { signal } = listeners;
const status = text => {
  el.querySelector('.demo-status').textContent = text;
};
// Local simulation only. Replace with your real data operation.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

function setup() {
  const dialog = el.querySelector('dialog');
          let restore;
          el.querySelector('[data-open]').addEventListener('click', () => {
            restore = kit.captureFocus();
            dialog.showModal();
          }, { signal });
          el.querySelector('[data-close]').addEventListener('click', () => dialog.close(), { signal });
          dialog.addEventListener('close', () => {
            restore?.(); status('Dialog closed. Focus returned to Open project settings.');
          }, { signal });
          return () => { if (dialog.open) dialog.close(); };
}
const stop = setup();

// Call when this component is removed.
function cleanup() {
  listeners.abort();
  stop?.();
}

Implementation and API

Detect keyboard, mouse or touch input

inputModality()

Click or tap the sample button, then press Tab. The input card reflects the latest input type. Use this to adapt focus presentation without hiding useful feedback.

Live example
Waiting for inputMost recent input method

Click, tap or press a key.

<div id="your-component">
<div class="input-device" data-device="unknown"><span class="device-symbol" aria-hidden="true">⌘</span><strong data-value>Waiting for input</strong><span class="muted">Most recent input method</span></div><button>Try pointer or keyboard input</button><p class="demo-status" role="status">Click, tap or press a key.</p>
</div>
import * as kit from 'subtly';

const el = document.querySelector('#your-component');
const listeners = new AbortController();
const { signal } = listeners;
const status = text => {
  el.querySelector('.demo-status').textContent = text;
};
// Local simulation only. Replace with your real data operation.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

function setup() {
  const card = el.querySelector('.input-device');
          const modality = kit.inputModality(value => {
            card.dataset.device = value;
            el.querySelector('[data-value]').textContent = value;
            status('Latest input: ' + value);
          });
          el.querySelector('button').addEventListener('click', () => status('Activated using ' + modality.current), { signal });
          return () => modality.destroy();
}
const stop = setup();

// Call when this component is removed.
function cleanup() {
  listeners.abort();
  stop?.();
}

Implementation and API

Follow the reduced-motion setting

motionPreference()

Play the sample transition. Its duration follows your system’s reduced-motion setting. Change that setting to see the value update while this page stays open.

Live example
System preference CheckingAnimation duration Checking

Follows your system setting.

<div id="your-component">
<div class="motion-stage"><span class="motion-dot"></span></div><div class="demo-metrics"><span>System preference <strong data-preference>Checking</strong></span><span>Animation duration <strong data-duration>Checking</strong></span></div><button>Play transition</button><p class="demo-status" role="status">Follows your system setting.</p>
</div>
import * as kit from 'subtly';

const el = document.querySelector('#your-component');
const listeners = new AbortController();
const { signal } = listeners;
const status = text => {
  el.querySelector('.demo-status').textContent = text;
};
// Local simulation only. Replace with your real data operation.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

function setup() {
  const preference = kit.motionPreference(update);
          function update(reduced) {
            el.querySelector('[data-preference]').textContent = reduced ? 'Reduced motion' : 'Standard motion';
            el.querySelector('[data-duration]').textContent = reduced ? '0 ms' : '600 ms';
          }
          update(preference.reduced);
          let animation;
          el.querySelector('button').addEventListener('click', () => {
            animation?.cancel();
            animation = el.querySelector('.motion-dot').animate(
              [{ transform: 'translateX(0)' }, { transform: 'translateX(100px)' }],
              { duration: preference.duration(600), fill: 'forwards' }
            );
            status(preference.reduced ? 'Position updated without animation.' : 'Transition played over 600 ms.');
          }, { signal });
          return () => { animation?.cancel(); preference.destroy(); };
}
const stop = setup();

// Call when this component is removed.
function cleanup() {
  listeners.abort();
  stop?.();
}

Implementation and API

Let an animation reverse smoothly

interruptibleMotion()

Expand the details, then collapse them before the transition finishes. The visual reverses from its current position instead of jumping back or queuing animations.

Live example

Collapsed. Try toggling quickly.

<div id="your-component">
<div class="motion-stage"><div class="motion-box"></div></div><button aria-pressed="false">Expand bar</button><p class="demo-status" role="status">Collapsed. Try toggling quickly.</p>
</div>
import * as kit from 'subtly';

const el = document.querySelector('#your-component');
const listeners = new AbortController();
const { signal } = listeners;
const status = text => {
  el.querySelector('.demo-status').textContent = text;
};
// Local simulation only. Replace with your real data operation.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

function setup() {
  const motion = kit.interruptibleMotion(el.querySelector('.motion-box'));
          const button = el.querySelector('button');
          let expanded = false;
          button.addEventListener('click', () => {
            expanded = !expanded;
            button.textContent = expanded ? 'Collapse bar' : 'Expand bar';
            button.setAttribute('aria-pressed', String(expanded));
            motion.to({ width: expanded ? '100%' : '25%' }, { duration: 700 });
            status(expanded ? 'Expanding from the current width.' : 'Collapsing from the current width.');
          }, { signal });
          return () => motion.destroy();
}
const stop = setup();

// Call when this component is removed.
function cleanup() {
  listeners.abort();
  stop?.();
}

Implementation and API

Search Subtly documentation

Popular pages
↑↓ to navigate↵ to openESC to close