Theme
Design your own
On this page (5)
Component Skill — components/logon/component-skill.md

Native basis

Buttons for the users and a <form> with an autocomplete="current-password" field; the runtime turns the native submit into an event. The message is a role="alert" paragraph, the field aria-invalid while it shows.

Web Platform APIs

submit eventautocompletearia-invalidCustomEvent

Notes

• Nothing is checked or kept: the password is in the event's detail and in the field until the state changes.

• data-no-password on a user signs in on the pick (an empty password in the event).

§Sign in and lock

Pick Ada and type 'secret' (anything else is refused), or pick Guest. Signed in, the desktop behind shows; Lock brings the screen back.

§States

Named states via the shared State API, bound on each .logon:

  • default - the users to pick from
  • signing-in - { user }: the password form for that user
  • error - { user, message }: the page refused it; the message shows under the field
  • signed-in - { user }: the screen hides

The first example carries data-state-demo; bun run screenshots drives it via el.api.setState(name) and captures screenshots/{mode}/logon-{state}.png.

Machine contract - verified against logon.schema.json by bun run verify:

StateTypeValuesDefaultDescription
signed-inbooleantrue, falsefalseSigned in: the screen hides (data-state-name).

§API

Generated from logon.ts and the shared State API - the descriptions are their JSDoc, the types are checked by the compiler.

States

type LogonState = 'default' | 'signing-in' | 'error' | 'signed-in' - setState(name, config) takes the config of the state it names.

StateDescription
default
The users to pick from.

No config.

signing-in
A user picked: the password form shows.
Config fieldTypeDescription
user?stringthe data-user of the picked user
error
The page refused the sign-in: the form shows its message.
Config fieldTypeDescription
user?stringthe data-user of the picked user
message?stringwhat went wrong, shown under the field
signed-in
Signed in: the screen hides.
Config fieldTypeDescription
user?stringthe data-user of the user signed in

Every element

MemberDescription
el.api.setState<S extends LogonState>(name: S, config?: LogonStateConfigs[S]): unknown
Enter a state: the DOM work runs (also when it is the current state), the store records it.
ArgumentTypeDescription
nameSa declared state (an unknown name throws)
config?LogonStateConfigs[S]that state's config (merged into the stored one when the component merges)

Returns unknown - what the state's DOM work returned - a Promise for an async state (or await settled())

el.api.getState(): { name: LogonState; config: LogonStateConfigs[LogonState]; model?: ElementModel }
The state the element shows now - read back from the DOM, so it includes what the user changed.

Returns { name: LogonState; config: LogonStateConfigs[LogonState]; model?: ElementModel } - the state's name, its config and the authored markup model render() starts from

el.api.render(state?: { name: LogonState; config: LogonStateConfigs[LogonState]; model?: ElementModel }): string
The element's markup in a state - the authored markup with that state applied; a pure function of the state.
ArgumentTypeDescription
state?{ name: LogonState; config: LogonStateConfigs[LogonState]; model?: ElementModel }a state as getState() returns it (default: the current one)

Returns string - the element's outer HTML in that state

el.api.settled(): Promise<void>
Wait for the last state's DOM work (async states: a diagram rendering, a chart mounting).

Returns Promise<void> - resolves when nothing is pending

el.store: Store<{ name: LogonState; config: LogonStateConfigs[LogonState] }>A defuss-store store of the element's state - subscribe to follow every change (also the user's), set it to drive the component.

Registry

MemberDescription
df$.shadcn.logonApi.setState<S extends LogonState>(el: HTMLElement, name: S, config?: LogonStateConfigs[S]): unknown
Enter a state: the DOM work runs (also when it is the current state), the store records it.
ArgumentTypeDescription
elHTMLElementthe component's element
nameSa declared state (an unknown name throws)
config?LogonStateConfigs[S]that state's config (merged into the stored one when the component merges)

Returns unknown - what the state's DOM work returned - a Promise for an async state (await it, or el.api.settled())

df$.shadcn.logonApi.getState(el: HTMLElement): { name: LogonState; config: LogonStateConfigs[LogonState]; model?: ElementModel }
The state the element shows now - read back from the DOM, so it includes what the user changed.
ArgumentTypeDescription
elHTMLElementthe component's element

Returns { name: LogonState; config: LogonStateConfigs[LogonState]; model?: ElementModel } - the state's name, its config and the authored markup model render() starts from

df$.shadcn.logonApi.render(state: { name: LogonState; config: LogonStateConfigs[LogonState]; model?: ElementModel }): string
The element's markup in a state - the authored markup with that state applied; a pure function of the state.
ArgumentTypeDescription
state{ name: LogonState; config: LogonStateConfigs[LogonState]; model?: ElementModel }a state as getState() returns it (with its model)

