Examples
Examples
Small, complete mx programs you can learn from. Every one runs as-is: try it below, or open it in the playground and change it.
Fetch & Render
Fetch data and render a list. The fetch is faked, so nothing leaves the page.
Open in playgroundEach example renders into #app and needs nothing but the engine. Want bigger ones? Patterns has sortable tables, drag and drop and a file drop zone. The tutorial builds a contact form step by step.
Todo App#
The list lives in the component: todos comes in through $() and every change goes out through this.$() as a new array. The text field stays uncontrolled: add() reads it from the form on submit, so typing never re-renders anything.
define('todo-app', {
$({ todos = [] }) {
let add = e => {
e.preventDefault();
let input = e.target.elements.todo;
let text = input.value.trim();
if (!text) return;
input.value = '';
this.$({ todos: [...todos, { text, done: false }] });
};
let toggle = index => this.$({ todos: todos.map((todo, i) => i === index ? { text: todo.text, done: !todo.done } : todo) });
let remove = index => this.$({ todos: todos.filter((todo, i) => i !== index) });
let left = todos.filter(todo => !todo.done).length;
return [
mx.form({ onsubmit: add },
mx.input({ name: 'todo', placeholder: 'What needs doing?', 'aria-label': 'New todo' }),
mx.button({ type: 'submit' }, 'Add')
),
mx.ul(...todos.map((todo, i) => mx.li({ class: todo.done ? 'done' : null },
mx.label(
mx.input({ type: 'checkbox', '.checked': todo.done, onchange: _ => toggle(i) }),
todo.text
),
mx.button({ onclick: _ => remove(i), 'aria-label': 'Remove ' + todo.text }, 'Remove')
))),
mx.p(left + ' of ' + todos.length + ' left')
];
}
});
document.getElementById('app').render(mx.todoApp({
todos: [{ text: 'Read the docs', done: true }, { text: 'Build something', done: false }]
}));Counter#
This is the smallest component, with one piece of state that has a default and two handlers that call this.$(). mx.clickCounter({ count: 42 }) sets the starting value from outside.
define('click-counter', {
$({ count = 0 }) {
return [
mx.button({ onclick: _ => this.$({ count: count - 1 }), 'aria-label': 'Decrement' }, '-'),
mx.output({ style: 'padding:0 12px' }, count),
mx.button({ onclick: _ => this.$({ count: count + 1 }), 'aria-label': 'Increment' }, '+')
];
}
});
document.getElementById('app').render(mx.clickCounter({ count: 42 }));Tabs#
This one component covers the WAI-ARIA tabs pattern, and role, aria-selected and a roving tabindex are just attributes in the description. Every panel is rendered and the inactive ones get hidden.
define('tab-set', {
$({ tabs = [], active = 0 }) {
let select = index => {
this.$({ active: (index + tabs.length) % tabs.length });
this.querySelector('[aria-selected="true"]').focus();
};
let step = { ArrowLeft: -1, ArrowRight: 1 };
return [
mx.div({ role: 'tablist', 'aria-label': 'Example tabs', onkeydown: e => {
if (step[e.key]) select(active + step[e.key]);
} },
...tabs.map((tab, i) => mx.button({
role: 'tab',
id: 'tab-' + i,
'aria-controls': 'panel-' + i,
'aria-selected': i === active ? 'true' : 'false',
tabindex: i === active ? '0' : '-1',
onclick: _ => select(i)
}, tab.label))
),
...tabs.map((tab, i) => mx.div({
role: 'tabpanel',
id: 'panel-' + i,
'aria-labelledby': 'tab-' + i,
tabindex: '0',
hidden: i !== active
}, tab.content))
];
}
});
document.getElementById('app').render(mx.tabSet({ tabs: [
{ label: 'Tab 1', content: 'Every panel is rendered; the inactive ones are hidden.' },
{ label: 'Tab 2', content: 'Arrow keys move between tabs, and focus follows.' },
{ label: 'Tab 3', content: 'The roles and ids are the WAI-ARIA tabs pattern.' }
] }));Fetch & Render#
Nothing goes over the network. fakeFetch returns a resolved promise with the same shape as fetch(), so the example runs anywhere. Swap it for fetch('/api/users') in a real app.
dom.userList({}) creates the element once and keeps a reference. When the data arrives, list.$({ users }) re-renders it. Loading and error states are just branches in $().
// Stands in for fetch('/api/users'): the same promise shape, no network.
let fakeFetch = url => Promise.resolve({
json: _ => Promise.resolve([
{ name: 'Ada Lovelace', role: 'Engineer' },
{ name: 'Grace Hopper', role: 'Admiral' },
{ name: 'Alan Turing', role: 'Researcher' }
])
});
define('user-list', {
$({ users, error }) {
if (error) return mx.p({ role: 'alert' }, 'Could not load users: ' + error);
if (!users) return mx.p('Loading...');
return mx.ul(...users.map(user => mx.li(mx.strong(user.name), ' - ' + user.role)));
}
});
let list = dom.userList({});
document.getElementById('app').render(list);
fakeFetch('/api/users')
.then(response => response.json())
.then(users => list.$({ users }))
.catch(error => list.$({ error: error.message }));Modal#
You don't need a modal component, because the native <dialog> element already handles focus, the inert background and Escape. dom.dialog() holds the node so the button can call showModal(), and <form method="dialog"> closes it without a handler.
let dialog = dom.dialog({ 'aria-labelledby': 'modal-title', style: 'margin:auto;max-width:360px;padding:16px' },
mx.h2({ id: 'modal-title' }, 'Modal title'),
mx.p('A native dialog: showModal() moves focus inside, makes the page behind it inert, and Escape closes it.'),
mx.form({ method: 'dialog' }, mx.button('Close'))
);
document.getElementById('app').render(
mx.button({ onclick: _ => dialog.showModal() }, 'Open modal'),
dialog
);Form#
The browser validates required and type="email" before onsubmit fires. new FormData(e.target) reads every named field at once, and the component swaps to a thank-you state.
define('signup-form', {
$({ sent }) {
if (sent) {
return [
mx.p('Thanks, ' + sent.name + '! We will write to ' + sent.email + '.'),
mx.button({ onclick: _ => this.$({ sent: null }) }, 'Send another')
];
}
return mx.form({ onsubmit: e => {
e.preventDefault();
this.$({ sent: Object.fromEntries(new FormData(e.target)) });
} },
mx.label('Name', mx.input({ name: 'name', required: true, autocomplete: 'name' })),
mx.label('Email', mx.input({ name: 'email', type: 'email', required: true, autocomplete: 'email' })),
mx.button({ type: 'submit' }, 'Send')
);
}
});
document.getElementById('app').render(mx.signupForm());Virtual scroll#
Two spacer divs above and below the visible slice give the container the full height of all 10,000 rows, so the scrollbar behaves as if every row were there. On scroll, onscroll works out which row is at the top and renders just the ten rows in view.
define('virtual-container', {
$({ height = 400, rowHeight = 48, rows = [] }) {
this._visibleRows = Math.ceil(height / rowHeight) + 1;
this._lastOffset = 0;
this.style.cssText = `display:block;height:${height}px;overflow-y:auto;border:1px solid var(--l1, #8884)`;
let renderVisible = offset => {
let visible = rows.slice(offset, offset + this._visibleRows);
return [
mx.div({ style: `height:${offset * rowHeight}px` }),
...visible,
mx.div({ style: `height:${(rows.length - offset - visible.length) * rowHeight}px` })
];
};
this.onscroll = _ => {
let scrollTop = this.scrollTop;
let offset = Math.floor(scrollTop / rowHeight);
if (offset === this._lastOffset) return;
this._lastOffset = offset;
this.render(...renderVisible(offset));
this.scrollTop = scrollTop;
};
return renderVisible(0);
}
});
let rows = Array.from({ length: 10000 }, (_, i) => mx.div({
style: 'box-sizing:border-box;height:48px;padding:12px 16px;border-bottom:1px solid var(--l2, #8884)'
}, 'Item ' + (i + 1)));
document.getElementById('app').render(mx.virtualContainer({ height: 400, rowHeight: 48, rows }));Date picker#
The calendar is a native popover: popovertarget on the trigger opens it, and the browser closes it on Escape or a click outside and hands focus back. onbeforetoggle places it under the field and jumps to the picked month. The day under the cursor is the grid's one Tab stop, and the arrow keys move it.
let uid = 0;
let same = (a, b) => a?.toDateString() === b.toDateString();
let format = (date, options) => date.toLocaleDateString('en-US', options);
let icon = (d, style) => mx.svg({ viewBox: '0 0 24 24', width: 16, height: 16, fill: 'none', stroke: 'currentColor',
'stroke-width': 1.8, 'stroke-linecap': 'round', 'stroke-linejoin': 'round', 'aria-hidden': 'true', style }, mx.path({ d }));
let BARE = 'padding:0;border:0;border-radius:var(--r2, 5px);font:inherit;cursor:pointer;';
define('date-field', {
$({ value, placeholder = 'Select date...', open = false, focus = value || new Date, top = 0, left = 0, onchange }) {
let id = this.fieldId ||= 'date-field-' + ++uid;
let year = focus.getFullYear();
let month = focus.getMonth();
let start = 1 - new Date(year, month, 1).getDay();
let steps = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: -7, ArrowDown: 7 };
let pick = date => {
this.$({ value: date });
this.querySelector('[popover]').hidePopover();
onchange?.(date);
};
// Day 1 of the other month: setMonth() on the 31st would overflow a short month
let nav = (label, delta, d) => mx.button({ type: 'button', 'aria-label': label,
style: BARE + 'display:grid;place-items:center;width:24px;height:24px;background:none;color:var(--fg3, inherit)',
onclick: _ => this.$({ focus: new Date(year, month + delta, 1) }) }, icon(d));
// The roving day gets a soft fill instead of a focus ring
let day = date => {
let picked = same(value, date);
let color = date.getMonth() === month ? 'var(--fg2, inherit)' : 'var(--fg4, GrayText)';
let fill = same(focus, date) ? 'var(--sf3, #8883)' : 'none';
let look = picked ? 'background:var(--p2, #f5a33a);color:var(--p5, #000);font-weight:700' : `background:${fill};color:${color}`;
return mx.button({
type: 'button',
tabindex: same(focus, date) ? '0' : '-1',
'aria-pressed': String(picked),
'aria-current': same(new Date, date) ? 'date' : null,
'aria-label': format(date, { dateStyle: 'full' }),
style: BARE + 'height:30px;box-shadow:none;font-variant-numeric:tabular-nums;' + look
+ (same(new Date, date) ? ';outline:1px solid var(--l3, #f5a33a88);outline-offset:-1px' : ''),
onclick: _ => pick(date)
}, date.getDate());
};
return [
mx.button({
type: 'button',
popovertarget: id,
'aria-haspopup': 'dialog',
'aria-expanded': String(open),
style: BARE + 'display:flex;align-items:center;gap:8px;width:260px;max-width:100%;height:34px;padding:0 12px;'
+ 'border:1px solid var(--input-border, #8886);border-radius:var(--r3, 7px);background:var(--sf5, Field);color:var(--fg1, FieldText)'
},
mx.span({ style: 'flex:1;text-align:left;color:' + (value ? 'inherit' : 'var(--fg4, GrayText)') },
value ? format(value, { dateStyle: 'long' }) : placeholder),
icon('M8 2v3M16 2v3M3.5 9.2h17M5 4.5h14a2 2 0 0 1 2 2v13a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-13a2 2 0 0 1 2-2z', 'color:var(--fg3, inherit)')
),
// A native popover: click outside or Escape closes it, and focus goes back to the trigger
mx.div({
id,
popover: '',
role: 'dialog',
'aria-label': 'Choose date',
style: `position:absolute;inset:auto;top:${top}px;left:${left}px;margin:0;padding:12px;font-size:14px;`
+ 'border:1px solid var(--l1, #8884);border-radius:var(--r3, 7px);background:var(--sf2, Canvas);color:var(--fg1, CanvasText);box-shadow:var(--sh2, 0 8px 24px #0003);backdrop-filter:blur(12px)',
// Open under the trigger, on the picked month
onbeforetoggle: e => {
let box = this.firstChild.getBoundingClientRect();
this.$({ open: e.newState === 'open', focus: value || new Date, top: box.bottom + scrollY + 6, left: box.left + scrollX });
},
ontoggle: e => e.newState === 'open' && this.querySelector('[tabindex="0"]').focus()
},
mx.div({ style: 'display:flex;align-items:center;gap:8px;margin-bottom:8px' },
mx.strong({ 'aria-live': 'polite', style: 'flex:1' }, format(focus, { month: 'long', year: 'numeric' })),
nav('Previous month', -1, 'm15 6-6 6 6 6'),
nav('Next month', 1, 'm9 6 6 6-6 6')
),
// Arrows move by day and week, across month edges too; Enter picks
mx.div({ style: 'display:grid;grid-template-columns:repeat(7, 36px);gap:2px', onkeydown: e => {
if (!steps[e.key]) return;
e.preventDefault();
this.$({ focus: new Date(year, month, focus.getDate() + steps[e.key]) });
this.querySelector('[tabindex="0"]').focus();
} },
...['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'].map(name => mx.span({ 'aria-hidden': 'true',
style: 'padding-bottom:4px;text-align:center;font-size:12px;color:var(--fg4, GrayText)' }, name)),
...Array.from({ length: 42 }, (_, i) => day(new Date(year, month, start + i)))
)
)
];
}
});
document.getElementById('app').render(mx.dateField());