Subtlyv0.1.1
Feedback & undo

optimistic()

Show a change before the server replies. Low-risk reversible updates.

Available in v0.1.1optimistic.jsFeedback

Try it

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?.();
}

Add it to your project

  1. Copy the HTML. Use the HTML tab above and place the markup inside a dedicated component root. Layout classes belong to this documentation website; use your own styles.
  2. Connect the behavior. Copy the JavaScript tab, update #your-component and initialize it after the elements exist. Replace simulated operations with your own data.
  3. Clean up on unmount. Call the example’s cleanup() when the component is removed. It aborts application listeners and releases the utility’s timers or observers.

The preview and JavaScript tab use the same utility wiring. status() writes plain text into the example’s status element. wait() is a simulated local delay. For examples with data-ix attributes, start the declarative runtime once at application level, as shown in the code. Use your framework guide to place setup and cleanup correctly.

API and lifecycle

Supply read(), write(next), request(next) and optional onError. run(next) snapshots the current UI value, applies the new value immediately, then confirms with the request. The request must reject on server failure.

Interface
read, write, request, onError; run(next), busy.
Lifecycle
Only one mutation runs per instance; further activations return busy. On failure, the previous snapshot is written back and the result reports error. Keep snapshots immutable.

Accessibility and safety

Implementation notes

Never optimistically confirm payments, booking, admission or permissions. Server remains authoritative.

Use only for reversible, low-risk changes. Do not optimistically confirm payments, admission, bookings or permissions; the server remains authoritative.

What to check

Test a successful save, a rejected request and repeated activation while busy. Confirm rollback restores both the visual state and accessible state.

View documented module source
/** One in-flight optimistic mutation per instance. Use for reversible, low-risk actions.
 * read/write operate on your UI state; request must reject on server failure.
 * Treat snapshots as immutable. Do not use for payments or ticket admission. */
export function optimistic({read,write,request,onError}){
    let busy=false;
    return {get busy(){return busy;},async run(next){if(busy)return {status:'busy'};busy=true;let previous,applied=false;try{previous=read();write(next);applied=true;const result=await request(next);return {status:'success',result};}catch(error){if(applied)write(previous);onError?.(error);return {status:'error',error};}finally{busy=false;}}};
}

Search Subtly documentation

Popular pages
↑↓ to navigate↵ to openESC to close