Returns string - the element's outer HTML in that state

df$.shadcn.logonApi.store(el: HTMLElement): Store<{ name: LogonState; config: LogonStateConfigs[LogonState] }>
The element's store (bindComponent made it).
ArgumentTypeDescription
elHTMLElementthe component's element

Returns Store<{ name: LogonState; config: LogonStateConfigs[LogonState] }> - a defuss-store store of { name, config } - subscribe to follow every change, set it to drive the component

df$.shadcn.logonApi.commit<S extends LogonState>(el: HTMLElement, name: S, config?: LogonStateConfigs[S]): void
Record a state the element reached on its own (no DOM work) - for a component's own handlers.
ArgumentTypeDescription
elHTMLElementthe component's element
nameSthe state it is in
config?LogonStateConfigs[S]its config
df$.shadcn.logonStates: LogonState[]The declared states, 'default' first: default, signing-in, error, signed-in.

df$.shadcn.logon

MemberDescription
fail(target: string | HTMLElement, message: string): HTMLElement | null
Refuse the sign-in: the form shows the message and keeps the user.
ArgumentTypeDescription
targetstring | HTMLElementthe .logon element, its id or a selector
messagestringwhat went wrong

Returns HTMLElement | null - the screen, null when the target matches none

done(target: string | HTMLElement): HTMLElement | null
Sign in: the screen hides.
ArgumentTypeDescription
targetstring | HTMLElementthe .logon element, its id or a selector

Returns HTMLElement | null - the screen, null when the target matches none

lock(target: string | HTMLElement): HTMLElement | null
Lock: the screen shows again, with the users to pick from.
ArgumentTypeDescription
targetstring | HTMLElementthe .logon element, its id or a selector

Returns HTMLElement | null - the screen, null when the target matches none

Events

EventDescription
logon-power
Fires when a power button is pressed - the page shuts down, restarts or sleeps.

detail: LogonPowerDetail

FieldTypeDescription
actionstringthe data-logon-power of the button: shutdown, restart, sleep ...
logon-submit
Fires when the reader signs in - the user and what they typed; the page answers with done() or fail().

detail: LogonSubmitDetail

FieldTypeDescription
userstringthe picked user's data-user
passwordstringwhat was typed into the password field ('' for a user without one) - the page checks it; nothing is kept

Types

TypeDescription
LogonPowerDetail
What logon-power carries.
FieldTypeDescription
actionstringthe data-logon-power of the button: shutdown, restart, sleep ...
LogonSubmitDetail
What logon-submit carries.
FieldTypeDescription
userstringthe picked user's data-user
passwordstringwhat was typed into the password field ('' for a user without one) - the page checks it; nothing is kept

§CSS view file

/* -- Logon component ----------------------------------------------
   A full-area sign-in / lock screen: the users as large buttons, the picked
   one's password form beside them, the power buttons in a corner. Inside a
   positioned desktop it covers it (position absolute, inset 0). A look
   restyles it - the screen with a divider and tiles, a centred avatar, a
   small dialog. Signed in, it hides. */
@layer components {
  .logon {
    position: absolute;
    inset: 0;
    z-index: 50;
    box-sizing: border-box;
    display: grid;
    grid-template-rows: 1fr auto;
    padding: 1.5rem;
    background: var(--logon-background, var(--background));
    color: var(--foreground);
    font-family: var(--font-sans);
    &[data-signed-in] {
      display: none;
    }
  }
  .logon-main {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: center;
    gap: 1.5rem 3rem;
    align-self: center;
  }
  .logon-brand {
    display: grid;
    gap: 0.25rem;
    text-align: center;
  }
  .logon-users {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 0.75rem;
    margin: 0;
    padding: 0;
    list-style: none;
  }
  .logon-user {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 0.5rem;
    min-width: 7rem;
    padding: 0.75rem;
    border: 1px solid transparent;
    border-radius: var(--radius-lg);
    background: none;
    color: inherit;
    font: inherit;
    cursor: pointer;
    & .avatar {
      width: 4rem;
      height: 4rem;
    }
    &:hover {
      background: var(--accent);
      color: var(--accent-foreground);
    }
    &[aria-pressed="true"] {
      border-color: var(--ring);
      background: var(--accent);
      color: var(--accent-foreground);
    }
    &:focus-visible {
      outline: 2px solid var(--ring);
      outline-offset: 2px;
    }
  }
  .logon-name {
    font-weight: 600;
  }
  .logon-form {
    display: grid;
    gap: 0.5rem;
    width: min(18rem, 100%);
    &[hidden] {
      display: none;
    }
  }
  .logon-for {
    margin: 0;
    font-weight: 600;
  }
  .logon-field {
    display: flex;
    gap: 0.375rem;
  }
  .logon-error {
    margin: 0;
    color: var(--destructive);
    font-size: 0.875rem;
  }
  .logon-power {
    display: flex;
    justify-content: flex-end;
    gap: 0.5rem;
  }
  @media (forced-colors: active) {
    .logon-user[aria-pressed="true"] {
      outline: 2px solid Highlight;
    }
  }
}

