Theme
Design your own
On this page (8)
Component Skill — components/window-manager/component-skill.md

Native basis

A positioned element holding non-modal <dialog> windows. One MutationObserver reads their open, data-active, data-minimized, data-maximized and title text; the close event is heard on the way down.

Web Platform APIs

MutationObserverclose eventCustomEventqueueMicrotask()

Notes

• Windows belong to the nearest .window-manager around them; the runtime gives a window without an id one.

• A Taskbar bound to it sets data-taskbar: minimized windows then leave the desktop for their buttons.

• toggle(window): a minimized window comes back (maximized when it was), the window in front minimizes, any other comes to the front.

§A desktop's model

Three windows on one desktop; the list under it is rendered from window-manager-change alone - open, focus, minimize, close and rename a window and watch it follow. A row's button is the taskbar rule. Show desktop minimizes every window and brings the same ones back.

§Two desktops, two front windows

Each manager keeps one window in front: a click in the right desktop does not take the front from the left one.

§Drawn scroll bars

With data-scrollbars="virtual" the manager draws the scroll bars of its windows itself - a browser shows its own bar the way it wants (Firefox and Safari style next to nothing of it), so a period look would end at the scroll bar. Each scrolling area keeps scrolling natively (wheel, keys, touch); the drawn bar follows it, and its arrow buttons, track and thumb drive it. Without a look it is a thin modern bar; the Desktop looks draw the 9x, XP and 7 bars. The Desktop look pages and the Desktop scaffold use it.

§Across browser windows

With data-share="name" on the manager, every browser window that shows the page is part of one desktop - after neo.mjs's shared dialogs, kept small. Drag a window past the edge of one browser window and it shows in the browser window beside it while it moves; drop it there and that one takes it, with its size, its place on the screen and the text in its fields. The browser windows talk over a BroadcastChannel, so it needs no server - only the same page in each. A docs card is a sandboxed frame without one, so try it full screen: open a Desktop look (Windows XP, Modern ...) with "Open full screen", then "New browser window" in its start menu opens a second one beside it. The Desktop scaffold shares its windows too.

<div class="window-desktop window-manager" id="desk" data-share="desk">
  <dialog class="window" id="notes" open>…</dialog>
</div>

§States

Named states via the shared State API, bound on each .window-manager:

  • default - the windows as the reader left them; leaving desktop brings back the windows it minimized
  • desktop - show the desktop: every open window minimized (data-desktop-shown); a window that shows again ends it

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

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

StateTypeValuesDefaultDescription
desktopbooleantrue, falsefalseEvery window minimized by show desktop (data-state-name).

§API

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

States

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

StateDescription
default
The windows as the reader left them (leaving 'desktop' brings back the ones it minimized).

No config.

desktop
Show the desktop: every open window minimized.

No config.

Every element

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

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

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

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

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

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

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

