Profile menu
The account menu behind an avatar: switch workspace, theme, shortcuts and sign out. Free and MIT licensed, as HTML, a typed React component or an Astro component, in three styles with light and dark mode.
Need this designed into your product? Book a call
- ↑↓
- Move through the menu
- HomeEnd
- First or last item
- Esc
- Close the menu
- ?
- Show these shortcuts
Install
Add it to your project with the CLI.
HTML, CSS and JS
npx designme add profile-menuReact
npx designme add profile-menu --reactAstro
npx designme add profile-menu --astroshadcn, React
npx shadcn@latest add https://designme.dev/r/shadcn/profile-menu.json shadcn, Astro
npx shadcn@latest add https://designme.dev/r/shadcn/astro/profile-menu.json The CLI copies the source into your project, so you own it and can change anything. Where each version lands, what it needs and the shadcn theme bridge: Installation.
About
What it is for and what it does.
Profile menu is the account menu that opens from an avatar in an app's top bar. It shows who is signed in, lists the workspaces to switch between, and holds a Theme row (System, Light or Dark), a Keyboard shortcuts row with its key, and Sign out. It is a real menu: the arrow keys move through it, Escape closes it and puts the focus back on the avatar.
- When people belong to more than one workspace and switch between them from anywhere in the app.
- When the account's settings that apply everywhere, like the theme, should sit one click from every page.
- When the app has keyboard shortcuts and people need a place to find them.
- When the top bar has room for an avatar but not for a row of account buttons.
- The menu opens under the avatar, lined up with its right edge, and starts with the person's name and email. It opens over the room the component keeps for it under the bar, so the bar never moves as it opens and closes, and the menu is never cut off.
- The workspaces are a group of radio items, each with its tile, a name and a quiet
detaillike "Free, 3 members". The tile is the workspace's initial on itstint, one of the avatars' fills with its own ink (white on blue, violet, red and pink); in Studio every tile is grey. The current one is checked; picking another closes the menu and the bar crossfades to its name. - The Theme row shows its label and a small three-way choice in the row, three icons on the segmented control's grey track: a monitor for System, a sun for Light and the moon for Dark, each named by a tooltip, with the knob sliding to the pick. System follows the device. The menu stays open after a pick, so the change shows where it was made. It reports the pick through
onThemeChange; applying the theme is up to you. - Keyboard shortcuts shows its key, ?, and opens a short list under the bar. Pressing ? anywhere in the component opens and closes the same list. By default it lists the keys the menu itself answers to.
- Sign out swaps the avatar for a Sign in button, which swaps it back.
notesays what just changed, like "Switched to Acme Labs", to screen readers only: the bar and the menu already show it, so there is no line of text under the bar.
- The avatar is a button with
aria-haspopup="menu"andaria-expanded, labelled "Account menu" and the person's name. - The menu has
role="menu"and is named by the name and email at its top. The workspaces aremenuitemradioitems in a group named "Workspaces"; the Theme row is a group of threemenuitemradioicon choices, each named by itsaria-label(System, Light, Dark), with the picked one checked; the rest aremenuitems. - Enter, Space or the down arrow on the avatar opens the menu on its first item, and the up arrow on its last. Inside, the up and down arrows move and wrap (stopping once on the Theme row, where Left and Right move between its choices), Home and End jump to the ends, Escape closes it and gives the focus back to the avatar, and Tab closes it and moves on.
noteis a polite live region, so a switch or a theme change is announced.
Usage
Import it in React and drive it from your own state, or place it in an Astro page.
React
import { ProfileMenu } from '@/components/designme/profile-menu/ProfileMenu';React example
The demo above as a React component, 41 lines you can copy.
'use client';
// The animated preview from designme.dev, rebuilt from the React component: an example of driving it from your own state.
import { useRef, useState } from 'react';
import { ProfileMenu, type ProfileMenuTheme, type ProfileMenuWorkspace } from './ProfileMenu';
import { useStory } from '../lib/useScript';
/* ---------- Profile menu: open it, switch to Acme Labs, then open it again and pick the Dark theme ---------- */
const WORKSPACES: ProfileMenuWorkspace[] = [
{ id: 'northwind', name: 'Northwind', detail: 'Pro, 12 members', tint: 'pb' },
{ id: 'acme', name: 'Acme Labs', detail: 'Free, 3 members', tint: 'pk' },
{ id: 'personal', name: 'Personal', detail: 'Just you', tint: 'pl' }
];
export default function ProfileMenuDemo() {
const ref = useRef<HTMLDivElement>(null);
const [workspace, setWorkspace] = useState('northwind');
// the theme row starts from the page's theme (System when it follows the device); apply it to your own app in onThemeChange
const [theme, setTheme] = useState<ProfileMenuTheme>(() => { const t = typeof document !== 'undefined' ? document.documentElement.dataset.theme : undefined; return t === 'dark' || t === 'light' ? t : 'system'; });
const [signedIn, setSignedIn] = useState(true);
const [note, setNote] = useState<string>();
// the preview's story: open the menu, switch to Acme Labs, then open it again and pick the Dark theme
useStory(ref, async ({ wait, press }) => {
await wait(1500); press('.dm-pfm-tr');
await wait(3000); press('.dm-mi[role="menuitemradio"]:nth-of-type(2)');
await wait(2500); press('.dm-pfm-tr');
await wait(1500); press('.dm-pfm-tho:nth-of-type(3)');
await wait(1800); press('.dm-pfm-tr');
});
return (
<div ref={ref} style={{ width: '100%' }}>
<ProfileMenu user={{ name: 'Maya Kim', email: 'maya@northwind.studio', color: 'var(--dm-av-l)' }} workspaces={WORKSPACES} context="Pricing refresh"
workspace={workspace} onWorkspaceChange={id => { if (id !== workspace) setNote(`Switched to ${WORKSPACES.find(w => w.id === id)!.name}`); setWorkspace(id); }}
theme={theme} onThemeChange={t => { setTheme(t); setNote(`Theme set to ${t === 'system' ? 'System' : t === 'light' ? 'Light' : 'Dark'}`); }}
signedIn={signedIn} onSignedInChange={s => { setSignedIn(s); setNote(s ? 'Signed in as Maya Kim' : `Signed out of ${WORKSPACES.find(w => w.id === workspace)!.name}`); }}
note={note} />
</div>
);
}
Astro
In a page in src/pages. It plays the demo above; change its profile-menu.js to show your own data. Attributes like class go on its root element.
---
import ProfileMenu from '../components/designme/profile-menu/ProfileMenu.astro';
---
<ProfileMenu />
<ProfileMenu data-style="soft" class="my-class" />Props
Everything ProfileMenu takes.
| Prop | Type | What it does |
|---|---|---|
userrequired | { name: string; email: string; initials?: string; color?: string } | The person signed in. `color` is the avatar's colour, like 'var(--dm-av-l)' |
workspacesrequired | ProfileMenuWorkspace[] | |
workspace | string | The current workspace's id. Leave it out to let the menu switch it |
defaultWorkspace | string | |
onWorkspaceChange | (id: string) => void | |
context | ReactNode | The quiet line under the workspace name in the bar, like the page you're on |
theme | ProfileMenuTheme | The theme row's three-way choice: System, Light or Dark. It only reports the change: apply the theme in `onThemeChange` |
defaultTheme | ProfileMenuTheme | |
onThemeChange | (theme: ProfileMenuTheme) => void | |
themeLabel | string | Defaults to "Theme" |
shortcuts | ProfileMenuShortcut[] | The list Keyboard shortcuts opens. Defaults to the keys this menu answers to |
shortcutsOpen | boolean | Whether that list is open. Keyboard shortcuts, or ? anywhere in the component, opens it |
defaultShortcutsOpen | boolean | |
onShortcutsOpenChange | (open: boolean) => void | |
signedIn | boolean | Sign out swaps the avatar for a Sign in button, which swaps it back |
defaultSignedIn | boolean | |
onSignedInChange | (signedIn: boolean) => void | |
note | string | What just changed, like "Switched to Acme Labs", said to screen readers (a polite live region). The bar and the menu already show it, so it is not a line on screen |
open | boolean | Whether the menu is open. Leave it out to let the avatar, Escape and a click outside open and close it |
defaultOpen | boolean | |
onOpenChange | (open: boolean) => void | |
className | string |
Code
The full source, as the CLI installs it.
ProfileMenu.tsxReact · 205 lines
'use client';
import { useEffect, useId, useRef, useState, type CSSProperties, type KeyboardEvent, type MouseEvent, type ReactNode } from 'react';
import { cx } from '../lib/cx';
import { useControllable, useIsoLayoutEffect } from '../lib/hooks';
import { Icon, type IconName } from '../lib/icons';
import { avatarInk, Fold, Swap, Tip } from '../lib/motion';
import { usePopover } from '../lib/popover';
import '../designme.css';
// its menus' rows glide in Studio
import '../lib/glide';
import './profile-menu.css';
/** The colour of a workspace's tile: the avatars' fills (white letters on blue, violet, red and pink). Studio draws every tile grey */
export type ProfileMenuTint = 'pb' | 'pl' | 'pm' | 'pp' | 'pr' | 'py' | 'pk' | 'pt';
/** The theme the menu's Theme row offers: follow the device, or always light or dark */
export type ProfileMenuTheme = 'system' | 'light' | 'dark';
// each choice is an icon, named by its label (aria-label and tooltip): a monitor for System, a sun for Light, the moon for Dark
const THEMES: { value: ProfileMenuTheme; label: string; icon: IconName }[] = [{ value: 'system', label: 'System', icon: 'monitor' }, { value: 'light', label: 'Light', icon: 'sun' }, { value: 'dark', label: 'Dark', icon: 'moon' }];
/** One workspace the account belongs to */
export interface ProfileMenuWorkspace {
id: string;
/** Like "Acme Labs" */
name: string;
/** The quiet line under the name in the menu, like "Free, 3 members" */
detail?: string;
/** The letter in its tile. Defaults to the first letter of the name */
initial?: string;
/** The tile's tint. Grey when left out */
tint?: ProfileMenuTint;
}
/** A row in the shortcuts list: the keys, then what they do */
export interface ProfileMenuShortcut {
keys: string[];
label: string;
}
export interface ProfileMenuProps {
/** The person signed in. `color` is the avatar's colour, like 'var(--dm-av-l)' */
user: { name: string; email: string; initials?: string; color?: string };
workspaces: ProfileMenuWorkspace[];
/** The current workspace's id. Leave it out to let the menu switch it */
workspace?: string;
defaultWorkspace?: string;
onWorkspaceChange?: (id: string) => void;
/** The quiet line under the workspace name in the bar, like the page you're on */
context?: ReactNode;
/** The theme row's three-way choice: System, Light or Dark. It only reports the change: apply the theme in `onThemeChange` */
theme?: ProfileMenuTheme;
defaultTheme?: ProfileMenuTheme;
onThemeChange?: (theme: ProfileMenuTheme) => void;
/** Defaults to "Theme" */
themeLabel?: string;
/** The list Keyboard shortcuts opens. Defaults to the keys this menu answers to */
shortcuts?: ProfileMenuShortcut[];
/** Whether that list is open. Keyboard shortcuts, or ? anywhere in the component, opens it */
shortcutsOpen?: boolean;
defaultShortcutsOpen?: boolean;
onShortcutsOpenChange?: (open: boolean) => void;
/** Sign out swaps the avatar for a Sign in button, which swaps it back */
signedIn?: boolean;
defaultSignedIn?: boolean;
onSignedInChange?: (signedIn: boolean) => void;
/** What just changed, like "Switched to Acme Labs", said to screen readers (a polite live region). The bar and the menu
already show it, so it is not a line on screen */
note?: string;
/** Whether the menu is open. Leave it out to let the avatar, Escape and a click outside open and close it */
open?: boolean;
defaultOpen?: boolean;
onOpenChange?: (open: boolean) => void;
className?: string;
}
const SHORTCUTS: ProfileMenuShortcut[] = [
{ keys: ['↑', '↓'], label: 'Move through the menu' }, { keys: ['Home', 'End'], label: 'First or last item' },
{ keys: ['Esc'], label: 'Close the menu' }, { keys: ['?'], label: 'Show these shortcuts' }
];
/** The account menu behind an avatar: who is signed in, the workspaces to switch between, a Theme row (System, Light, Dark), keyboard shortcuts and Sign out. */
export function ProfileMenu({
user, workspaces, workspace, defaultWorkspace, onWorkspaceChange, context, theme, defaultTheme = 'system', onThemeChange, themeLabel = 'Theme',
shortcuts = SHORTCUTS, shortcutsOpen, defaultShortcutsOpen = false, onShortcutsOpenChange, signedIn, defaultSignedIn = true, onSignedInChange,
note, open, defaultOpen = false, onOpenChange, className
}: ProfileMenuProps) {
const [ws, setWs] = useControllable(workspace, defaultWorkspace ?? workspaces[0]?.id ?? '', onWorkspaceChange);
const [th, setTh] = useControllable(theme, defaultTheme, onThemeChange);
const [keysOpen, setKeysOpen] = useControllable(shortcutsOpen, defaultShortcutsOpen, onShortcutsOpenChange);
const [isIn, setIn] = useControllable(signedIn, defaultSignedIn, onSignedInChange);
// the menu opens downwards under the avatar, lined up with its right edge
const menu = usePopover({ align: 'end', side: 'down', open, defaultOpen, onOpenChange });
const pop = menu.pop.ref, trigger = menu.trigger.ref;
const signIn = useRef<HTMLButtonElement>(null), closeKeys = useRef<HTMLButtonElement>(null);
const id = useId();
const cur = workspaces.find(w => w.id === ws) ?? workspaces[0];
const initials = user.initials ?? user.name.split(' ').map(p => p[0]).join('').slice(0, 2).toUpperCase();
// where the focus goes once the menu has opened: the first or last item, or nowhere for a scripted click
const focusTo = useRef<'first' | 'last' | null>(null);
// the arrow keys stop once on the theme row, on its picked choice (or the one with the focus); Left and Right move between its three
const thRow = useRef<HTMLDivElement>(null);
const items = () => Array.from(pop.current?.querySelectorAll<HTMLElement>('[role^="menuitem"]') ?? []).filter(x => !x.classList.contains('dm-pfm-tho')
|| (thRow.current?.contains(document.activeElement) ? x === document.activeElement : x.getAttribute('aria-checked') === 'true'));
// the knob slides under the picked theme
const [knob, setKnob] = useState<CSSProperties>({});
useIsoLayoutEffect(() => {
const el = thRow.current; if (!el) return;
const place = () => { const b = el.querySelector<HTMLElement>('[aria-checked="true"]'); if (b && b.offsetWidth) setKnob({ left: b.offsetLeft, width: b.offsetWidth }); };
place(); const ro = new ResizeObserver(place); ro.observe(el); return () => ro.disconnect();
}, [th]);
useEffect(() => {
if (!menu.open || !focusTo.current) return;
const all = items(); (focusTo.current === 'last' ? all[all.length - 1] : all[0])?.focus(); focusTo.current = null;
}, [menu.open]); // eslint-disable-line react-hooks/exhaustive-deps
// closing it from inside gives the focus back to the avatar
const close = (soon = false) => { if (pop.current?.contains(document.activeElement)) trigger.current?.focus(); if (soon) menu.closeSoon(); else menu.close(); };
const onTrigger = (e: MouseEvent) => { if (!menu.open && e.nativeEvent.isTrusted) focusTo.current = 'first'; menu.trigger.onClick(); };
const onTriggerKey = (e: KeyboardEvent) => {
if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp') return;
e.preventDefault(); focusTo.current = e.key === 'ArrowUp' ? 'last' : 'first';
if (menu.open) { const all = items(); (focusTo.current === 'last' ? all[all.length - 1] : all[0])?.focus(); focusTo.current = null; } else menu.setOpen(true);
};
// inside the menu: the arrow keys move and wrap, Home and End jump to the ends, Tab leaves it (Escape is the popover's)
const onMenuKey = (e: KeyboardEvent) => {
const all = items(), i = all.indexOf(document.activeElement as HTMLElement);
const go = ({ ArrowDown: all[(i + 1) % all.length], ArrowUp: all[(i - 1 + all.length) % all.length], Home: all[0], End: all[all.length - 1] } as Record<string, HTMLElement | undefined>)[e.key];
const opts = Array.from(thRow.current?.querySelectorAll<HTMLElement>('.dm-pfm-tho') ?? []), t = opts.indexOf(document.activeElement as HTMLElement);
const side = ({ ArrowLeft: -1, ArrowRight: 1 } as Record<string, number>)[e.key];
if (go) { e.preventDefault(); go.focus(); } else if (t >= 0 && side) { e.preventDefault(); opts[(t + side + opts.length) % opts.length].focus(); } else if (e.key === 'Tab') setTimeout(() => menu.close());
};
const showKeys = (on: boolean) => setKeysOpen(on);
// the menu opens over the component from the avatar and never moves the bar: the component keeps room for it below the bar,
// so centred in a stage, the open menu still ends inside it
const bar = useRef<HTMLDivElement>(null);
const [room, setRoom] = useState<number>();
useEffect(() => {
const fit = () => { if (bar.current && pop.current) setRoom(Math.ceil(bar.current.offsetHeight + 6 + pop.current.offsetHeight)); };
fit(); const ro = new ResizeObserver(fit);
if (bar.current) ro.observe(bar.current); if (pop.current) ro.observe(pop.current);
return () => ro.disconnect();
}, []); // eslint-disable-line react-hooks/exhaustive-deps
return (
<div data-dm="" className={cx('dm-pfm', className)} style={room ? { minHeight: room } : undefined}
onKeyDown={e => { if (e.key === '?' && !(e.target as HTMLElement).matches('input,textarea')) { e.preventDefault(); menu.close(); showKeys(!keysOpen); } }}>
<div ref={bar} className="dm-pfm-bar dm-panel">
{cur && <span className="dm-pfm-lg" data-t={cur.tint}>{cur.initial ?? cur.name[0]}</span>}
<span className="dm-pfm-ws"><Swap className="dm-pfm-wn">{cur?.name ?? ''}</Swap>{context && <span className="dm-muted">{context}</span>}</span>
{isIn ? (
<button {...menu.trigger} onClick={onTrigger} onKeyDown={onTriggerKey} type="button" className="dm-pfm-tr" aria-label={`Account menu, ${user.name}`}>
<span className="dm-av" style={user.color ? { background: user.color, color: avatarInk(user.color) } : undefined}>{initials}</span><Icon name="chev-d" size="xs" />
</button>
) : (
<button ref={signIn} type="button" className="dm-pill dm-line dm-sm dm-pfm-in" onClick={() => { setIn(true); setTimeout(() => trigger.current?.focus()); }}>Sign in</button>
)}
</div>
<div {...menu.pop} className={cx(menu.pop.className, 'dm-pfm-pop')} role="menu" aria-labelledby={`${id}-n ${id}-e`} onKeyDown={onMenuKey}>
<div className="dm-pfm-me" role="none">
<span className="dm-av" style={user.color ? { background: user.color, color: avatarInk(user.color) } : undefined}>{initials}</span>
<span className="dm-t"><b id={`${id}-n`}>{user.name}</b><span className="dm-muted" id={`${id}-e`}>{user.email}</span></span>
</div>
<div className="dm-sep" role="separator" />
<div role="group" aria-labelledby={`${id}-w`}>
<div className="dm-ph" role="none" id={`${id}-w`}>Workspaces</div>
{workspaces.map(w => (
<button key={w.id} type="button" className="dm-mi" role="menuitemradio" aria-checked={w.id === cur?.id} tabIndex={-1} onClick={() => { setWs(w.id); close(true); }}>
<span className="dm-pfm-lg" data-t={w.tint}>{w.initial ?? w.name[0]}</span>
<span>{w.name}{w.detail && <span className="dm-d">{w.detail}</span>}</span>
<span className="dm-ck"><Icon name="check" size="xs" /></span>
</button>
))}
</div>
<div className="dm-sep" role="separator" />
{/* the theme row: its label, and a small three-way choice of icons on the segmented track; the menu stays open so the change shows */}
<div className="dm-pfm-th" role="group" aria-label={themeLabel}>
<Icon name="moon" /><span aria-hidden="true">{themeLabel}</span>
<span className="dm-seg2 dm-pfm-ths" ref={thRow}>
<span className="dm-knob" style={knob} />
{THEMES.map(o => <Tip key={o.value} label={o.label}><button type="button" className="dm-pfm-tho" role="menuitemradio" aria-checked={o.value === th} aria-label={o.label} tabIndex={-1} onClick={() => setTh(o.value)}><Icon name={o.icon} /></button></Tip>)}
</span>
</div>
<button type="button" className="dm-mi dm-pfm-ky" role="menuitem" tabIndex={-1} onClick={() => { const had = pop.current?.contains(document.activeElement); menu.close(); showKeys(true); if (had) setTimeout(() => closeKeys.current?.focus()); }}>
<Icon name="keyboard" /><span>Keyboard shortcuts</span><span className="dm-kbd" aria-hidden="true">?</span>
</button>
<div className="dm-sep" role="separator" />
<button type="button" className="dm-mi dm-pfm-out" role="menuitem" tabIndex={-1} onClick={() => { const had = pop.current?.contains(document.activeElement); menu.close(); setIn(false); if (had) setTimeout(() => signIn.current?.focus()); }}>
<Icon name="logout" /><span>Sign out</span>
</button>
</div>
<Fold open={keysOpen} className="dm-pfm-kf">
<div className="dm-pfm-keys dm-panel" role="region" aria-label="Keyboard shortcuts">
<div className="dm-pfm-kh"><b>Keyboard shortcuts</b>
<Tip label="Close"><button ref={closeKeys} type="button" className="dm-ib dm-pfm-kx" aria-label="Close shortcuts" onClick={() => { showKeys(false); trigger.current?.focus(); }}><Icon name="x" size="xs" /></button></Tip>
</div>
<dl className="dm-pfm-kl">
{shortcuts.map(s => <div key={s.label}><dt>{s.keys.map(k => <span key={k} className="dm-kbd">{k}</span>)}</dt><dd>{s.label}</dd></div>)}
</dl>
</div>
</Fold>
<p className="dm-pfm-note" aria-live="polite">{note}</p>
</div>
);
}
profile-menu.cssReact · 75 lines
/* Generated from designme.dev by scripts/sync.mjs. Edit the site, then sync. */
/* ---------- Profile menu ---------- */
/* an app's top bar with the account behind the avatar. The menu opens under it, lined up with its right edge, over the room
the component keeps for it under the bar, so the bar never moves as the menu opens and shuts (owner, 20 Nov: menus open over
the component from their trigger and never move it) and the menu is never cut off. The bar's content sits 16px in all round
in every style: the workspace's tile on the left, the avatar's trigger on the right. The trigger's box fills on hover and
while its menu is open, so the box itself is 16px from the bar's top, right and bottom (32px tall round the 26px avatar) */
.dm-pfm{position:relative;width:100%;max-width:400px;margin:0 auto;display:flex;flex-direction:column;gap:12px}
.dm-pfm-bar{display:flex;align-items:center;gap:12px;min-height:64px;padding:var(--dm-s-4);border-radius:var(--dm-r-card)}
/* a workspace's tile is its identity mark: in Soft and Blueprint a vivid fill with its own ink, the avatars' colours (white on
blue, violet, red and pink; 4.5:1 and APCA Lc 60); Studio keeps its marks monochrome */
.dm-pfm-lg{--dm-tb:var(--dm-chip);--dm-tc:var(--dm-fg2);width:28px;height:28px;border-radius:var(--dm-r-sm);display:grid;place-items:center;flex:none;font-size:12px;font-weight:500;background:var(--dm-tb);color:var(--dm-tc);transition:background var(--dm-t) var(--dm-ease),color var(--dm-t) var(--dm-ease)}
.dm-pfm-lg[data-t="pb"]{--dm-tb:var(--dm-av-b);--dm-tc:var(--dm-av-b-ink)}.dm-pfm-lg[data-t="pl"]{--dm-tb:var(--dm-av-l);--dm-tc:var(--dm-av-l-ink)}.dm-pfm-lg[data-t="pr"]{--dm-tb:var(--dm-av-r);--dm-tc:var(--dm-av-r-ink)}.dm-pfm-lg[data-t="pk"]{--dm-tb:var(--dm-av-k);--dm-tc:var(--dm-av-k-ink)}
.dm-pfm-lg[data-t="pm"]{--dm-tb:var(--dm-av-m);--dm-tc:var(--dm-av-m-ink)}.dm-pfm-lg[data-t="pt"]{--dm-tb:var(--dm-av-t);--dm-tc:var(--dm-av-t-ink)}.dm-pfm-lg[data-t="py"]{--dm-tb:var(--dm-av-y);--dm-tc:var(--dm-av-y-ink)}.dm-pfm-lg[data-t="pp"]{--dm-tb:var(--dm-av-p);--dm-tc:var(--dm-av-p-ink)}
.dm-pfm-ws{flex:1;min-width:0;display:flex;flex-direction:column}
.dm-pfm-wn{font-size:13.5px;line-height:18px;font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:100%}
.dm-pfm-ws .dm-muted{font-size:12px;line-height:16px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.dm-pfm-tr{display:flex;align-items:center;gap:4px;height:32px;padding:0 6px 0 3px;border-radius:var(--dm-r-pill);color:var(--dm-muted);flex:none;transition:background-color var(--dm-t-fast) var(--dm-ease)}
.dm-pfm-tr[aria-expanded="true"]{background:color-mix(in srgb,var(--dm-fg) 5%,transparent)}
@media (hover:hover) and (pointer:fine){.dm-pfm-tr:hover{background:color-mix(in srgb,var(--dm-fg) 5%,transparent)}}
.dm-pfm-tr .dm-av,.dm-pfm-me .dm-av{background:var(--dm-av-l);color:var(--dm-av-l-ink)}
.dm-pfm-tr .dm-av{width:26px;height:26px;font-size:11px}
.dm-pfm-tr>.dm-i{transition:transform var(--dm-t) var(--dm-ease)}
.dm-pfm-tr[aria-expanded="true"]>.dm-i{transform:rotate(180deg)}
.dm-pfm-in{flex:none;margin-right:4px}
/* nothing in it grows or shrinks when it is pressed (owner, 18 Nov); Studio's ink primary alone presses. The same goes for the
other menus of this group (Context switcher, Filter menu, Context menu) and Ticket list */
.dm-pfm :is(.dm-pill,.dm-ib):active,:root[data-style="studio"] :is(.dm-pfm,.dm-csw,.dm-flm,.dm-cxm,.dm-tkx) .dm-ib:active,:root [data-style="studio"] :is(.dm-pfm,.dm-csw,.dm-flm,.dm-cxm,.dm-tkx) .dm-ib:active,:root [data-style="studio"]:is(.dm-pfm,.dm-csw,.dm-flm,.dm-cxm,.dm-tkx) .dm-ib:active{transform:none}
/* the rows of these menus hover, and show the item picked, with a quiet fill that shows in light mode too (the owner's batch 2
notes: a hover fill shows on whatever it sits on; --dm-row barely shows on a white menu) */
:is(.dm-pfm-pop,.dm-flm-pop,.dm-cxm-pop,.dm-cxm-pop2) .dm-mi.dm-hl{background:color-mix(in srgb,var(--dm-fg) 5%,transparent)}
@media (hover:hover) and (pointer:fine){:is(.dm-pfm-pop,.dm-flm-pop,.dm-cxm-pop,.dm-cxm-pop2) .dm-mi:hover{background:color-mix(in srgb,var(--dm-fg) 5%,transparent)}}
/* the picked workspace shows by its tick, not a fill, so it never reads as a second hovered row (owner, 30 Nov) */
.dm-pfm-pop{width:256px}
.dm-pfm-me{display:flex;align-items:center;gap:10px;padding:var(--dm-s-2) var(--dm-s-2) 6px}
.dm-pfm-me .dm-av{width:32px;height:32px;font-size:12px}
.dm-pfm-me .dm-t{min-width:0;display:flex;flex-direction:column;line-height:1.35}
.dm-pfm-me b{font-size:13.5px;font-weight:500}
.dm-pfm-me .dm-muted{font-size:12px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.dm-pfm-pop .dm-mi .dm-pfm-lg{width:24px;height:24px;font-size:11px;border-radius:calc(7px * var(--dm-rk-m,var(--dm-rk)))}
.dm-pfm-pop .dm-mi .dm-d{white-space:nowrap}
/* the theme row (owner, 28 Nov): Theme, and a small three-way choice in the row on the segmented control's grey track with its
sliding knob. The choices are icons (owner, 30 Nov): a monitor for System, a sun for Light, the moon for Dark, each named by
its aria-label and the core tooltip, in square-ish segments of one width. The row itself has no hover: its three choices
are what you press */
.dm-pfm-th{display:flex;align-items:center;gap:10px;padding:2px 2px 2px var(--dm-s-2);font-size:13px;color:var(--dm-fg)}
.dm-pfm-th>.dm-i{color:var(--dm-fg2)}
.dm-pfm-ths{margin-left:auto}
.dm-pfm-ths button{display:inline-flex;align-items:center;justify-content:center;width:32px;height:24px;padding:0}
.dm-pfm-ths button[aria-checked="true"]{color:var(--dm-fg)}
.dm-pfm-ky .dm-kbd{margin-left:auto}
/* the shortcuts: a plain list of keys and what they do, 16px in from every edge; Close sits on the title's line with its glyph
16px in */
.dm-pfm-keys{padding:var(--dm-s-4);border-radius:var(--dm-r-card)}
.dm-pfm-kh{display:flex;align-items:center;justify-content:space-between;gap:var(--dm-s-2);height:20px;margin-bottom:var(--dm-s-3);font-size:13.5px}
.dm-pfm-kh b{font-weight:500}
.dm-pfm-kh .dm-ib{width:26px;height:26px;margin:-3px -7px -3px 0}
.dm-pfm-kl{margin:0;display:flex;flex-direction:column;gap:var(--dm-s-2)}
.dm-pfm-kl>div{display:flex;align-items:center;gap:var(--dm-s-3);font-size:12.5px}
.dm-pfm-kl dt{display:flex;gap:var(--dm-s-1);width:88px;flex:none}
.dm-pfm-kl dd{margin:0;color:var(--dm-fg2);min-width:0}
/* what changed (a switch, the theme, signing out) is said to screen readers only: the bar and the menu already show it, so no
line of text repeats it under the bar (owner, 18 Nov) */
.dm-pfm-note{position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip-path:inset(50%);white-space:nowrap}
/* Studio: the bar is a card with 22px corners; the tiles are monochrome; the menu takes the card's corners with its rows
concentric inside them; the Theme row's choice is the segmented track; the shortcuts card has an off-white head strip with Close a 28px
circle 16px from its top and right edges (owner, 23 Nov) */
:root[data-style="studio"] .dm-pfm-lg[data-t],:root [data-style="studio"] .dm-pfm-lg[data-t],:root [data-style="studio"].dm-pfm-lg[data-t]{background:var(--dm-chip);color:var(--dm-fg2);box-shadow:inset 0 0 0 1px var(--dm-hair)}
:root[data-style="studio"] .dm-pfm-pop,:root [data-style="studio"] .dm-pfm-pop,:root [data-style="studio"].dm-pfm-pop{padding:6px;border-radius:var(--dm-r-card)}
:root[data-style="studio"] .dm-pfm-pop .dm-mi,:root [data-style="studio"] .dm-pfm-pop .dm-mi,:root [data-style="studio"].dm-pfm-pop .dm-mi{border-radius:calc(var(--dm-r-card) - 6px)}
:root[data-style="studio"] .dm-pfm-ths button[aria-checked="true"],:root [data-style="studio"] .dm-pfm-ths button[aria-checked="true"],:root [data-style="studio"].dm-pfm-ths button[aria-checked="true"]{color:var(--dm-fg)}
:root[data-style="studio"] .dm-pfm-keys,:root [data-style="studio"] .dm-pfm-keys,:root [data-style="studio"].dm-pfm-keys{padding:0 16px 16px}
:root[data-style="studio"] .dm-pfm-kh,:root [data-style="studio"] .dm-pfm-kh,:root [data-style="studio"].dm-pfm-kh{height:auto;margin:0 -16px 16px;padding:var(--dm-strip-y) 16px;background:var(--dm-strip);border-bottom:1px solid var(--dm-line);border-radius:var(--dm-r-card) var(--dm-r-card) 0 0;line-height:28px}
:root[data-style="studio"] .dm-pfm-kh .dm-ib,:root [data-style="studio"] .dm-pfm-kh .dm-ib,:root [data-style="studio"].dm-pfm-kh .dm-ib{width:28px;height:28px;margin:0}
ProfileMenu.astroAstro · 45 lines
---
// Generated from designme.dev by scripts/sync.mjs. Edit the site, then sync.
// Profile menu: The account menu behind an avatar: switch workspace, theme, shortcuts and sign out.
// The markup, CSS and script are designme.dev's own, run by the shared core in ../core, which mounts the component when it scrolls
// into view and plays its demo. To show your own data, change profile-menu.js. The markup is kept exactly as it is (is:raw).
import type { HTMLAttributes } from 'astro/types';
import '../core/designme.css';
import './profile-menu.css';
export interface Props extends HTMLAttributes<'div'> {
/** "soft" or "studio" draws it in that style. Leave it out for Blueprint, or for the style set on <html> (data-style="soft" or "studio") */
'data-style'?: 'soft' | 'studio';
}
const { class: className, ...rest } = Astro.props;
---
<div class:list={['card', className]} data-c="profile-menu" {...rest}>
<div class="stage-in"><Fragment is:raw>
<div class="pfm">
<div class="pfm-bar panel">
<span class="pfm-lg pfm-cur"></span><span class="pfm-ws"><b class="pfm-wn"></b><span class="muted">Pricing refresh</span></span>
<button class="pfm-tr" aria-haspopup="menu" aria-expanded="false" aria-label="Account menu, Maya Kim" data-pop-align="end" data-pop-pos="down"><span class="av" data-pic="MK-g03">MK</span><svg class="i xs"><use href="#i-chev-d"/></svg></button>
<button class="pill line sm pfm-in" hidden>Sign in</button>
</div>
<div class="pop pfm-pop" role="menu">
<div class="pfm-me" role="none"><span class="av" data-pic="MK-g03">MK</span><span class="t"><b class="pfm-nm">Maya Kim</b><span class="muted pfm-em">maya@northwind.studio</span></span></div>
<div class="sep" role="separator"></div>
<div class="pfm-grp" role="group"><div class="ph pfm-gl" role="none">Workspaces</div><div class="pfm-wsl"></div></div>
<div class="sep" role="separator"></div>
<div class="pfm-th" role="group" aria-label="Theme"><svg class="i s"><use href="#i-moon"/></svg><span aria-hidden="true">Theme</span><span class="seg2 pfm-ths"><button class="pfm-tho" role="menuitemradio" aria-checked="true" tabindex="-1" data-v="system" aria-label="System" data-tip="System"><svg class="i s"><use href="#i-monitor"/></svg></button><button class="pfm-tho" role="menuitemradio" aria-checked="false" tabindex="-1" data-v="light" aria-label="Light" data-tip="Light"><svg class="i s"><use href="#i-sun"/></svg></button><button class="pfm-tho" role="menuitemradio" aria-checked="false" tabindex="-1" data-v="dark" aria-label="Dark" data-tip="Dark"><svg class="i s"><use href="#i-moon"/></svg></button></span></div>
<button class="mi pfm-ky" role="menuitem" tabindex="-1"><svg class="i s"><use href="#i-keyboard"/></svg><span>Keyboard shortcuts</span><span class="kbd" aria-hidden="true">?</span></button>
<div class="sep" role="separator"></div>
<button class="mi pfm-out" role="menuitem" tabindex="-1"><svg class="i s"><use href="#i-logout"/></svg><span>Sign out</span></button>
</div>
<div class="fold shut pfm-kf"><div><div class="pfm-keys panel" role="region" aria-label="Keyboard shortcuts">
<div class="pfm-kh"><b>Keyboard shortcuts</b><button class="ib pfm-kx" aria-label="Close shortcuts" data-tip="Close"><svg class="i xs"><use href="#i-x"/></svg></button></div>
<dl class="pfm-kl"><div><dt><span class="kbd">↑</span><span class="kbd">↓</span></dt><dd>Move through the menu</dd></div><div><dt><span class="kbd">Home</span><span class="kbd">End</span></dt><dd>First or last item</dd></div><div><dt><span class="kbd">Esc</span></dt><dd>Close the menu</dd></div><div><dt><span class="kbd">?</span></dt><dd>Show these shortcuts</dd></div></dl>
</div></div></div>
<p class="pfm-note" aria-live="polite"></p>
</div>
</Fragment></div>
</div>
<script>
import './profile-menu.js';
</script>
profile-menu.htmlHTML · 27 lines
<div class="card" data-c="profile-menu">
<div class="stage-in">
<div class="pfm">
<div class="pfm-bar panel">
<span class="pfm-lg pfm-cur"></span><span class="pfm-ws"><b class="pfm-wn"></b><span class="muted">Pricing refresh</span></span>
<button class="pfm-tr" aria-haspopup="menu" aria-expanded="false" aria-label="Account menu, Maya Kim" data-pop-align="end" data-pop-pos="down"><span class="av" data-pic="MK-g03">MK</span><svg class="i xs"><use href="#i-chev-d"/></svg></button>
<button class="pill line sm pfm-in" hidden>Sign in</button>
</div>
<div class="pop pfm-pop" role="menu">
<div class="pfm-me" role="none"><span class="av" data-pic="MK-g03">MK</span><span class="t"><b class="pfm-nm">Maya Kim</b><span class="muted pfm-em">maya@northwind.studio</span></span></div>
<div class="sep" role="separator"></div>
<div class="pfm-grp" role="group"><div class="ph pfm-gl" role="none">Workspaces</div><div class="pfm-wsl"></div></div>
<div class="sep" role="separator"></div>
<div class="pfm-th" role="group" aria-label="Theme"><svg class="i s"><use href="#i-moon"/></svg><span aria-hidden="true">Theme</span><span class="seg2 pfm-ths"><button class="pfm-tho" role="menuitemradio" aria-checked="true" tabindex="-1" data-v="system" aria-label="System" data-tip="System"><svg class="i s"><use href="#i-monitor"/></svg></button><button class="pfm-tho" role="menuitemradio" aria-checked="false" tabindex="-1" data-v="light" aria-label="Light" data-tip="Light"><svg class="i s"><use href="#i-sun"/></svg></button><button class="pfm-tho" role="menuitemradio" aria-checked="false" tabindex="-1" data-v="dark" aria-label="Dark" data-tip="Dark"><svg class="i s"><use href="#i-moon"/></svg></button></span></div>
<button class="mi pfm-ky" role="menuitem" tabindex="-1"><svg class="i s"><use href="#i-keyboard"/></svg><span>Keyboard shortcuts</span><span class="kbd" aria-hidden="true">?</span></button>
<div class="sep" role="separator"></div>
<button class="mi pfm-out" role="menuitem" tabindex="-1"><svg class="i s"><use href="#i-logout"/></svg><span>Sign out</span></button>
</div>
<div class="fold shut pfm-kf"><div><div class="pfm-keys panel" role="region" aria-label="Keyboard shortcuts">
<div class="pfm-kh"><b>Keyboard shortcuts</b><button class="ib pfm-kx" aria-label="Close shortcuts" data-tip="Close"><svg class="i xs"><use href="#i-x"/></svg></button></div>
<dl class="pfm-kl"><div><dt><span class="kbd">↑</span><span class="kbd">↓</span></dt><dd>Move through the menu</dd></div><div><dt><span class="kbd">Home</span><span class="kbd">End</span></dt><dd>First or last item</dd></div><div><dt><span class="kbd">Esc</span></dt><dd>Close the menu</dd></div><div><dt><span class="kbd">?</span></dt><dd>Show these shortcuts</dd></div></dl>
</div></div></div>
<p class="pfm-note" aria-live="polite"></p>
</div>
</div>
</div>
profile-menu.cssHTML · 74 lines
/* ---------- Profile menu ---------- */
/* an app's top bar with the account behind the avatar. The menu opens under it, lined up with its right edge, over the room
the component keeps for it under the bar, so the bar never moves as the menu opens and shuts (owner, 20 Nov: menus open over
the component from their trigger and never move it) and the menu is never cut off. The bar's content sits 16px in all round
in every style: the workspace's tile on the left, the avatar's trigger on the right. The trigger's box fills on hover and
while its menu is open, so the box itself is 16px from the bar's top, right and bottom (32px tall round the 26px avatar) */
.pfm{position:relative;width:100%;max-width:400px;margin:0 auto;display:flex;flex-direction:column;gap:12px}
.pfm-bar{display:flex;align-items:center;gap:12px;min-height:64px;padding:var(--dm-s-4);border-radius:var(--dm-r-card)}
/* a workspace's tile is its identity mark: in Soft and Blueprint a vivid fill with its own ink, the avatars' colours (white on
blue, violet, red and pink; 4.5:1 and APCA Lc 60); Studio keeps its marks monochrome */
.pfm-lg{--dm-tb:var(--dm-chip);--dm-tc:var(--dm-fg2);width:28px;height:28px;border-radius:var(--dm-r-sm);display:grid;place-items:center;flex:none;font-size:12px;font-weight:500;background:var(--dm-tb);color:var(--dm-tc);transition:background var(--dm-t) var(--dm-ease),color var(--dm-t) var(--dm-ease)}
.pfm-lg[data-t="pb"]{--dm-tb:var(--dm-av-b);--dm-tc:var(--dm-av-b-ink)}.pfm-lg[data-t="pl"]{--dm-tb:var(--dm-av-l);--dm-tc:var(--dm-av-l-ink)}.pfm-lg[data-t="pr"]{--dm-tb:var(--dm-av-r);--dm-tc:var(--dm-av-r-ink)}.pfm-lg[data-t="pk"]{--dm-tb:var(--dm-av-k);--dm-tc:var(--dm-av-k-ink)}
.pfm-lg[data-t="pm"]{--dm-tb:var(--dm-av-m);--dm-tc:var(--dm-av-m-ink)}.pfm-lg[data-t="pt"]{--dm-tb:var(--dm-av-t);--dm-tc:var(--dm-av-t-ink)}.pfm-lg[data-t="py"]{--dm-tb:var(--dm-av-y);--dm-tc:var(--dm-av-y-ink)}.pfm-lg[data-t="pp"]{--dm-tb:var(--dm-av-p);--dm-tc:var(--dm-av-p-ink)}
.pfm-ws{flex:1;min-width:0;display:flex;flex-direction:column}
.pfm-wn{font-size:13.5px;line-height:18px;font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:100%}
.pfm-ws .muted{font-size:12px;line-height:16px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.pfm-tr{display:flex;align-items:center;gap:4px;height:32px;padding:0 6px 0 3px;border-radius:var(--dm-r-pill);color:var(--dm-muted);flex:none;transition:background-color var(--dm-t-fast) var(--dm-ease)}
.pfm-tr[aria-expanded="true"]{background:color-mix(in srgb,var(--dm-fg) 5%,transparent)}
@media (hover:hover) and (pointer:fine){.pfm-tr:hover{background:color-mix(in srgb,var(--dm-fg) 5%,transparent)}}
.pfm-tr .av,.pfm-me .av{background:var(--dm-av-l);color:var(--dm-av-l-ink)}
.pfm-tr .av{width:26px;height:26px;font-size:11px}
.pfm-tr>.i{transition:transform var(--dm-t) var(--dm-ease)}
.pfm-tr[aria-expanded="true"]>.i{transform:rotate(180deg)}
.pfm-in{flex:none;margin-right:4px}
/* nothing in it grows or shrinks when it is pressed (owner, 18 Nov); Studio's ink primary alone presses. The same goes for the
other menus of this group (Context switcher, Filter menu, Context menu) and Ticket list */
.pfm :is(.pill,.ib):active,:root[data-style="studio"] :is(.pfm,.csw,.flm,.cxm,.tkx) .ib:active,:root [data-style="studio"] :is(.pfm,.csw,.flm,.cxm,.tkx) .ib:active,:root [data-style="studio"]:is(.pfm,.csw,.flm,.cxm,.tkx) .ib:active{transform:none}
/* the rows of these menus hover, and show the item picked, with a quiet fill that shows in light mode too (the owner's batch 2
notes: a hover fill shows on whatever it sits on; --dm-row barely shows on a white menu) */
:is(.pfm-pop,.flm-pop,.cxm-pop,.cxm-pop2) .mi.hl{background:color-mix(in srgb,var(--dm-fg) 5%,transparent)}
@media (hover:hover) and (pointer:fine){:is(.pfm-pop,.flm-pop,.cxm-pop,.cxm-pop2) .mi:hover{background:color-mix(in srgb,var(--dm-fg) 5%,transparent)}}
/* the picked workspace shows by its tick, not a fill, so it never reads as a second hovered row (owner, 30 Nov) */
.pfm-pop{width:256px}
.pfm-me{display:flex;align-items:center;gap:10px;padding:var(--dm-s-2) var(--dm-s-2) 6px}
.pfm-me .av{width:32px;height:32px;font-size:12px}
.pfm-me .t{min-width:0;display:flex;flex-direction:column;line-height:1.35}
.pfm-me b{font-size:13.5px;font-weight:500}
.pfm-me .muted{font-size:12px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.pfm-pop .mi .pfm-lg{width:24px;height:24px;font-size:11px;border-radius:calc(7px * var(--dm-rk-m,var(--dm-rk)))}
.pfm-pop .mi .d{white-space:nowrap}
/* the theme row (owner, 28 Nov): Theme, and a small three-way choice in the row on the segmented control's grey track with its
sliding knob. The choices are icons (owner, 30 Nov): a monitor for System, a sun for Light, the moon for Dark, each named by
its aria-label and the core tooltip, in square-ish segments of one width. The row itself has no hover: its three choices
are what you press */
.pfm-th{display:flex;align-items:center;gap:10px;padding:2px 2px 2px var(--dm-s-2);font-size:13px;color:var(--dm-fg)}
.pfm-th>.i{color:var(--dm-fg2)}
.pfm-ths{margin-left:auto}
.pfm-ths button{display:inline-flex;align-items:center;justify-content:center;width:32px;height:24px;padding:0}
.pfm-ths button[aria-checked="true"]{color:var(--dm-fg)}
.pfm-ky .kbd{margin-left:auto}
/* the shortcuts: a plain list of keys and what they do, 16px in from every edge; Close sits on the title's line with its glyph
16px in */
.pfm-keys{padding:var(--dm-s-4);border-radius:var(--dm-r-card)}
.pfm-kh{display:flex;align-items:center;justify-content:space-between;gap:var(--dm-s-2);height:20px;margin-bottom:var(--dm-s-3);font-size:13.5px}
.pfm-kh b{font-weight:500}
.pfm-kh .ib{width:26px;height:26px;margin:-3px -7px -3px 0}
.pfm-kl{margin:0;display:flex;flex-direction:column;gap:var(--dm-s-2)}
.pfm-kl>div{display:flex;align-items:center;gap:var(--dm-s-3);font-size:12.5px}
.pfm-kl dt{display:flex;gap:var(--dm-s-1);width:88px;flex:none}
.pfm-kl dd{margin:0;color:var(--dm-fg2);min-width:0}
/* what changed (a switch, the theme, signing out) is said to screen readers only: the bar and the menu already show it, so no
line of text repeats it under the bar (owner, 18 Nov) */
.pfm-note{position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip-path:inset(50%);white-space:nowrap}
/* Studio: the bar is a card with 22px corners; the tiles are monochrome; the menu takes the card's corners with its rows
concentric inside them; the Theme row's choice is the segmented track; the shortcuts card has an off-white head strip with Close a 28px
circle 16px from its top and right edges (owner, 23 Nov) */
:root[data-style="studio"] .pfm-lg[data-t],:root [data-style="studio"] .pfm-lg[data-t],:root [data-style="studio"].pfm-lg[data-t]{background:var(--dm-chip);color:var(--dm-fg2);box-shadow:inset 0 0 0 1px var(--dm-hair)}
:root[data-style="studio"] .pfm-pop,:root [data-style="studio"] .pfm-pop,:root [data-style="studio"].pfm-pop{padding:6px;border-radius:var(--dm-r-card)}
:root[data-style="studio"] .pfm-pop .mi,:root [data-style="studio"] .pfm-pop .mi,:root [data-style="studio"].pfm-pop .mi{border-radius:calc(var(--dm-r-card) - 6px)}
:root[data-style="studio"] .pfm-ths button[aria-checked="true"],:root [data-style="studio"] .pfm-ths button[aria-checked="true"],:root [data-style="studio"].pfm-ths button[aria-checked="true"]{color:var(--dm-fg)}
:root[data-style="studio"] .pfm-keys,:root [data-style="studio"] .pfm-keys,:root [data-style="studio"].pfm-keys{padding:0 16px 16px}
:root[data-style="studio"] .pfm-kh,:root [data-style="studio"] .pfm-kh,:root [data-style="studio"].pfm-kh{height:auto;margin:0 -16px 16px;padding:var(--dm-strip-y) 16px;background:var(--dm-strip);border-bottom:1px solid var(--dm-line);border-radius:var(--dm-r-card) var(--dm-r-card) 0 0;line-height:28px}
:root[data-style="studio"] .pfm-kh .ib,:root [data-style="studio"] .pfm-kh .ib,:root [data-style="studio"].pfm-kh .ib{width:28px;height:28px;margin:0}
profile-menu.jsHTML · 110 lines
DM.def('profile-menu', (r, c) => {
r.innerHTML = r.innerHTML.replace('{chev}', I('chev-d','xs')).replace('{moon}', I('moon')).replace('{th-sys}', I('monitor','s')).replace('{th-light}', I('sun','s')).replace('{th-dark}', I('moon','s')).replace('{keyboard}', I('keyboard')).replace('{logout}', I('logout')).replace('{x}', I('x','xs'));
// the workspaces this account belongs to: initial, name, plan and the tint of its tile
const WS = [['N', 'Northwind', 'Pro, 12 members', 'pb'], ['A', 'Acme Labs', 'Free, 3 members', 'pk'], ['P', 'Personal', 'Just you', 'pl']];
const uid = Math.random().toString(36).slice(2, 7);
const tr = $('.pfm-tr', r), pop = $('.pfm-pop', r), wsl = $('.pfm-wsl', r), th = $('.pfm-th', r), ths = $('.pfm-ths', r), tho = $$('.pfm-tho', r), note = $('.pfm-note', r), kf = $('.pfm-kf', r), sin = $('.pfm-in', r), cur = $('.pfm-cur', r), wn = $('.pfm-wn', r);
// the menu is named by the account it belongs to, and the workspaces by their heading
$('.pfm-nm', r).id = 'pfm-nm-' + uid; $('.pfm-em', r).id = 'pfm-em-' + uid; $('.pfm-gl', r).id = 'pfm-gl-' + uid;
pop.setAttribute('aria-labelledby', `pfm-nm-${uid} pfm-em-${uid}`); $('.pfm-grp', r).setAttribute('aria-labelledby', 'pfm-gl-' + uid);
wsl.innerHTML = WS.map((w, i) => `<button class="mi" role="menuitemradio" aria-checked="${!i}" tabindex="-1" data-i="${i}"><span class="pfm-lg" data-t="${w[3]}">${w[0]}</span><span>${w[1]}<span class="d">${w[2]}</span></span><span class="ck">${I('check','xs')}</span></button>`).join('');
const rows = $$('.mi', wsl);
// the arrow keys stop once on the theme row, on its picked choice (or the one with the focus); Left and Right move between its three
const items = () => $$('.mi, .pfm-tho', pop).filter(x => !x.matches('.pfm-tho') || (th.contains(document.activeElement) ? x === document.activeElement : x.getAttribute('aria-checked') === 'true'));
// the theme choice starts from the page's own theme: System when the page follows the device
const root = document.documentElement;
const pageTheme = () => root.dataset.theme === 'dark' || root.dataset.theme === 'light' ? root.dataset.theme : 'system';
let ws = 0, theme = pageTheme();
// the knob slides under the picked choice, placed at once the first time
const knob = document.createElement('span'); knob.className = 'knob'; ths.prepend(knob);
const place = () => { const b = tho.find(x => x.getAttribute('aria-checked') === 'true'); if (b && b.offsetWidth){ knob.style.left = b.offsetLeft + 'px'; knob.style.width = b.offsetWidth + 'px'; } };
const ro = new ResizeObserver(place); ro.observe(ths); c.offs.push(() => ro.disconnect());
// what changed is said to screen readers; the bar and the menu show it, so it has no line of its own under the bar
const say = t => { note.textContent = t || ''; };
function paint(){
const w = WS[ws]; cur.textContent = w[0]; cur.dataset.t = w[3];
rows.forEach((m, i) => m.setAttribute('aria-checked', i === ws)); tho.forEach(x => x.setAttribute('aria-checked', x.dataset.v === theme)); place();
}
// the workspace name in the bar crossfades to the new one. Each switch replaces the one before it, so switching again
// before the fade has finished (or straight back) still ends on the workspace you picked, never on an empty line
let named = WS[0][1], nameT = 0;
const setName = t => {
clearTimeout(nameT); wn.classList.add('sw');
if (t === named){ wn.textContent = t; wn.classList.remove('out'); return; }
wn.classList.add('out');
nameT = setTimeout(() => { named = t; wn.textContent = t; wn.classList.remove('out'); }, REDUCE ? 0 : 170);
};
c.offs.push(() => clearTimeout(nameT));
wn.textContent = named; paint();
// the menu opens and closes on its own rather than through the page's shared popover, so a story playing in the card
// beside it can't close it. Closing it while the focus is inside gives the focus back to the avatar
const isOpen = () => pop.classList.contains('open');
// the focus is the one highlight: a row the demo's pointer left lit goes dark
const focusItem = m => { if (!m) return; items().forEach(x => { x.tabIndex = x === m ? 0 : -1; x.classList.remove('hl'); }); m.focus({ preventScroll:true }); };
function show(on, focus){
if (on && !isOpen()){ hideTip(); placePop(tr, pop); knob.style.transition = 'none'; place(); void knob.offsetWidth; knob.style.transition = ''; }
pop.classList.toggle('open', on); pop.inert = !on; tr.setAttribute('aria-expanded', on);
if (on && focus){ const all = items(); focusItem(focus === 'last' ? all[all.length - 1] : all[0]); }
if (!on){ items().forEach(x => x.classList.remove('hl')); if (pop.contains(document.activeElement)) tr.focus({ preventScroll:true }); }
}
show(false);
// the menu opens over whatever sits under the bar, so the component keeps room for it below the bar: centred in a
// stage, the open menu still ends inside it
const room = () => { const el = $('.pfm', r); el.style.minHeight = Math.ceil($('.pfm-bar', r).offsetHeight + 6 + pop.offsetHeight) + 'px'; };
room(); if (document.fonts) document.fonts.ready.then(() => { if (!c.dead) room(); });
c.on(window, 'resize', room);
// the avatar opens it with a click, Enter, Space or the down arrow, and the focus goes to the first item; the up arrow
// opens it on the last. A story's tap opens it without moving the focus
c.on(tr, 'click', e => show(!isOpen(), e.isTrusted && 'first'));
c.on(tr, 'keydown', e => { if (e.key === 'ArrowDown' || e.key === 'ArrowUp'){ e.preventDefault(); show(true, e.key === 'ArrowUp' ? 'last' : 'first'); } });
c.on(document, 'pointerdown', e => { if (isOpen() && !pop.contains(e.target) && !tr.contains(e.target)) show(false); });
c.on(window, 'resize', e => { if (e.isTrusted) show(false); });
// inside the menu: the arrow keys move and wrap, Home and End jump to the ends, Escape closes it, Tab leaves it
c.on(pop, 'keydown', e => {
const all = items(), i = all.indexOf(document.activeElement);
const go = { ArrowDown:all[(i + 1) % all.length], ArrowUp:all[(i - 1 + all.length) % all.length], Home:all[0], End:all[all.length - 1] }[e.key];
const t = tho.indexOf(document.activeElement), side = { ArrowLeft:-1, ArrowRight:1 }[e.key];
if (go){ e.preventDefault(); focusItem(go); }
else if (t >= 0 && side){ e.preventDefault(); focusItem(tho[(t + side + 3) % 3]); }
else if (e.key === 'Escape'){ e.preventDefault(); e.stopPropagation(); show(false); }
else if (e.key === 'Tab') setTimeout(() => show(false));
});
rows.forEach((m, i) => m.addEventListener('click', () => {
show(false); if (i === ws) return;
ws = i; paint(); setName(WS[ws][1]); say(`Switched to ${WS[ws][1]}`);
}));
// the theme is a three-way choice: the menu stays open so the change shows where it was made. A real click sets the page's
// theme too (System follows the device again); the preview's story only moves the choice, so the page doesn't flash between
// themes while the demo loops
tho.forEach(b => b.addEventListener('click', e => {
if (b.dataset.v === theme) return;
theme = b.dataset.v; paint(); say(`Theme set to ${b.getAttribute('aria-label')}`);
if (!e.isTrusted) return;
if (theme === 'system'){ delete root.dataset.theme; try { localStorage.removeItem('dmui-theme'); } catch(err){} }
else { root.dataset.theme = theme; try { localStorage.setItem('dmui-theme', theme); } catch(err){} }
}));
// and when the page's theme changes from anywhere else, the choice follows it
const mo = new MutationObserver(() => { if (pageTheme() !== theme){ theme = pageTheme(); paint(); } });
mo.observe(root, { attributes:true, attributeFilter:['data-theme'] }); c.offs.push(() => mo.disconnect());
// Keyboard shortcuts, or ? anywhere in the component, opens the list of the keys the menu answers to
const keys = on => { kf.classList.toggle('shut', !on); kf.inert = !on; };
keys(false);
$('.pfm-ky', r).addEventListener('click', () => { const had = pop.contains(document.activeElement); show(false); keys(true); if (had) $('.pfm-kx', r).focus({ preventScroll:true }); });
$('.pfm-kx', r).onclick = () => { keys(false); tr.focus({ preventScroll:true }); };
c.on(r, 'keydown', e => { if (e.key === '?' && !e.target.matches('input,textarea')){ e.preventDefault(); show(false); keys(kf.classList.contains('shut')); } });
// signing out swaps the avatar for Sign in, which brings it back
$('.pfm-out', r).addEventListener('click', () => { const had = pop.contains(document.activeElement); show(false); tr.hidden = true; sin.hidden = false; if (had) sin.focus({ preventScroll:true }); say(`Signed out of ${WS[ws][1]}`); });
sin.onclick = () => { sin.hidden = true; tr.hidden = false; tr.focus({ preventScroll:true }); say('Signed in as Maya Kim'); };
// the preview's story: open the menu, look over the workspaces, switch to Acme Labs, then open it again and pick Dark
c.story(async s => {
const hl = el => items().forEach(x => x.classList.toggle('hl', x === el));
await s.beat(3); await s.tap(tr); await s.beat(2);
hl(rows[2]); await s.point(rows[2]); await s.beat(2);
hl(rows[1]); await s.point(rows[1]); await s.beat(2);
await s.tap(rows[1]); s.away(); await s.beat(4);
await s.tap(tr); await s.beat(2);
await s.tap(tho[2]); await s.beat(3);
await s.tap(tr); s.away(); await s.beat(3);
});
});
Questions
What people ask about it.
- Does the Theme row change the theme?
- No. It keeps its own pick and calls
onThemeChangewith'system','light'or'dark'. Setdata-themeon<html>there (or remove it for System), or call your own theme code. On designme.dev a click sets the page's theme too; the demo only moves the pick. - Can the workspaces be a submenu instead?
- They are an inline list, so the whole menu fits a phone screen without a flyout. Keep the list short; for many workspaces, link to a page that lists them all.
- What happens on Sign out?
- The avatar gives way to a Sign in button and
onSignedInChange(false)is called. Do the real sign out there, or control it withsignedIn. - Can I list my app's own shortcuts?
- Yes. Pass
shortcutsas{ keys, label }[]. Only ? is handled by the component; your other keys need your own handlers.
More in Collaboration
Threads, inboxes and boards for teams working alongside an agent.