Signals, an event bus and validation
Hold a field in a signal, validate it with a schema, broadcast its changes on an event bus.
Apache-2.0Runs on this page
Package: @awacloud/fw
An email field held in a signal and validated by a schema, changes and saves broadcast on an event bus, and failures reported by a structured logger instead of thrown at the page.
Uses @awacloud/fw (Apache-2.0). This example's code is Apache-2.0.
When to use it
The state layer of a page without a framework: one source of truth per field, validation derived from it, other parts of the page told through topics rather than direct calls, and failures logged rather than thrown.
Copy-paste steps
npm install @awacloud/fw- Serve
node_modules/@awacloud/fw/src/at/vendor/fw/(node serve.jsfrom the examples root does this; any static server works). - Copy
index.htmlandmain.jsnext to each other and openindex.htmlthrough that server. The../../_style/examples.csslink is optional: copy that file along, or delete the link. - Replace the body of
submitwith your real save; a throw inside it is logged by the guard.
What it shows
signal.createfor the value,signal.computedfor its validation,signal.effectto render,subscribeto forward changes.valid.compile(schema)withformat: 'email', givingvalidate(with messages) andtest(boolean).eventBus.create():emit('form:change')andemit('form:saved'), a listener per topic, and the unsubscribe functiononreturns.errors.logger({ sink })for structured records, rendered by the sink into the page's log, anderrors.guardso a failing submit is logged, not thrown.
Code
main.js
// SPDX-License-Identifier: Apache-2.0
import fw from '@awacloud/fw';
import { signal } from '@awacloud/fw/io/utils/signal.js';
import { eventBus } from '@awacloud/fw/io/utils/eventBus.js';
import { errors } from '@awacloud/fw/io/utils/errors.js';
import { valid } from '@awacloud/fw/io/utils/valid.js';
fw.runtime.registerAllDeep([signal, eventBus, errors, valid]);
const SIGNAL = fw.runtime.resolve('signal');
const VALID = fw.runtime.resolve('valid');
const ERRORS = fw.runtime.resolve('errors');
/** The one bus of the page; other modules subscribe to `form:change` / `form:saved`. */
export const bus = fw.runtime.resolve('eventBus').create();
const validator = VALID.compile({ type: 'string', format: 'email', maxLength: 64 });
/** State: the raw value, and its validation derived from it. */
export const email = SIGNAL.create('');
export const check = SIGNAL.computed(() => validator.validate(email.get()));
/** @param {string} id @param {string} text */
const append = (id, text) => {
const list = /** @type {HTMLElement} */ (document.getElementById(id));
list.appendChild(document.createElement('li')).textContent = text;
};
/** Structured logging, rendered by its sink into the page's log. */
const log = ERRORS.logger({
level: 'info',
prefix: 'form',
/** @param {{ level: string, prefix: string, message: string }} r */
sink: (r) => append('log', `${r.level} [${r.prefix}] ${r.message}`),
});
/** A submission that fails is logged, never thrown at the caller. */
const guarded = ERRORS.guard({
onError: (/** @type {Error} */ err) => log.error(`submit failed: ${err.message}`),
});
/** @param {string} value */
export function submit(value) {
guarded(() => {
if (!validator.test(value)) throw new Error(`invalid email "${value}"`);
log.info(`saved ${value}`);
bus.emit('form:saved', value);
});
}
const input = /** @type {HTMLInputElement} */ (document.getElementById('email'));
const error = /** @type {HTMLElement} */ (document.getElementById('error'));
SIGNAL.effect(() => {
const result = check.get();
const messages = result.errors?.map((/** @type {{ message: string }} */ e) => e.message) ?? [];
error.textContent = messages.join('; ');
input.setAttribute('aria-invalid', String(!result.valid));
});
email.subscribe((/** @type {string} */ value) => bus.emit('form:change', value));
for (const topic of ['form:change', 'form:saved']) {
bus.on(topic, (/** @type {string} */ value) => append('events', `${topic} ${value}`));
}
log.info('ready');
input.addEventListener('input', () => email.set(input.value));
/** @type {HTMLElement} */ (document.getElementById('submit')).addEventListener('click', () => submit(email.get()));
email.set(input.value);index.html
<!doctype html>
<!-- SPDX-License-Identifier: Apache-2.0 -->
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>fw · Signals, an event bus and validation</title>
<link rel="stylesheet" href="../../_style/examples.css">
<script type="importmap">
{ "imports": {
"@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/" } }
</script>
<script type="module" src="./main.js"></script>
</head>
<body>
<main>
<h1>Signals, an event bus and validation</h1>
<label for="email">Email</label>
<input id="email" type="email" value="ada@example" autocomplete="off" aria-describedby="error">
<p id="error" class="error" aria-live="polite"></p>
<button id="submit" type="button">Submit</button>
<h2>Event bus</h2>
<ol id="events" aria-label="Events"></ol>
<h2>Log</h2>
<ol id="log" aria-label="Log"></ol>
</main>
</body>
</html>