df$.shadcn.windowManagerApi.commit<S extends WindowManagerState>(el: HTMLElement, name: S, config?: WindowManagerStateConfigs[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?WindowManagerStateConfigs[S]its config
df$.shadcn.windowManagerStates: WindowManagerState[]The declared states, 'default' first: default, desktop.

df$.shadcn.windowManager

MemberDescription
windows(target: string | HTMLElement): WindowManagerEntry[]
The windows of a manager, in the order they opened.
ArgumentTypeDescription
targetstring | HTMLElementthe .window-manager element, its id or a selector

Returns WindowManagerEntry[] - its open windows (an empty list when the target matches none)

active(target: string | HTMLElement): HTMLDialogElement | undefined
The window in front.
ArgumentTypeDescription
targetstring | HTMLElementthe .window-manager element, its id or a selector

Returns HTMLDialogElement | undefined - the active window that is not minimized, undefined when none is

toggle(target: string | HTMLElement): string
What a taskbar button does: a minimized window comes back to the front, the window in front is minimized, any other comes to the front.
ArgumentTypeDescription
targetstring | HTMLElementthe .window element, its id or a selector

Returns string - the window's state afterwards, '' when the target matches none

showDesktop(target: string | HTMLElement): boolean
Show the desktop (every window minimized), or bring the windows back when it shows.
ArgumentTypeDescription
targetstring | HTMLElementthe .window-manager element, its id or a selector

Returns boolean - whether the desktop shows now

cascade(target: string | HTMLElement, step: number = 28): void
Steps the windows diagonally from the top left - df$.shadcn.win.cascade inside this manager.
ArgumentTypeDescription
targetstring | HTMLElementthe .window-manager element, its id or a selector
stepnumber = 28px between two windows (default 28)
tile(target: string | HTMLElement): void
Lays the windows side by side in a grid - df$.shadcn.win.tile inside this manager.
ArgumentTypeDescription
targetstring | HTMLElementthe .window-manager element, its id or a selector

Events

EventDescription
window-manager-change
Fires when the manager's windows change - one opened, closed, came to the front, was minimized or restored, or renamed.

detail: WindowManagerChangeDetail

FieldTypeDescription
windowsWindowManagerEntry[]the open windows, in the order they opened
activestringthe id of the window in front, '' when none is

Types

TypeDescription
WindowManagerChangeDetail
What window-manager-change carries.
FieldTypeDescription
windowsWindowManagerEntry[]the open windows, in the order they opened
activestringthe id of the window in front, '' when none is
WindowManagerEntry
One window as the manager publishes it.
FieldTypeDescription
idstringthe window's id (the runtime gives one to a window without)
titlestringits title (the .window-title text)
iconstringthe Lucide name of its .window-icon, '' when it has none or another kind of icon
glyphstringthe data-glyph of its .window-icon (a Desktop glyph that follows the look), '' when it has none
statestringits Window state: default, maximized, minimized or closed
activebooleanwhether it is the window in front

§CSS view file

/* -- Window Manager component -------------------------------------
   The area one desktop's windows live in. It adds no chrome of its own: the
   windows are Window components, a taskbar renders the manager's model. With
   a taskbar bound (data-taskbar, set by the Taskbar) a minimized window leaves
   the desktop for its taskbar button instead of rolling up to its title bar. */
@layer components {
  .window-manager {
    position: relative;
    isolation: isolate;
    overflow: hidden;
  }
  .window-manager[data-taskbar] .window[data-minimized] {
    display: none;
  }
  /* -- drawn scroll bars (data-scrollbars="virtual") ---------------------------------------------------------
     The runtime lays a bar over each scrolling area of a window, in a layer appended to the window; the native bar
     is hidden and the area's padding keeps the room. These rules are the structure and a thin modern bar; a look
     (desktop.css) restyles the parts: --window-scrollbar-size, the buttons (shown by giving them a size), the track,
     the thumb, the corner; --window-scrollbar-inset on an area keeps the bar inside a frame drawn on it. */
  .window-manager[data-scrollbars="virtual"] .window [data-drawn-scroll] {
    scrollbar-width: none;
    &::-webkit-scrollbar {
      display: none;
    }
  }
  .window-manager-scrollbars {
    position: absolute;
    inset: 0;
    z-index: 3;
    pointer-events: none;
    --window-scrollbar-size: 10px;
  }
  .window-manager-scrollbar {
    position: absolute;
    display: flex;
    box-sizing: border-box;
    pointer-events: auto;
    touch-action: none;
    user-select: none;
    &[data-axis="y"] {
      flex-direction: column;
      width: var(--window-scrollbar-size);
    }
    &[data-axis="x"] {
      height: var(--window-scrollbar-size);
    }
    &[hidden] {
      display: none;
    }
  }
  .window-manager-scrollbar-track {
    position: relative;
    flex: 1;
    min-width: 0;
    min-height: 0;
  }
  .window-manager-scrollbar-thumb {
    position: absolute;
    inset: 0;
    box-sizing: border-box;
    border-radius: 999px;
    background: color-mix(in oklch, var(--muted-foreground) 45%, transparent);
    background-clip: content-box;
    border: 2px solid transparent;
    [data-axis="y"] > .window-manager-scrollbar-track > & {
      bottom: auto;
    }
    [data-axis="x"] > .window-manager-scrollbar-track > & {
      right: auto;
    }
    &:hover,
    &[data-pressed] {
      background-color: color-mix(in oklch, var(--muted-foreground) 75%, transparent);
    }
  }
  /* buttons take no room until a look gives them a size */
  .window-manager-scrollbar-button {
    flex: none;
    display: grid;
    place-items: center;
    box-sizing: border-box;
    width: 0;
    height: 0;
    overflow: hidden;
    &::before {
      content: "";
      width: 8px;
      height: 8px;
      background: currentColor;
      mask: center / contain no-repeat;
    }
    [data-axis="y"] > &[data-step="-1"]::before {
      mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8' shape-rendering='crispEdges'%3E%3Cpath d='M4 2L7 6H1z'/%3E%3C/svg%3E");
    }
    [data-axis="y"] > &[data-step="1"]::before {
      mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8' shape-rendering='crispEdges'%3E%3Cpath d='M1 2h6L4 6z'/%3E%3C/svg%3E");
    }
    [data-axis="x"] > &[data-step="-1"]::before {
      mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8' shape-rendering='crispEdges'%3E%3Cpath d='M6 1v6L2 4z'/%3E%3C/svg%3E");
    }
    [data-axis="x"] > &[data-step="1"]::before {
      mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8' shape-rendering='crispEdges'%3E%3Cpath d='M2 1l4 3-4 3z'/%3E%3C/svg%3E");
    }
  }
  .window-manager-scrollbar-corner {
    position: absolute;
    width: var(--window-scrollbar-size);
    height: var(--window-scrollbar-size);
    &[hidden] {
      display: none;
    }
  }
}
@media (forced-colors: active) {
  @layer components {
    .window-manager-scrollbar-thumb {
      background: ButtonText;
    }
    .window-manager-scrollbar-button::before {
      background: ButtonText;
    }
  }
}

§JavaScript view file

One observer per manager builds the model; every change to a window goes through df$.shadcn.windowApi / df$.shadcn.win.

// -- Window Manager -----------------------------------------------
// The model of one desktop's windows: which windows it holds, in the order
// they opened, which one is in front, which are minimized - published as one
// event (`window-manager-change`) that a taskbar (or anything else) renders,
// plus the commands a desktop needs (bring to front or minimize from a
// taskbar button, show the desktop, cascade, tile). It never moves or styles
// a window itself: every window change goes through the Window component's
// State API and df$.shadcn.win, so Window stays usable without a manager
// (AGENTS.md "Compose, don't share state").
// VERIFIED: (window-manager.e2e) two managers on one page keep their own front window, and cascade / tile
// arrange their own windows only - a manager is one desktop's model, never the page's.
// 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;
/** One window as the manager publishes it. */
interface WindowManagerEntry {
  /** the window's id (the runtime gives one to a window without) */
  id: string;
  /** its title (the .window-title text) */
  title: string;
  /** the Lucide name of its .window-icon, '' when it has none or another kind of icon */
  icon: string;
  /** the data-glyph of its .window-icon (a Desktop glyph that follows the look), '' when it has none */
  glyph: string;
  /** its Window state: default, maximized, minimized or closed */
  state: string;
  /** whether it is the window in front */
  active: boolean;
}
/** What window-manager-change carries. */
interface WindowManagerChangeDetail {
  /** the open windows, in the order they opened */
  windows: WindowManagerEntry[];
  /** the id of the window in front, '' when none is */
  active: string;
}
const windowManagerStates = ['default', 'desktop'];
/** setState() configs per state - neither takes one. */
export interface WindowManagerStateConfigs {
  /** The windows as the reader left them (leaving 'desktop' brings back the ones it minimized). */
  default: {};
  /** Show the desktop: every open window minimized. */
  desktop: {};
}
const resolve = (target) =>
  typeof target === 'string' ? (dfDollar('#' + CSS.escape(target)).get(0) ?? dfDollar(target).get(0)) : target;
/** The manager a window belongs to (the nearest one around it). */
const managerOf = (w: Element): HTMLElement | null => w.closest('.window-manager');
/** A manager's own windows - not those of a manager nested inside it. */
const own = (m: HTMLElement): HTMLDialogElement[] =>
  dfDollar(m)
    .find<HTMLDialogElement>('dialog.window')
    .toArray()
    .filter((w) => managerOf(w) === m);
let seq = 0;
const stateOf = (w: HTMLDialogElement): string =>
  !w.open
    ? 'closed'
    : w.hasAttribute('data-minimized')
      ? 'minimized'
      : w.hasAttribute('data-maximized')
        ? 'maximized'
        : 'default';
/** The manager's open windows, in the order they opened (a window that closes and opens again goes last). */
function entries(m: HTMLElement): WindowManagerEntry[] {
  return own(m)
    .filter((w) => w.open && !w.hasAttribute('data-share-remote'))
    .sort((a, b) => (a._wmOpened ?? 0) - (b._wmOpened ?? 0))
    .map((w) => ({
      id: w.id,
      title: dfDollar(w).find('.window-title').get(0)?.textContent?.trim() ?? '',
      icon: dfDollar(w).find('.window-icon').attr('data-lucide') ?? '',
      glyph: dfDollar(w).find('.window-icon').attr('data-glyph') ?? '',
      state: stateOf(w),
      active: w.hasAttribute('data-active'),
    }));
}
/** Gives every window an id and a place in the opening order; publishes the model when it changed. */
function refresh(m: HTMLElement) {
  for (const w of own(m)) {
    if (!w.id) w.id = `window-${Math.random().toString(36).slice(2, 8)}`;
    if (w.open && !w._wmWasOpen) w._wmOpened = ++seq;
    w._wmWasOpen = w.open;
  }
  const windows = entries(m);
  const active = windows.find((e) => e.active && e.state !== 'minimized')?.id ?? '';
  const key = JSON.stringify([windows, active]);
  if (key === m._wmKey) return;
  m._wmKey = key;
  // the desktop state ends when a window shows again
  if (m.dataset.stateName === 'desktop' && windows.some((e) => e.state !== 'minimized'))
    m.dataset.stateName = 'default';
  // Fires when the manager's windows change - one opened, closed, came to the front, was minimized or restored, or renamed.
  m.dispatchEvent(
    new CustomEvent<WindowManagerChangeDetail>('window-manager-change', { bubbles: true, detail: { windows, active } }),
  );
}
const later = (m: HTMLElement) => {
  if (m._wmQueued) return;
  m._wmQueued = true;
  queueMicrotask(() => {
    m._wmQueued = false;
    refresh(m);
    if (m.dataset.scrollbars === 'virtual') requestAnimationFrame(() => drawScrollbars(m));
  });
};
const win = () => df$.win;
const winApi = () => df$.windowApi;
/** The markup of a state: the manager element itself - its windows are their own components. */
function applyMarkup(el, stateName) {
  dfDollar(el).attr('data-desktop-shown', stateName === 'desktop' ? '' : null);
}
/** UI side of setState: 'desktop' minimizes every open window and remembers them; 'default' brings them back. */
function triggerStateChange(m, stateName) {
  if (stateName === 'desktop') {
    m._wmShown = entries(m)
      .filter((e) => e.state !== 'minimized')
      .map((e) => e.id);
    for (const id of m._wmShown) winApi()?.setState(byId(id), 'minimized', {});
  } else if (m._wmShown) {
    for (const id of m._wmShown) {
      const w = byId(id) as HTMLDialogElement | null;
      if (w?.open && w.hasAttribute('data-minimized')) winApi()?.setState(w, 'default', {});
    }
    m._wmShown = null;
  }
  m.dataset.stateName = stateName;
  applyMarkup(m, stateName);
}
/** Registry-level API; pass the .window-manager element explicitly. Unknown names throw. */
export const windowManagerApi = componentState({
  component: 'window-manager',
  states: windowManagerStates,
  apply: (m, state) => triggerStateChange(m, state.name),
  read: (m, state) => ({ name: m.dataset.stateName || 'default', config: state.config }),
  markup: (el, state) => applyMarkup(el, state.name),
});
df$.windowManagerApi = windowManagerApi;
df$.windowManagerStates = windowManagerStates;
/**
 * The windows of a manager, in the order they opened.
 * @param target - the .window-manager element, its id or a selector
 * @returns its open windows (an empty list when the target matches none)
 */
const windows = (target: string | HTMLElement): WindowManagerEntry[] => {
  const m = resolve(target);
  return m ? entries(m) : [];
};
/**
 * The window in front.
 * @param target - the .window-manager element, its id or a selector
 * @returns the active window that is not minimized, undefined when none is
 */
const active = (target: string | HTMLElement): HTMLDialogElement | undefined => {
  const m = resolve(target);
  return m
    ? own(m).find((w) => w.open && w.hasAttribute('data-active') && !w.hasAttribute('data-minimized'))
    : undefined;
};
/**
 * What a taskbar button does: a minimized window comes back to the front, the
 * window in front is minimized, any other comes to the front.
 * @param target - the .window element, its id or a selector
 * @returns the window's state afterwards, '' when the target matches none
 */
const toggle = (target: string | HTMLElement): string => {
  const w = resolve(target) as HTMLDialogElement | null;
  if (!w) return '';
  const m = managerOf(w);
  if (w.hasAttribute('data-minimized')) winApi()?.setState(w, w._wmMaximized ? 'maximized' : 'default', {});
  else if (m && active(m) === w) {
    w._wmMaximized = w.hasAttribute('data-maximized');
    winApi()?.setState(w, 'minimized', {});
  } else win()?.focus(w);
  return stateOf(w);
};
/**
 * Show the desktop (every window minimized), or bring the windows back when it shows.
 * @param target - the .window-manager element, its id or a selector
 * @returns whether the desktop shows now
 */
const showDesktop = (target: string | HTMLElement): boolean => {
  const m = resolve(target);
  if (!m) return false;
  const showing = m.dataset.stateName === 'desktop';
  windowManagerApi.setState(m, showing ? 'default' : 'desktop', {});
  return !showing;
};
/**
 * Steps the windows diagonally from the top left - df$.shadcn.win.cascade inside this manager.
 * @param target - the .window-manager element, its id or a selector
 * @param step - px between two windows (default 28)
 */
const cascade = (target: string | HTMLElement, step: number = 28): void => {
  const m = resolve(target);
  if (m) win()?.cascade(m, step);
};
/**
 * Lays the windows side by side in a grid - df$.shadcn.win.tile inside this manager.
 * @param target - the .window-manager element, its id or a selector
 */
const tile = (target: string | HTMLElement): void => {
  const m = resolve(target);
  if (m) win()?.tile(m);
};
/** df$.shadcn.windowManager - the windows of a desktop and what a desktop does with them. */
export const windowManagerActions = { windows, active, toggle, showDesktop, cascade, tile };
df$.windowManager = windowManagerActions;
// -- Across browser windows (data-share) ----------------------------------------------------------------------------
// Every browser window that shows the same page with the same data-share name is one desktop: a window dragged over
// another browser window shows there while it moves (the part beyond this one's edge), and the browser window it is
// dropped on takes it - opens its own copy (same id) at that place with the same size and field values, and this one
// closes. The browser windows talk over a BroadcastChannel and place windows in SCREEN coordinates; a page loaded in
// each is all it needs, no server. Dropped where no browser window takes it, the window comes back inside.
// VERIFIED: (window-manager.e2e "across browser windows") two Chromium windows side by side hand a window over.
/** Where this viewport's top-left corner is on the screen, in CSS px. */
let calibrated: { x: number; y: number; sx: number; sy: number } | null = null;
// a pointer event knows the exact offset (screen - client); kept relative to the window position, so a moved browser
// window stays right until the next pointer event measures it again
addEventListener(
  'pointermove',
  (e) => (calibrated = { x: e.screenX - e.clientX, y: e.screenY - e.clientY, sx: screenX, sy: screenY }),
  { capture: true, passive: true },
);
const viewportOrigin = () =>
  calibrated
    ? { x: calibrated.x + screenX - calibrated.sx, y: calibrated.y + screenY - calibrated.sy }
    : // before any pointer event: the browser's frame estimated (the toolbars above, equal borders at the sides)
      { x: screenX + (outerWidth - innerWidth) / 2, y: screenY + outerHeight - innerHeight };
interface ScreenBox {
  x: number;
  y: number;
  w: number;
  h: number;
}
const screenBox = (el: Element): ScreenBox => {
  const r = el.getBoundingClientRect();
  const o = viewportOrigin();
  return { x: o.x + r.left, y: o.y + r.top, w: r.width, h: r.height };
};
const inside = (b: ScreenBox, p: { x: number; y: number }) =>
  p.x >= b.x && p.x < b.x + b.w && p.y >= b.y && p.y < b.y + b.h;
const overlaps = (a: ScreenBox, b: ScreenBox) =>
  a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h;
/** This page among the browser windows (a message from itself is ignored). */
const PEER = Math.random().toString(36).slice(2);
/** The values of a window's fields, in document order - the text in a Notepad goes along. */
const fieldsOf = (w: HTMLElement) =>
  dfDollar(w)
    .find<HTMLInputElement>('input, textarea, select')
    .toArray()
    .map((el) => (el.type === 'checkbox' || el.type === 'radio' ? el.checked : el.value));
const setFields = (w: HTMLElement, values: unknown[]) => {
  const els = dfDollar(w).find<HTMLInputElement>('input, textarea, select').toArray();
  if (els.length !== values.length) return;
  els.forEach((el, i) => {
    if (el.type === 'checkbox' || el.type === 'radio') el.checked = !!values[i];
    else el.value = String(values[i] ?? '');
  });
};
/** Shows a window where another browser window has it: placed in screen coordinates, sized like there. */
function place(m: HTMLElement, w: HTMLDialogElement, box: ScreenBox, bounded: boolean) {
  const desk = screenBox(m);
  win()?.resize(w, box.w, box.h);
  win()?.move(w, box.x - desk.x, box.y - desk.y, bounded);
}
/** A window only shown here while another browser window drags it goes away again. */
function dropRemote(w: HTMLDialogElement) {
  if (!w.hasAttribute('data-share-remote')) return;
  w.removeAttribute('data-share-remote');
  w.inert = false;
  win()?.close(w);
}
function share(m: HTMLElement) {
  let channel: BroadcastChannel;
  try {
    channel = new BroadcastChannel('defuss-shadcn:window-manager:' + m.dataset.share);
  } catch {
    return; // an opaque origin (a sandboxed frame) has no channel: the desktop stays in this browser window
  }
  const post = (msg: Record<string, unknown>) => channel.postMessage({ ...msg, from: PEER });
  const byIdHere = (id: string) => own(m).find((w) => w.id === id);
  let last = { x: 0, y: 0 };
  let dragged = '';
  let frame = 0;
  // this browser window drags: the others follow the window's place on the screen
  m.addEventListener('pointermove', (e) => {
    const w = (e.target as Element).closest?.('dialog.window[data-dragging]') as HTMLDialogElement | null;
    if (!w || managerOf(w) !== m) return;
    last = { x: e.screenX, y: e.screenY };
    dragged = w.id;
    if (frame) return;
    frame = requestAnimationFrame(() => {
      frame = 0;
      post({ type: 'move', id: w.id, box: screenBox(w), desk: screenBox(m) });
    });
  });
  m.addEventListener('window-move', (e) => {
    const w = e.target as HTMLDialogElement;
    if (w.id !== dragged || managerOf(w) !== m) return;
    dragged = '';
    cancelAnimationFrame(frame);
    frame = 0;
    const desk = screenBox(m);
    post({ type: 'drop', id: w.id, box: screenBox(w), desk, point: last, fields: fieldsOf(w) });
    if (inside(desk, last)) return;
    // dropped outside this browser window: wait for one to take it, else bring it back inside
    clearTimeout(w._shareWait);
    w._shareWait = setTimeout(() => win()?.move(w, w.offsetLeft, w.offsetTop), 400);
  });
  channel.onmessage = ({ data }) => {
    if (!data || data.from === PEER) return;
    const w = byIdHere(data.id);
    if (!w) return; // a window this page does not hold is not handed over
    if (data.type === 'take') {
      if (data.to !== PEER) return;
      clearTimeout(w._shareWait);
      w.removeAttribute('data-dragging');
      win()?.close(w);
      return;
    }
    const desk = screenBox(m);
    const openHere = w.open && !w.hasAttribute('data-share-remote');
    if (data.type === 'move') {
      if (openHere) return; // already open here: it moves only when it is dropped here
      if (!overlaps(desk, data.box)) return dropRemote(w);
      if (!w.open) {
        w.setAttribute('data-share-remote', '');
        w.inert = true;
        win()?.open(w);
      }
      place(m, w, data.box, false);
      return;
    }
    if (data.type === 'drop') {
      const mine = inside(desk, data.point) && !inside(data.desk, data.point);
      if (!mine) return dropRemote(w);
      w.removeAttribute('data-share-remote');
      w.inert = false;
      if (!w.open) win()?.open(w);
      place(m, w, data.box, true);
      setFields(w, data.fields ?? []);
      win()?.focus(w);
      later(m);
      channel.postMessage({ type: 'take', id: w.id, to: data.from, from: PEER });
    }
  };
}
// -- Drawn scroll bars (data-scrollbars="virtual") ------------------------------------------------------------------
// A native scroll bar cannot look like a period one in every browser (Firefox and Safari style next to nothing of
// it), so a manager with data-scrollbars="virtual" draws its own over every scrolling area of its windows: arrow
// buttons, a track and a thumb in a layer appended to the window, the native bar hidden, room for the drawn one
// kept by the area's own padding. The area still scrolls natively (wheel, keys, touch, selection); the drawn bar
// only follows it and drives it - buttons step 16px, the track pages, the thumb drags, all repeating while held.
// The look styles the parts (window-manager.css: a thin modern bar; desktop.css: the 9x, XP and 7 bars).
// VERIFIED: (window-manager.e2e "drawn scroll bars") the thumb follows and drives the scroll, buttons and track step.
/** The places in a window that may scroll: the body, two levels inside it, any text area. */
const SCROLLER_SEL = '.window-body, .window-body > *, .window-body > * > *, textarea';
const scrolls = (v: string) => v === 'auto' || v === 'scroll';
interface DrawnBar {
  el: HTMLElement;
  track: HTMLElement;
  thumb: HTMLElement;
}
interface DrawnScroll {
  y: DrawnBar;
  x: DrawnBar;
  corner: HTMLElement;
  pad: { end: string; bottom: string };
}
const span = (cls: string) => {
  const el = document.createElement('span');
  el.className = cls;
  return el;
};
/** One bar: [button][track [thumb]][button]. */
function makeBar(s: HTMLElement, axis: 'x' | 'y'): DrawnBar {
  const el = span('window-manager-scrollbar');
  el.dataset.axis = axis;
  const dec = span('window-manager-scrollbar-button');
  dec.dataset.step = '-1';
  const inc = span('window-manager-scrollbar-button');
  inc.dataset.step = '1';
  const track = span('window-manager-scrollbar-track');
  const thumb = span('window-manager-scrollbar-thumb');
  track.append(thumb);
  el.append(dec, track, inc);
  const pos = axis === 'y' ? 'scrollTop' : 'scrollLeft';
  // held: step now, again after 300 ms, then every 50 ms (a track press pages until the thumb reaches the pointer)
  const hold = (e: PointerEvent, step: () => boolean | void) => {
    e.preventDefault();
    const part = e.currentTarget as HTMLElement;
    part.setPointerCapture(e.pointerId);
    part.dataset.pressed = '';
    let timer = 0;
    const stop = () => {
      clearTimeout(timer);
      clearInterval(timer);
      delete part.dataset.pressed;
      part.removeEventListener('pointerup', stop);
      part.removeEventListener('pointercancel', stop);
    };
    part.addEventListener('pointerup', stop);
    part.addEventListener('pointercancel', stop);
    if (step() === false) return;
    timer = setTimeout(() => {
      timer = setInterval(() => step() === false && stop(), 50) as unknown as number;
    }, 300) as unknown as number;
  };
  for (const b of [dec, inc])
    b.addEventListener('pointerdown', (e) => hold(e, () => void (s[pos] += Number(b.dataset.step) * 16)));
  track.addEventListener('pointerdown', (e) => {
    if (e.target === thumb) return;
    const at = axis === 'y' ? e.clientY : e.clientX;
    hold(e, () => {
      const r = thumb.getBoundingClientRect();
      const [from, to] = axis === 'y' ? [r.top, r.bottom] : [r.left, r.right];
      if (at >= from && at <= to) return false;
      const page = axis === 'y' ? s.clientHeight : s.clientWidth;
      s[pos] += (at < from ? -1 : 1) * page;
    });
  });
  thumb.addEventListener('pointerdown', (e) => {
    e.preventDefault();
    thumb.setPointerCapture(e.pointerId);
    thumb.dataset.pressed = '';
    const start = axis === 'y' ? e.clientY : e.clientX;
    const was = s[pos];
    const [size, client, length] =
      axis === 'y'
        ? [s.scrollHeight, s.clientHeight, track.clientHeight - thumb.offsetHeight]
        : [s.scrollWidth, s.clientWidth, track.clientWidth - thumb.offsetWidth];
    const move = (m: PointerEvent) => {
      const d = (axis === 'y' ? m.clientY : m.clientX) - start;
      s[pos] = was + (d * (size - client)) / Math.max(1, length);
    };
    const up = () => {
      delete thumb.dataset.pressed;
      thumb.removeEventListener('pointermove', move);
      thumb.removeEventListener('pointerup', up);
      thumb.removeEventListener('pointercancel', up);
    };
    thumb.addEventListener('pointermove', move);
    thumb.addEventListener('pointerup', up);
    thumb.addEventListener('pointercancel', up);
  });
  return { el, track, thumb };
}
/** The thumb's length and place on one axis. */
function placeThumb(s: HTMLElement, bar: DrawnBar, axis: 'x' | 'y') {
  const [size, client, at] =
    axis === 'y' ? [s.scrollHeight, s.clientHeight, s.scrollTop] : [s.scrollWidth, s.clientWidth, s.scrollLeft];
  const length = axis === 'y' ? bar.track.clientHeight : bar.track.clientWidth;
  const thumb = Math.max(Math.min(length, 12), Math.round((length * client) / Math.max(size, 1)));
  const offset = size > client ? Math.round(((length - thumb) * at) / (size - client)) : 0;
  const [lengthProp, offsetProp] = axis === 'y' ? ['height', 'top'] : ['width', 'left'];
  bar.thumb.style[lengthProp] = thumb + 'px';
  bar.thumb.style[offsetProp] = offset + 'px';
}
/**
 * Where an element sits inside the window's padding box (the drawn layer's frame), from layout offsets - unlike a
 * client rect, these ignore a transform, so a window still scaling in while it opens places its bars right.
 */
function offsetIn(el: HTMLElement, w: HTMLElement): { x: number; y: number } {
  let x = 0;
  let y = 0;
  let n: HTMLElement | null = el;
  while (n && n !== w) {
    x += n.offsetLeft;
    y += n.offsetTop;
    const p = n.offsetParent as HTMLElement | null;
    if (p && p !== w) {
      x += p.clientLeft - p.scrollLeft;
      y += p.clientTop - p.scrollTop;
    }
    n = p;
  }
  return { x, y };
}
/** Lays a scrolling area's drawn bars over it: which bars it needs, the room they take, their place in the window. */
function layoutScroll(w: HTMLElement, s: HTMLElement) {
  const d: DrawnScroll = s._drawnScroll;
  if (!s.getClientRects().length) {
    d.y.el.hidden = d.x.el.hidden = d.corner.hidden = true; // not shown (a closed view): nothing to draw
    return;
  }
  const cs = getComputedStyle(s);
  const inset = parseFloat(cs.getPropertyValue('--window-scrollbar-inset')) || 0;
  // the look's thickness (the bar's CSS width - a hidden bar has no box to measure)
  const thick = parseFloat(getComputedStyle(d.y.el).width) || 16;
  // the room first (it changes what overflows), then what overflows with it
  const wantY = scrolls(cs.overflowY) && s.scrollHeight > s.clientHeight + 1;
  const wantX = scrolls(cs.overflowX) && s.scrollWidth > s.clientWidth + 1;
  s.style.paddingInlineEnd = wantY ? 'calc(' + d.pad.end + ' + ' + (thick + inset) + 'px)' : '';
  s.style.paddingBlockEnd = wantX ? 'calc(' + d.pad.bottom + ' + ' + (thick + inset) + 'px)' : '';
  const needY = scrolls(cs.overflowY) && s.scrollHeight > s.clientHeight + 1;
  const needX = scrolls(cs.overflowX) && s.scrollWidth > s.clientWidth + 1;
  if (needY !== wantY || needX !== wantX) {
    s.style.paddingInlineEnd = needY ? 'calc(' + d.pad.end + ' + ' + (thick + inset) + 'px)' : '';
    s.style.paddingBlockEnd = needX ? 'calc(' + d.pad.bottom + ' + ' + (thick + inset) + 'px)' : '';
  }
  const { x: left, y: top } = offsetIn(s, w);
  const sr = { width: s.offsetWidth, height: s.offsetHeight };
  d.y.el.hidden = !needY;
  d.x.el.hidden = !needX;
  d.corner.hidden = !needX || !needY;
  const both = needX && needY ? thick : 0;
  Object.assign(d.y.el.style, {
    left: left + sr.width - inset - thick + 'px',
    top: top + inset + 'px',
    height: sr.height - 2 * inset - both + 'px',
  });
  Object.assign(d.x.el.style, {
    left: left + inset + 'px',
    top: top + sr.height - inset - thick + 'px',
    width: sr.width - 2 * inset - both + 'px',
  });
  Object.assign(d.corner.style, {
    left: left + sr.width - inset - thick + 'px',
    top: top + sr.height - inset - thick + 'px',
  });
  if (needY) placeThumb(s, d.y, 'y');
  if (needX) placeThumb(s, d.x, 'x');
}
/** Gives every scrolling area of a manager's open windows its drawn bars (once) and lays them out. */
function drawScrollbars(m: HTMLElement) {
  for (const w of own(m)) {
    if (!w.open) continue;
    for (const s of dfDollar(w).find<HTMLElement>(SCROLLER_SEL).toArray()) {
      if (s.closest('.window-manager-scrollbars, .terminal') || s._drawnScroll === false) continue;
      if (!s._drawnScroll) {
        const cs = getComputedStyle(s);
        if (!scrolls(cs.overflowY) && !scrolls(cs.overflowX)) {
          s._drawnScroll = false; // never scrolls: not looked at again
          continue;
        }
        let layer = dfDollar(w).children('.window-manager-scrollbars').get(0) as HTMLElement | undefined;
        if (!layer) {
          layer = span('window-manager-scrollbars');
          layer.setAttribute('aria-hidden', 'true');
          w.append(layer);
        }
        const d: DrawnScroll = {
          y: makeBar(s, 'y'),
          x: makeBar(s, 'x'),
          corner: span('window-manager-scrollbar-corner'),
          pad: { end: cs.paddingInlineEnd, bottom: cs.paddingBlockEnd },
        };
        layer.append(d.y.el, d.x.el, d.corner);
        s._drawnScroll = d;
        s.setAttribute('data-drawn-scroll', '');
        let frame = 0;
        const follow = () => {
          if (frame) return;
          frame = requestAnimationFrame(() => {
            frame = 0;
            layoutScroll(w, s);
          });
        };
        s.addEventListener('scroll', follow, { passive: true });
        s.addEventListener('input', follow);
        new ResizeObserver(follow).observe(s);
        // the window resized, finished its opening animation, the area's content changed (a folder got an icon)
        new ResizeObserver(follow).observe(w);
        w.addEventListener('transitionend', follow);
        w.addEventListener('animationend', follow);
        new MutationObserver(follow).observe(s, { childList: true, subtree: true, characterData: true });
      }
      layoutScroll(w, s);
    }
  }
}
function init() {
  dfDollar('.window-manager:not([data-init])')
    .toArray()
    .forEach((m) => {
      m.dataset.init = '';
      m.dataset.stateName = m.hasAttribute('data-desktop-shown') ? 'desktop' : 'default';
      // el.store + el.api (AGENTS.md "State through stores")
      bindComponent(m, windowManagerApi);
      // whatever changes a window - its state, its title, the front - shows in its attributes or its text
      new MutationObserver(() => later(m)).observe(m, {
        subtree: true,
        childList: true,
        characterData: true,
        attributes: true,
        attributeFilter: ['open', 'data-active', 'data-minimized', 'data-maximized', 'id'],
      });
      // close does not bubble: listen on the way down
      m.addEventListener('close', () => later(m), true);
      if (m.dataset.share) share(m);
      later(m);
    });
}
init();
new MutationObserver(init).observe(document, { childList: true, subtree: true });

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