§JavaScript view file

The native submit becomes logon-submit; done(), fail() and lock() are the page's answers.

// -- Logon --------------------------------------------------------
// A desktop's sign-in and lock screen: the users as buttons, a password form
// for the one picked and the power buttons. It checks nothing itself - a
// submit fires logon-submit with the user and the typed password, and the
// page answers: df$.shadcn.logon.fail() shows a message, .done() signs in
// (the screen hides), .lock() brings it back. A user without a password
// (data-no-password) signs in on the pick.
// VERIFIED: (logon.e2e) a screen authored signed in starts signed in - read() derives the state from the markup,
// so render() reproduces it.
// Shared preamble (AGENTS.md "State API"); the implementation lives in core.js —
// build.ts rewrites this import into a df$.shadcn.shared binding in dist/.
import { defussGlobals, defussQuery, componentState, bindComponent } from '../../../shared/state-api.js';
const df$ = defussGlobals();
const dfDollar = defussQuery();
/** What logon-submit carries. */
interface LogonSubmitDetail {
  /** the picked user's data-user */
  user: string;
  /** what was typed into the password field ('' for a user without one) - the page checks it; nothing is kept */
  password: string;
}
/** What logon-power carries. */
interface LogonPowerDetail {
  /** the data-logon-power of the button: shutdown, restart, sleep ... */
  action: string;
}
const logonStates = ['default', 'signing-in', 'error', 'signed-in'];
/** setState() configs per state. */
export interface LogonStateConfigs {
  /** The users to pick from. */
  default: {};
  /** A user picked: the password form shows. */
  'signing-in': {
    /** the data-user of the picked user */
    user?: string;
  };
  /** The page refused the sign-in: the form shows its message. */
  error: {
    /** the data-user of the picked user */
    user?: string;
    /** what went wrong, shown under the field */
    message?: string;
  };
  /** Signed in: the screen hides. */
  'signed-in': {
    /** the data-user of the user signed in */
    user?: string;
  };
}
const resolve = (target) =>
  typeof target === 'string' ? (dfDollar('#' + CSS.escape(target)).get(0) ?? dfDollar(target).get(0)) : target;
const users = (el: HTMLElement): HTMLElement[] => dfDollar(el).find<HTMLElement>('.logon-user').toArray();
const nameOf = (u: HTMLElement): string =>
  (dfDollar(u).find('.logon-name').get(0)?.textContent ?? u.textContent ?? '').trim();
/**
 * The markup of a state: which user is pressed, the form and its message, the
 * screen's own data-user / data-signed-in.
 */
