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

Native basis

A group of <button>s and a <time> the runtime writes. An item opens its popover with popovertarget; a badge is data-badge, drawn with attr().

Web Platform APIs

Intl.DateTimeFormat<time>popovertargetattr()

Variants

• data-seconds - the clock shows seconds; data-date - the date under the time.

§Items, badge and clock

The network item opens its panel, the bell carries a badge, the clock shows seconds and the date in German (lang on the tray). Add mail puts an item before the clock through df$.shadcn.tray.

§States

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

  • default - the tray; { seconds, date } set how the clock reads

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

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

StateTypeValuesDefaultDescription

§API

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

States

type TrayState = 'default' - setState(name, config) takes the config of the state it names.

StateDescription
default
The tray - how its clock reads.
Config fieldTypeDescription
seconds?booleanthe clock shows seconds (data-seconds)
date?booleanthe clock shows the date under the time (data-date)

Every element

MemberDescription
el.api.setState<S extends TrayState>(name: S, config?: TrayStateConfigs[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?TrayStateConfigs[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: TrayState; config: TrayStateConfigs[TrayState]; model?: ElementModel }
The state the element shows now - read back from the DOM, so it includes what the user changed.

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

el.api.render(state?: { name: TrayState; config: TrayStateConfigs[TrayState]; 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: TrayState; config: TrayStateConfigs[TrayState]; 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: TrayState; config: TrayStateConfigs[TrayState] }>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.trayApi.setState<S extends TrayState>(el: HTMLElement, name: S, config?: TrayStateConfigs[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?TrayStateConfigs[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.trayApi.getState(el: HTMLElement): { name: TrayState; config: TrayStateConfigs[TrayState]; 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: TrayState; config: TrayStateConfigs[TrayState]; model?: ElementModel } - the state's name, its config and the authored markup model render() starts from

df$.shadcn.trayApi.render(state: { name: TrayState; config: TrayStateConfigs[TrayState]; 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: TrayState; config: TrayStateConfigs[TrayState]; model?: ElementModel }a state as getState() returns it (with its model)

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

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

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

df$.shadcn.trayApi.commit<S extends TrayState>(el: HTMLElement, name: S, config?: TrayStateConfigs[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?TrayStateConfigs[S]its config
df$.shadcn.trayStates: TrayState[]The declared states, 'default' first: default.

df$.shadcn.tray

MemberDescription
add(target: string | HTMLElement, options: TrayItemOptions): HTMLButtonElement | null
Adds an icon to the tray (or updates the one with that id).
ArgumentTypeDescription
targetstring | HTMLElementthe .tray element, its id or a selector
optionsTrayItemOptionsid, icon, label, badge and the popover it opens

Returns HTMLButtonElement | null - the item, null when the target matches none

remove(target: string | HTMLElement, id: string): boolean
Removes an icon.
ArgumentTypeDescription
targetstring | HTMLElementthe .tray element, its id or a selector
idstringthe item's id

Returns boolean - whether an item went

badge(item: HTMLElement, value: string | number): void
Sets an item's badge.
ArgumentTypeDescription
itemHTMLElementthe .tray-item element (or its tray's item id with the tray: use add())
valuestring | numbera number or a short word; '' or 0 removes it

Types

TypeDescription
TrayItemOptions
What add() takes.
FieldTypeDescription
idstringthe item's id
iconstringa Lucide icon name
labelstringits accessible name (and tooltip)
badge?string | numbera number or a short word shown on the icon
popover?stringthe id of a popover it opens

§CSS view file

/* -- Tray component -----------------------------------------------
   The notification area: small icon buttons (a badge on one with
   data-badge), the clock the runtime keeps (two lines with the date) and a
   thin "show desktop" strip at the very end. */
@layer components {
  .tray {
    display: flex;
    align-items: center;
    gap: 0.125rem;
    margin-inline-start: auto;
    height: 100%;
    .taskbar:is([data-position="left"], [data-position="right"]) & {
      flex-direction: column;
      margin-inline-start: 0;
      margin-block-start: auto;
      height: auto;
    }
  }
  .tray-item {
    position: relative;
    display: inline-grid;
    place-items: center;
    width: 2rem;
    height: 2rem;
    padding: 0;
    border: 0;
    border-radius: var(--radius-sm);
    background: none;
    color: inherit;
    cursor: default;
    & svg,
    & img {
      width: 1rem;
      height: 1rem;
    }
    &:hover {
      background: color-mix(in oklch, var(--accent) 70%, transparent);
    }
    &:focus-visible {
      outline: 2px solid var(--ring);
      outline-offset: -2px;
    }
    &[data-badge]::after {
      content: attr(data-badge);
      position: absolute;
      inset-block-start: 0.0625rem;
      inset-inline-end: 0;
      min-width: 0.875rem;
      height: 0.875rem;
      padding-inline: 0.1875rem;
      box-sizing: border-box;
      border-radius: 999px;
      background: var(--destructive);
      color: var(--destructive-foreground, white);
      font-size: 0.5625rem;
      font-weight: 700;
      line-height: 0.875rem;
      text-align: center;
    }
  }
  .tray-clock {
    padding-inline: 0.375rem;
    font-size: 0.75rem;
    font-variant-numeric: tabular-nums;
    line-height: 1.25;
    text-align: end;
    white-space: pre;
  }
  .tray-show-desktop {
    align-self: stretch;
    width: 0.375rem;
    margin-inline-start: 0.25rem;
    padding: 0;
    border: 0;
    border-inline-start: 1px solid var(--border);
    background: none;
    cursor: default;
    &:hover,
    &:focus-visible {
      background: color-mix(in oklch, var(--accent) 70%, transparent);
      outline: none;
    }
  }
  @media (forced-colors: active) {
    .tray-item[data-badge]::after {
      forced-color-adjust: none;
      background: Highlight;
      color: HighlightText;
    }
  }
}

§JavaScript view file

The clock ticks on the full second; show desktop calls df$.shadcn.windowManager.showDesktop() on the taskbar's manager.

// -- Tray ---------------------------------------------------------
// The notification area at the end of a taskbar: small icon buttons (each may
// open a popover - native popovertarget - and carry a badge), a clock the
// runtime keeps (Intl, in the tray's language, with seconds and the date when
// asked) and a "show desktop" button that asks the Window Manager of its
// taskbar to minimize every window (and bring them back).
// VERIFIED: (tray.e2e) the clock reads in the language of the nearest [lang] (German with seconds and the date,
// en-US plain) and ticks on the full second.
// 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();
/** An element by id, through df$ (null when none has it). */
const byId = (id: string | null | undefined): HTMLElement | null =>
  (id ? (dfDollar('#' + CSS.escape(id)).get(0) as HTMLElement | undefined) : undefined) ?? null;
/** What add() takes. */
interface TrayItemOptions {
  /** the item's id */
  id: string;
  /** a Lucide icon name */
  icon: string;
  /** its accessible name (and tooltip) */
  label: string;
  /** a number or a short word shown on the icon */
  badge?: string | number;
  /** the id of a popover it opens */
  popover?: string;
}
const trayStates = ['default'];
/** setState() configs per state. */
export interface TrayStateConfigs {
  /** The tray - how its clock reads. */
  default: {
    /** the clock shows seconds (data-seconds) */
    seconds?: boolean;
    /** the clock shows the date under the time (data-date) */
    date?: boolean;
  };
}
const resolve = (target) =>
  typeof target === 'string' ? (dfDollar('#' + CSS.escape(target)).get(0) ?? dfDollar(target).get(0)) : target;
function applyMarkup(tray, _stateName, config) {
  if (config.seconds !== undefined) dfDollar(tray).attr('data-seconds', config.seconds ? '' : null);
  if (config.date !== undefined) dfDollar(tray).attr('data-date', config.date ? '' : null);
}
/** Writes the clock's time (and date) in the tray's language. */
function tick(tray: HTMLElement) {
  const clock = dfDollar(tray).find('.tray-clock').get(0) as HTMLTimeElement | undefined;
  if (!clock) return;
  const lang = tray.closest('[lang]')?.getAttribute('lang') || undefined;
  const now = new Date();
  const time = new Intl.DateTimeFormat(lang, {
    hour: 'numeric',
    minute: '2-digit',
    second: tray.hasAttribute('data-seconds') ? '2-digit' : undefined,
  }).format(now);
  const date = tray.hasAttribute('data-date') ? new Intl.DateTimeFormat(lang, { dateStyle: 'short' }).format(now) : '';
  const text = date ? `${time}\n${date}` : time;
  if (clock.textContent !== text) clock.textContent = text;
  clock.dateTime = now.toISOString().slice(0, tray.hasAttribute('data-seconds') ? 19 : 16);
}
/** The one function that changes the tray for a state: what the clock shows, then the clock itself. */
function triggerStateChange(tray, stateName, config) {
  applyMarkup(tray, stateName, config);
  tick(tray);
}
/** Registry-level API; pass the .tray element explicitly. Unknown names throw. */
export const trayApi = componentState({
  component: 'tray',
  states: trayStates,
  apply: (tray, state) => triggerStateChange(tray, state.name, state.config),
  read: (tray) => ({
    name: 'default',
    config: { seconds: tray.hasAttribute('data-seconds'), date: tray.hasAttribute('data-date') },
  }),
  markup: (el, state) => applyMarkup(el, state.name, state.config),
});
df$.trayApi = trayApi;
df$.trayStates = trayStates;
/** The Window Manager of the taskbar around the tray. */
const managerOf = (tray: HTMLElement): HTMLElement | null => {
  const id = (tray.closest('.taskbar') as HTMLElement | null)?.dataset.taskbarFor;
  return id ? byId(id) : null;
};
/**
 * Adds an icon to the tray (or updates the one with that id).
 * @param target - the .tray element, its id or a selector
 * @param options - id, icon, label, badge and the popover it opens
 * @returns the item, null when the target matches none
 */
const add = (target: string | HTMLElement, options: TrayItemOptions): HTMLButtonElement | null => {
  const tray = resolve(target);
  if (!tray) return null;
  let b = dfDollar(tray)
    .find<HTMLButtonElement>(`.tray-item[data-id="${CSS.escape(options.id)}"]`)
    .get(0);
  if (!b) {
    b = document.createElement('button');
    b.type = 'button';
    b.className = 'tray-item';
    b.dataset.id = options.id;
    const clock = dfDollar(tray).find('.tray-clock').get(0);
    if (clock) clock.before(b);
    else tray.append(b);
  }
  b.setAttribute('aria-label', options.label);
  b.title = options.label;
  dfDollar(b).html(`<i data-lucide="${options.icon}"></i>`);
  if (options.popover) b.setAttribute('popovertarget', options.popover);
  badge(b, options.badge ?? '');
  globalThis.lucide?.createIcons?.();
  return b;
};
/**
 * Removes an icon.
 * @param target - the .tray element, its id or a selector
 * @param id - the item's id
 * @returns whether an item went
 */
const remove = (target: string | HTMLElement, id: string): boolean => {
  const tray = resolve(target);
  const b = tray
    ? dfDollar(tray)
        .find(`.tray-item[data-id="${CSS.escape(id)}"]`)
        .get(0)
    : undefined;
  b?.remove();
  return !!b;
};
/**
 * Sets an item's badge.
 * @param item - the .tray-item element (or its tray's item id with the tray: use add())
 * @param value - a number or a short word; '' or 0 removes it
 */
function badge(item: HTMLElement, value: string | number): void {
  if (value === '' || value === 0) item.removeAttribute('data-badge');
  else item.dataset.badge = String(value);
}
/** df$.shadcn.tray - add, remove and badge tray icons. */
export const trayActions = { add, remove, badge };
df$.tray = trayActions;
function init() {
  dfDollar('.tray:not([data-init])')
    .toArray()
    .forEach((tray) => {
      tray.dataset.init = '';
      tick(tray);
      // a tick at every full second keeps the minute exact without a busy timer
      const loop = () => {
        if (!tray.isConnected) return;
        tick(tray);
        setTimeout(loop, 1000 - (Date.now() % 1000) + 5);
      };
      setTimeout(loop, 1000 - (Date.now() % 1000) + 5);
      tray.addEventListener('click', (e) => {
        if ((e.target as Element).closest('.tray-show-desktop')) {
          const m = managerOf(tray);
          if (m) df$.windowManager?.showDesktop(m);
        }
      });
      // el.store + el.api (AGENTS.md "State through stores")
      bindComponent(tray, trayApi);
    });
}
init();
new MutationObserver(init).observe(document, { childList: true, subtree: true });

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