Open in a new tab

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

  1. npm install @awacloud/fw
  2. Serve node_modules/@awacloud/fw/src/ at /vendor/fw/ (node serve.js from the examples root does this; any static server works).
  3. Copy index.html and main.js next to each other and open index.html through that server. The ../../_style/examples.css link is optional: copy that file along, or delete the link.
  4. Replace the body of submit with your real save; a throw inside it is logged by the guard.

What it shows

  • signal.create for the value, signal.computed for its validation, signal.effect to render, subscribe to forward changes.
  • valid.compile(schema) with format: 'email', giving validate (with messages) and test (boolean).
  • eventBus.create(): emit('form:change') and emit('form:saved'), a listener per topic, and the unsubscribe function on returns.
  • errors.logger({ sink }) for structured records, rendered by the sink into the page's log, and errors.guard so a failing submit is logged, not thrown.

Code

main.js

javascriptApache-2.067 lines

// 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

htmlApache-2.028 lines

<!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>