function applyMarkup(el, stateName, config) {
  const user = stateName === 'default' ? '' : (config.user ?? '');
  for (const u of users(el)) dfDollar(u).attr('aria-pressed', user && u.dataset.user === user ? 'true' : 'false');
  dfDollar(el).attr('data-user', user || null);
  dfDollar(el).attr('data-signed-in', stateName === 'signed-in' ? '' : null);
  const form = dfDollar(el).find('.logon-form');
  form.attr('hidden', stateName === 'signing-in' || stateName === 'error' ? null : '');
  const picked = users(el).find((u) => u.dataset.user === user);
  form.find('.logon-for').text(picked ? nameOf(picked) : '');
  const err = dfDollar(el).find('.logon-error');
  err.attr('hidden', stateName === 'error' ? null : '');
  err.text(stateName === 'error' ? (config.message ?? '') : '');
  form.find('input[type="password"]').attr('aria-invalid', stateName === 'error' ? 'true' : null);
}
function triggerStateChange(el, stateName, config) {
  applyMarkup(el, stateName, config);
  el.dataset.stateName = stateName;
  const input = dfDollar(el).find('.logon-form input[type="password"]').get(0) as HTMLInputElement | undefined;
  if (stateName === 'signing-in' || stateName === 'error') {
    if (input) {
      if (stateName === 'signing-in') input.value = '';
      requestAnimationFrame(() => input.focus());
      if (stateName === 'error') input.select();
    }
  } else if (input) input.value = '';
  if (stateName === 'default') users(el)[0]?.focus({ preventScroll: true });
}
/** Registry-level API; pass the .logon element explicitly. Unknown names throw. */
export const logonApi = componentState({
  component: 'logon',
  states: logonStates,
  apply: (el, state) => triggerStateChange(el, state.name, state.config),
  // the config is in the markup: the user picked (data-user) and the message shown
  read: (el) => {
    const name = el.dataset.stateName || 'default';
    if (name === 'default') return { name, config: {} };
    const user = el.dataset.user ?? '';
    if (name !== 'error') return { name, config: { user } };
    return { name, config: { user, message: dfDollar(el).find('.logon-error').text() } };
  },
  markup: (el, state) => applyMarkup(el, state.name, state.config),
});
df$.logonApi = logonApi;
df$.logonStates = logonStates;
function pickUser(el: HTMLElement, u: HTMLElement) {
  const user = u.dataset.user ?? nameOf(u);
  if (u.hasAttribute('data-no-password')) {
    logonApi.setState(el, 'signing-in', { user });
    submit(el, user, '');
  } else logonApi.setState(el, 'signing-in', { user });
}
function submit(el: HTMLElement, user: string, password: string) {
  // Fires when the reader signs in - the user and what they typed; the page answers with done() or fail().
  el.dispatchEvent(new CustomEvent<LogonSubmitDetail>('logon-submit', { bubbles: true, detail: { user, password } }));
}
function bind(el: HTMLElement) {
  el.addEventListener('click', (e) => {
    const u = (e.target as Element).closest('.logon-user') as HTMLElement | null;
    if (u) pickUser(el, u);
    const p = (e.target as Element).closest('[data-logon-power]') as HTMLElement | null;
    // Fires when a power button is pressed - the page shuts down, restarts or sleeps.
    if (p)
      el.dispatchEvent(
        new CustomEvent<LogonPowerDetail>('logon-power', {
          bubbles: true,
          detail: { action: p.dataset.logonPower ?? '' },
        }),
      );
  });
  dfDollar(el)
    .find('.logon-form')
    .on('submit', (e) => {
      e.preventDefault();
      const input = dfDollar(el).find('.logon-form input[type="password"]').get(0) as HTMLInputElement | undefined;
      submit(el, el.dataset.user ?? '', input?.value ?? '');
    });
  el.addEventListener('keydown', (e) => {
    if (e.key === 'Escape' && (e.target as Element).closest('.logon-form')) {
      e.preventDefault();
      logonApi.setState(el, 'default', {});
    }
    // arrows between the users
    const u = (e.target as Element).closest('.logon-user');
    if (!u || !['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(e.key)) return;
    const all = users(el);
    const next =
      all[
        (all.indexOf(u as HTMLElement) + (e.key === 'ArrowRight' || e.key === 'ArrowDown' ? 1 : -1) + all.length) %
          all.length
      ];
    e.preventDefault();
    next.focus();
  });
}
/**
 * Refuse the sign-in: the form shows the message and keeps the user.
 * @param target - the .logon element, its id or a selector
 * @param message - what went wrong
 * @returns the screen, null when the target matches none
 */
const fail = (target: string | HTMLElement, message: string): HTMLElement | null => {
  const el = resolve(target);
  if (el) logonApi.setState(el, 'error', { user: el.dataset.user ?? '', message });
  return el;
};
/**
 * Sign in: the screen hides.
 * @param target - the .logon element, its id or a selector
 * @returns the screen, null when the target matches none
 */
const done = (target: string | HTMLElement): HTMLElement | null => {
  const el = resolve(target);
  if (el) logonApi.setState(el, 'signed-in', { user: el.dataset.user ?? '' });
  return el;
};
/**
 * Lock: the screen shows again, with the users to pick from.
 * @param target - the .logon element, its id or a selector
 * @returns the screen, null when the target matches none
 */
const lock = (target: string | HTMLElement): HTMLElement | null => {
  const el = resolve(target);
  if (el) logonApi.setState(el, 'default', {});
  return el;
};
/** df$.shadcn.logon - answer a sign-in, lock the screen. */
export const logonActions = { fail, done, lock };
df$.logon = logonActions;
function init() {
  dfDollar('.logon:not([data-init])')
    .toArray()
    .forEach((el) => {
      el.dataset.init = '';
      for (const u of users(el)) if (!u.hasAttribute('aria-pressed')) u.setAttribute('aria-pressed', 'false');
      el.dataset.stateName = el.hasAttribute('data-signed-in') ? 'signed-in' : 'default';
      // the markup the authored state implies (its user pressed and named) is written at init, not on the first change
      if (el.dataset.stateName === 'signed-in') applyMarkup(el, 'signed-in', { user: el.dataset.user ?? '' });
      bind(el);
      // el.store + el.api (AGENTS.md "State through stores")
      bindComponent(el, logonApi);
    });
}
init();
new MutationObserver(init).observe(document, { childList: true, subtree: true });

Comments, ideas or improvements? Edit this page's source on GitHub