Subtlyv0.1.1
Menus & navigation

navigationMemory()

Restore a list and its scroll position. Restore lists, filters, scroll.

Available in v0.1.1navigation.jsNavigation

Try it

Scroll the project list and save your position. Scroll somewhere else, then restore. The saved position is held in memory for this page only.

Live example
Project 01Design review
Project 02Design review
Project 03Design review
Project 04Design review
Project 05Design review
Project 06Design review
Project 07Design review
Project 08Design review
Project 09Design review
Project 10Design review
Project 11Design review
Project 12Design review
Project 13Design review
Project 14Design review
Project 15Design review

Scroll the list to begin.

<div id="your-component">
<div class="list-demo" tabindex="0" role="region" aria-label="Scrollable project list"><div><span class="task-checkbox" aria-hidden="true"></span><span>Project 01</span><span class="muted">Design review</span></div><div><span class="task-checkbox" aria-hidden="true"></span><span>Project 02</span><span class="muted">Design review</span></div><div><span class="task-checkbox" aria-hidden="true"></span><span>Project 03</span><span class="muted">Design review</span></div><div><span class="task-checkbox" aria-hidden="true"></span><span>Project 04</span><span class="muted">Design review</span></div><div><span class="task-checkbox" aria-hidden="true"></span><span>Project 05</span><span class="muted">Design review</span></div><div><span class="task-checkbox" aria-hidden="true"></span><span>Project 06</span><span class="muted">Design review</span></div><div><span class="task-checkbox" aria-hidden="true"></span><span>Project 07</span><span class="muted">Design review</span></div><div><span class="task-checkbox" aria-hidden="true"></span><span>Project 08</span><span class="muted">Design review</span></div><div><span class="task-checkbox" aria-hidden="true"></span><span>Project 09</span><span class="muted">Design review</span></div><div><span class="task-checkbox" aria-hidden="true"></span><span>Project 10</span><span class="muted">Design review</span></div><div><span class="task-checkbox" aria-hidden="true"></span><span>Project 11</span><span class="muted">Design review</span></div><div><span class="task-checkbox" aria-hidden="true"></span><span>Project 12</span><span class="muted">Design review</span></div><div><span class="task-checkbox" aria-hidden="true"></span><span>Project 13</span><span class="muted">Design review</span></div><div><span class="task-checkbox" aria-hidden="true"></span><span>Project 14</span><span class="muted">Design review</span></div><div><span class="task-checkbox" aria-hidden="true"></span><span>Project 15</span><span class="muted">Design review</span></div></div><div class="demo-row"><button data-save>Remember position</button><button data-restore>Restore position</button></div><p class="demo-status" role="status">Scroll the list to begin.</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 memory = kit.navigationMemory();
          const list = el.querySelector('.list-demo');
          el.querySelector('[data-save]').addEventListener('click', () => {
            memory.save('projects', list);
            status('Remembered position: ' + Math.round(list.scrollTop) + ' px. Scroll elsewhere now.');
          }, { signal });
          el.querySelector('[data-restore]').addEventListener('click', () => {
            status(memory.restore('projects', list) ? 'List returned to its saved position.' : 'Remember a position first.');
          }, { signal });
          return () => memory.clear();
}
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

Create a memory instance and save(key, list, state) before leaving a list. It stores scroll coordinates plus a cloned state object; read(key) returns that state. Use keys that identify the route and list.

Interface
max; save/read/restore/clear.
Lifecycle
Restore filters and render the list before calling restore(key, list). It returns whether a saved entry exists. clear() removes all entries; storage is memory-only, with 30 entries by default.

Accessibility and safety

Implementation notes

Initialize after the DOM is available. Keep native controls and keyboard interactions intact; release listeners and timers on unmount.

Restore a useful position without stealing focus. Avoid sharing an instance across user sessions or storing sensitive filter values unnecessarily.

What to check

Scroll and filter a list, visit a detail view and return. Confirm state is restored after rendering and that missing entries are handled normally.

View documented module source
/** Typeahead for a custom menu/listbox. Pass visible enabled items only.
 * Repeated letters cycle matching items; multi-letter input matches prefixes.
 * Does not assign ARIA roles or selection; your widget owns those semantics. */
export function typeahead(root, { items, label = e => e.textContent.trim(), timeout = 600 } = {}) {
    let buffer = '', last = 0;
    function key(e) {
        if (e.defaultPrevented || e.isComposing || e.ctrlKey || e.metaKey || e.altKey || e.key.length !== 1 || e.key === ' ' || e.target.closest('input,textarea,[contenteditable]')) return;
        const now = Date.now(), char = e.key.toLocaleLowerCase();
        buffer = now - last > timeout ? char : buffer + char; last = now;
        const repeated = [...buffer].every(c => c === char);
        const query = repeated ? char : buffer;
        const list = [...items()]; if (!list.length) return;
        const index = list.indexOf(document.activeElement);
        const start = repeated ? index + 1 : Math.max(0,index);
        for (let n = 0; n < list.length; n++) {
            const item = list[(start+n)%list.length];
            if (label(item).toLocaleLowerCase().startsWith(query)) { e.preventDefault(); item.focus(); break; }
        }
    }
    root.addEventListener('keydown', key);
    return () => root.removeEventListener('keydown', key);
}

/** Dismiss an overlay when pointer starts AND ends outside it.
 * Include trigger and portalled descendants in `inside()`.
 * Keyboard Escape is intentionally separate: only the topmost overlay
 * should handle it. Use your framework's overlay stack if available. */
export function outsidePress(inside, dismiss, doc = document) {
    let outside = false, pointer = null;
    const isOutside = e => !inside().some(el => e.composedPath().includes(el));
    function down(e) { if (!e.isPrimary || e.button !== 0) return; pointer = e.pointerId; outside = isOutside(e); }
    function up(e) { if (pointer !== e.pointerId) return; const close = outside && isOutside(e); pointer = null; outside = false; if (close) dismiss(e); }
    function cancel() { pointer = null; outside = false; }
    doc.addEventListener('pointerdown',down,true); doc.addEventListener('pointerup',up,true); doc.addEventListener('pointercancel',cancel,true);
    return () => { doc.removeEventListener('pointerdown',down,true); doc.removeEventListener('pointerup',up,true); doc.removeEventListener('pointercancel',cancel,true); };
}

/** Save/restore list scroll position and optional filter state.
 * Call restore AFTER content is rendered; key by route and list identity.
 * Memory-only by default: no sensitive search terms persisted to storage. */
export function navigationMemory({ max = 30 } = {}) {
    const cache = new Map();
    return {
        save(key, element, state = {}) { cache.delete(key); cache.set(key,{ top:element.scrollTop,left:element.scrollLeft,state:structuredClone(state) }); while(cache.size>max) cache.delete(cache.keys().next().value); },
        read(key) { const value=cache.get(key); return value ? structuredClone(value.state) : null; },
        restore(key,element) { const value=cache.get(key); if(value) element.scrollTo({top:value.top,left:value.left,behavior:'instant'}); return Boolean(value); },
        clear() { cache.clear(); }
    };
}

Search Subtly documentation

Popular pages
↑↓ to navigate↵ to openESC to close