oneslash-design-system 2.24.0 → 2.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/DESIGN.md +8 -4
- package/dist/cases/ask-page/answered.jsx +10 -2
- package/dist/cases/ask-page.md +12 -3
- package/dist/cases/billing-page/self-serve.jsx +4 -4
- package/dist/cases/billing-page/trial.d.ts +1 -0
- package/dist/cases/billing-page/trial.jsx +115 -0
- package/dist/cases/billing-page.md +166 -5
- package/dist/cases/collapsible-search/popover.jsx +1 -1
- package/dist/cases/collapsible-search.md +2 -2
- package/dist/cases/cookie-choice/banner.d.ts +1 -0
- package/dist/cases/cookie-choice/banner.jsx +82 -0
- package/dist/cases/cookie-choice/settings.d.ts +1 -0
- package/dist/cases/cookie-choice/settings.jsx +75 -0
- package/dist/cases/cookie-choice.md +234 -0
- package/dist/cases/dashboard/numbers-first.jsx +1 -1
- package/dist/cases/dashboard/work-first.jsx +1 -1
- package/dist/cases/dashboard.md +2 -2
- package/dist/cases/data-table-page/all-rows.jsx +1 -1
- package/dist/cases/data-table-page/paged.jsx +1 -1
- package/dist/cases/data-table-page.md +2 -2
- package/dist/cases/invoice-list/table.jsx +21 -9
- package/dist/cases/invoice-list.md +27 -12
- package/dist/cases/message-reactions/picker.jsx +1 -1
- package/dist/cases/message-reactions.md +2 -2
- package/dist/cases/message-row.md +2 -1
- package/dist/cases/newsletter-signup/inline.d.ts +1 -0
- package/dist/cases/newsletter-signup/inline.jsx +72 -0
- package/dist/cases/newsletter-signup/section.d.ts +1 -0
- package/dist/cases/newsletter-signup/section.jsx +72 -0
- package/dist/cases/newsletter-signup.md +234 -0
- package/dist/cases/number-format.md +6 -2
- package/dist/cases/on-this-page.md +2 -0
- package/dist/cases/people-row/stack.jsx +1 -1
- package/dist/cases/people-row.md +2 -2
- package/dist/cases/plan-comparison/table.d.ts +1 -0
- package/dist/cases/plan-comparison/table.jsx +47 -0
- package/dist/cases/plan-comparison.md +94 -0
- package/dist/cases/plan-picker.md +1 -0
- package/dist/cases/pricing-section.md +1 -1
- package/dist/cases/site-footer/columns.jsx +2 -1
- package/dist/cases/site-footer.md +3 -1
- package/dist/cases/stat-row/tiles.jsx +2 -1
- package/dist/cases/stat-row.md +4 -1
- package/dist/cases/task-header/agent-sets-status.jsx +1 -1
- package/dist/cases/task-header/people-change-status.jsx +1 -1
- package/dist/cases/task-header.md +2 -2
- package/dist/cases.json +245 -28
- package/dist/components/alert.d.ts +3 -1
- package/dist/components/alert.jsx +5 -5
- package/dist/components/barChart.jsx +4 -2
- package/dist/components/dateField.jsx +1 -1
- package/dist/components/formatNumber.d.ts +10 -2
- package/dist/components/formatNumber.js +44 -9
- package/dist/components/layout.d.ts +4 -2
- package/dist/components/layout.jsx +13 -2
- package/dist/components/markdown.d.ts +24 -0
- package/dist/components/markdown.jsx +81 -0
- package/dist/components/onThisPage.d.ts +14 -3
- package/dist/components/onThisPage.jsx +72 -8
- package/dist/components/pageShell.d.ts +3 -3
- package/dist/components/pageShell.jsx +6 -5
- package/dist/components/popover.d.ts +5 -1
- package/dist/components/popover.jsx +3 -2
- package/dist/components/progress.jsx +1 -1
- package/dist/components/select.jsx +5 -2
- package/dist/components/statTile.d.ts +1 -1
- package/dist/components/statTile.jsx +7 -2
- package/dist/components/tableCell.d.ts +4 -3
- package/dist/components/tableCell.jsx +2 -2
- package/dist/components/toaster.jsx +81 -11
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/internal/markdown.d.ts +40 -0
- package/dist/internal/markdown.js +577 -0
- package/dist/internal/toaster.d.ts +2 -0
- package/dist/internal/toaster.js +8 -0
- package/dist/native-mapping.json +9 -3
- package/dist/stories/Cases.generated.stories.d.ts +6 -0
- package/dist/stories/Cases.generated.stories.jsx +12 -0
- package/dist/stories/Markdown.stories.d.ts +9 -0
- package/dist/stories/Markdown.stories.jsx +66 -0
- package/dist/stories/OnThisPage.stories.d.ts +1 -0
- package/dist/stories/OnThisPage.stories.jsx +11 -0
- package/dist/stories/Popover.stories.d.ts +2 -0
- package/dist/stories/Popover.stories.jsx +33 -0
- package/dist/stories/StatTile.stories.d.ts +4 -0
- package/dist/stories/StatTile.stories.jsx +47 -2
- package/dist/stories/Toaster.stories.d.ts +4 -0
- package/dist/stories/Toaster.stories.jsx +30 -0
- package/package.json +1 -1
package/dist/cases.json
CHANGED
|
@@ -986,6 +986,7 @@
|
|
|
986
986
|
"Say where the agent looks above the `Composer`: 'Acme Agent looks in the docs, chats and tasks of all 3 of your workspaces.' Change it with the scope.",
|
|
987
987
|
"Name the `Composer` for who reads it: 'Ask Acme Agent'.",
|
|
988
988
|
"Show the question as the person's `Message`, and the answer as the agent's, with its sources as cards under it, as the case 'Reply sources' says.",
|
|
989
|
+
"Render an agent's markdown with `Markdown`, never as raw text with its marks.",
|
|
989
990
|
"Offer 'Save to Docs' under an answer when the product keeps answers as docs. While it saves it is `loading`. Then a toast says 'Answer saved to Docs.', a link 'Open in Docs' takes its place, and focus goes to the link.",
|
|
990
991
|
"Keep the conversation when the person leaves the page, and show it again when they come back.",
|
|
991
992
|
"Show the agent's progress row where the answer will appear while it works, with a Stop Button, as the rule 'An agent shows its progress' says. Once the run has ended, Stop gives way to 'Stopped. Nothing was changed.' and focus goes back to the `Composer`.",
|
|
@@ -1029,7 +1030,7 @@
|
|
|
1029
1030
|
"id": "answered",
|
|
1030
1031
|
"title": "Answered",
|
|
1031
1032
|
"useWhen": "A question has its answer and sources, and the person can ask the next one.",
|
|
1032
|
-
"source": "'use client';\nimport { useEffect, useRef, useState } from 'react';\nimport { BookOpen, Bot, ListChecks, MessageSquare, Plug } from 'lucide-react';\nimport Toaster, { toast, dismissToast } from 'oneslash-design-system/components/toaster';\nimport AppShell from 'oneslash-design-system/components/appShell';\nimport Navigation from 'oneslash-design-system/components/navigation';\nimport MenuItem from 'oneslash-design-system/components/menuItem';\nimport TitleBar from 'oneslash-design-system/components/titleBar';\nimport Button from 'oneslash-design-system/components/button';\nimport Popover from 'oneslash-design-system/components/popover';\nimport Menu from 'oneslash-design-system/components/menu';\nimport Line from 'oneslash-design-system/components/line';\nimport Message from 'oneslash-design-system/components/message';\nimport UserImage from 'oneslash-design-system/components/userImage';\nimport TimeStamp from 'oneslash-design-system/components/timeStamp';\nimport Tag from 'oneslash-design-system/components/tag';\nimport Paragraph from 'oneslash-design-system/components/paragraph';\nimport SourceCard from 'oneslash-design-system/components/sourceCard';\nimport Composer from 'oneslash-design-system/components/composer';\nimport StepList from 'oneslash-design-system/components/stepList';\nimport { Cluster, Grid, Stack } from 'oneslash-design-system/components/layout';\n\n// A real app reads these from the session.\nconst me = 'Dana Lee';\nconst agentName = 'Acme Agent';\nconst workspaces = ['Acme Design', 'Acme Engineering', 'Acme Marketing'];\nconst all = `All ${workspaces.length} Workspaces`;\n\nconst question = { from: me, at: new Date('2026-11-16T14:40:00Z'), text: 'Who owns the press kit for the launch?' };\nconst answeredAt = new Date('2026-11-16T14:41:00Z');\nconst answer = 'Mia Park owns the press kit. Ben Carter handed it to her in #launch on Nov 12, 2026, and the launch plan lists her as its owner. It is due Nov 19, 2026.';\n\ntype Kind = 'chat' | 'docs' | 'tasks';\nconst kinds = {\n chat: { label: 'Chat', icon: MessageSquare },\n docs: { label: 'Docs', icon: BookOpen },\n tasks: { label: 'Tasks', icon: ListChecks },\n};\n\n// Each card links to the thing it read.\nconst sources: { kind: Kind; title: string; where: string; href: string }[] = [\n { kind: 'chat', title: 'Press kit hand-off', where: 'Acme Marketing · #launch · Nov 12', href: '/chat/launch/m-2210' },\n { kind: 'docs', title: 'Launch plan', where: 'Acme Marketing', href: '/docs/launch-plan' },\n { kind: 'tasks', title: 'Write the press kit', where: 'Acme Design · Due Nov 19', href: '/tasks/press-kit' },\n];\n\n// 'From Chat · Docs · Tasks': each kind once, in the order it first appears.\nconst kindsTag = `From ${sources.map((s) => kinds[s.kind].label).filter((l, i, list) => list.indexOf(l) === i).join(' · ')}`;\n\n// The next question and the agent's run on it. 'nothing' is the end of a run that found nothing in the scope.\ntype Phase = 'running' | 'stopping' | 'stopped' | 'nothing';\ntype Turn = { id: string; text: string; scope: string | null; phase: Phase; seconds: number };\ntype Focusable = HTMLButtonElement | HTMLAnchorElement | null;\n\n// The places. A real app lets each link go to its page.\nconst sidebar = (\n <Navigation aria-label=\"Main\">\n {[\n ['Home', 'House', '/'],\n ['Ask', 'MessageCircle', '/ask'],\n ['Docs', 'BookOpen', '/docs'],\n ].map(([label, icon, href]) => (\n <MenuItem\n key={href}\n size=\"small\"\n label={label}\n iconName={icon}\n href={href}\n isSelected={href === '/ask'}\n aria-current={href === '/ask' ? 'page' : undefined}\n onClick={(event: { preventDefault: () => void }) => event.preventDefault()}\n />\n ))}\n </Navigation>\n);\n\nexport default function AskPageAnswered() {\n const [navOpen, setNavOpen] = useState(false);\n // null means every workspace.\n const [scope, setScope] = useState<string | null>(null);\n const [anchor, setAnchor] = useState<HTMLElement | null>(null);\n const [open, setOpen] = useState(false);\n const [turns, setTurns] = useState<Turn[]>([]);\n const [text, setText] = useState('');\n const [saving, setSaving] = useState(false);\n const [saved, setSaved] = useState(false);\n const openButton = useRef<Focusable>(null);\n const timer = useRef<ReturnType<typeof setTimeout>>();\n const run = useRef<ReturnType<typeof setTimeout>>();\n const tick = useRef<ReturnType<typeof setInterval>>();\n const field = useRef<HTMLTextAreaElement>(null);\n const toastIds = useRef<string[]>([]);\n // Where focus goes after the next render, once the element it goes to is on screen.\n const focusNext = useRef<() => void>();\n const label = scope ?? all;\n\n // On unmount it stops the request and closes every toast it opened.\n useEffect(() => () => {\n clearTimeout(timer.current);\n clearTimeout(run.current);\n clearInterval(tick.current);\n toastIds.current.forEach((id) => dismissToast(id));\n toastIds.current = [];\n }, []);\n\n useEffect(() => {\n const move = focusNext.current;\n focusNext.current = undefined;\n move?.();\n });\n\n function choose(next: string | null) {\n setScope(next);\n setOpen(false);\n }\n\n // The answer goes to Docs, away from this page, so a toast says where it went.\n // 'Save to Docs' gives way to a link to the new doc, and focus goes to it.\n function saveToDocs() {\n if (saving || saved) return;\n setSaving(true);\n // Stands in for the request to the server.\n timer.current = setTimeout(() => {\n setSaving(false);\n setSaved(true);\n toastIds.current.push(toast({ type: 'success', message: 'Answer saved to Docs.' }));\n focusNext.current = () => openButton.current?.focus({ preventScroll: true });\n }, 1200);\n }\n\n const running = turns.some((t) => t.phase === 'running' || t.phase === 'stopping');\n\n // Changes the last turn, the one the agent is working on.\n function setLast(change: Partial<Turn>) {\n setTurns((list) => list.map((t, i) => (i === list.length - 1 ? { ...t, ...change } : t)));\n }\n\n function endRun() {\n clearTimeout(run.current);\n clearInterval(tick.current);\n }\n\n // The question shows at once, and the agent's progress row takes the place of its answer while it works.\n // This run finds nothing in the scope, so its answer says so in one plain sentence and shows no sources.\n function send() {\n if (running) return;\n setTurns((list) => [...list, { id: `t${list.length + 1}`, text: text.trim(), scope, phase: 'running', seconds: 0 }]);\n setText('');\n tick.current = setInterval(() => setTurns((list) => list.map((t, i) => (i === list.length - 1 ? { ...t, seconds: t.seconds + 1 } : t))), 1000);\n // Stands in for the agent's run.\n run.current = setTimeout(() => {\n endRun();\n setLast({ phase: 'nothing' });\n }, 3000);\n }\n\n // Stop asks the server to end the run. The row says it stopped only once the run has ended,\n // then focus goes back to the question box, since Stop is gone.\n function stop() {\n clearTimeout(run.current);\n setLast({ phase: 'stopping' });\n run.current = setTimeout(() => {\n endRun();\n setLast({ phase: 'stopped' });\n focusNext.current = () => field.current?.focus({ preventScroll: true });\n }, 1200);\n }\n\n return (\n <AppShell title=\"Ask\" navOpen={navOpen} onNavOpenChange={setNavOpen} sidebar={sidebar}>\n <Stack gap=\"large\">\n <TitleBar\n title=\"Ask\"\n actions={\n // The label is the scope. The chevron says it opens a menu.\n <Button\n size=\"small\"\n type=\"tertiary\"\n state={open ? 'selected' : 'enabled'}\n label={label}\n actionIcon=\"ChevronDown\"\n aria-label={`${label}, change where ${agentName} looks`}\n aria-haspopup=\"menu\"\n aria-expanded={open}\n onClickButton={(e: { currentTarget: HTMLElement }) => {\n setAnchor(e.currentTarget);\n setOpen((o) => !o);\n }}\n />\n }\n />\n {/* A real app keeps the conversation when the person leaves, and gives the list that holds the rows role=\"log\". */}\n <Stack gap=\"small\">\n <Message\n aria-label={question.from}\n avatar={<UserImage userHandle={question.from} decorative />}\n name={question.from}\n meta={<TimeStamp createdAt={question.at} dateFormat=\"absolute\" data=\"time\" />}\n >\n <Paragraph measure=\"none\">{question.text}</Paragraph>\n </Message>\n <Message\n aria-label={`${agentName}, agent`}\n avatar={<UserImage userHandle={agentName} icon={Bot} decorative />}\n name={agentName}\n meta={\n <>\n <Tag variant=\"contained\" size=\"small\" label=\"Agent\" />\n <TimeStamp createdAt={answeredAt} dateFormat=\"absolute\" data=\"time\" />\n <Paragraph size=\"caption\" tone=\"secondary\" measure=\"none\">Model name</Paragraph>\n </>\n }\n // The sources sit directly under the answer they support.\n footer={\n <Stack gap=\"medium\">\n <Cluster>\n <Tag variant=\"contained\" size=\"small\" color=\"success\" icon={Plug} label={kindsTag} />\n </Cluster>\n <Grid columns={2} gap=\"medium\">\n {sources.map((s) => (\n <SourceCard key={s.href} icon={kinds[s.kind].icon} title={s.title} meta={`${kinds[s.kind].label} · ${s.where}`} href={s.href} />\n ))}\n </Grid>\n <Cluster>\n {saved ? (\n <Button ref={openButton} size=\"small\" type=\"tertiary\" state=\"enabled\" label=\"Open in Docs\" decoIcon=\"FileText\" href=\"/docs/press-kit-owner\" />\n ) : (\n <Button size=\"small\" type=\"secondary\" state=\"enabled\" label=\"Save to Docs\" decoIcon=\"BookmarkPlus\" loading={saving} onClickButton={saveToDocs} />\n )}\n </Cluster>\n </Stack>\n }\n >\n <Paragraph measure=\"none\">{answer}</Paragraph>\n </Message>\n {turns.map((t) => {\n const place = t.scope ?? `all ${workspaces.length} of your workspaces`;\n const working = t.phase === 'running' || t.phase === 'stopping';\n return (\n <Stack key={t.id} gap=\"small\">\n <Message\n aria-label={me}\n avatar={<UserImage userHandle={me} decorative />}\n name={me}\n meta={<TimeStamp createdAt={new Date('2026-11-16T14:45:00Z')} dateFormat=\"absolute\" data=\"time\" />}\n >\n <Paragraph measure=\"none\">{t.text}</Paragraph>\n </Message>\n <Message\n aria-label={`${agentName}, agent`}\n avatar={<UserImage userHandle={agentName} icon={Bot} decorative />}\n name={agentName}\n meta={\n <>\n <Tag variant=\"contained\" size=\"small\" label=\"Agent\" />\n <TimeStamp createdAt={new Date('2026-11-16T14:45:00Z')} dateFormat=\"absolute\" data=\"time\" />\n <Paragraph size=\"caption\" tone=\"secondary\" measure=\"none\">Model name</Paragraph>\n </>\n }\n // The only Stop, on the row for the whole run. It shows loading while the run is stopping.\n footer={working ? (\n <Cluster>\n <Button size=\"small\" type=\"secondary\" state=\"enabled\" label=\"Stop\" loading={t.phase === 'stopping'} onClickButton={stop} />\n </Cluster>\n ) : undefined}\n >\n {working ? (\n // A real app wraps this part in a polite live region, since StepList has none.\n <Stack gap=\"medium\">\n <Paragraph size=\"caption\" tone=\"secondary\" measure=\"none\">{`Working for ${t.seconds} ${t.seconds === 1 ? 'second' : 'seconds'}`}</Paragraph>\n <StepList\n aria-label={`${agentName}'s steps`}\n steps={[\n { label: 'Read your question', status: 'done' },\n { label: `Looking in the docs, chats and tasks of ${place}`, status: 'running' },\n ]}\n />\n </Stack>\n ) : t.phase === 'stopped' ? (\n <Paragraph measure=\"none\">Stopped. Nothing was changed.</Paragraph>\n ) : (\n // It read nothing it could use, so the answer has no sources section.\n <Paragraph measure=\"none\">{`I found nothing about this in the docs, chats and tasks of ${place}. Try other words, or change where I look.`}</Paragraph>\n )}\n </Message>\n </Stack>\n );\n })}\n </Stack>\n <Stack gap=\"small\">\n {/* Where the agent looks, said above the box it is asked in. */}\n <Paragraph size=\"body2\" tone=\"secondary\" measure=\"none\">\n {scope ? `${agentName} looks in the docs, chats and tasks of ${scope}.` : `${agentName} looks in the docs, chats and tasks of all ${workspaces.length} of your workspaces.`}\n </Paragraph>\n <Composer\n ref={field}\n id=\"ask-page-answered-question\"\n aria-label={`Ask ${agentName}`}\n placeholder={`Ask ${agentName}`}\n value={text}\n onChange={setText}\n onSubmit={send}\n />\n </Stack>\n </Stack>\n <Popover open={open} anchorEl={anchor} onClose={() => setOpen(false)} returnFocus>\n <Menu navigable aria-label={`Where ${agentName} looks`} width={220}>\n <MenuItem size=\"small\" label={all} isSelected={scope === null} role=\"menuitemradio\" onClick={() => choose(null)} />\n <Line />\n {workspaces.map((w) => (\n <MenuItem key={w} size=\"small\" label={w} isSelected={scope === w} role=\"menuitemradio\" onClick={() => choose(w)} />\n ))}\n </Menu>\n </Popover>\n {/* A real app mounts one Toaster near its root. */}\n <Toaster />\n </AppShell>\n );\n}\n",
|
|
1033
|
+
"source": "'use client';\nimport { useEffect, useRef, useState } from 'react';\nimport { BookOpen, Bot, ListChecks, MessageSquare, Plug } from 'lucide-react';\nimport Toaster, { toast, dismissToast } from 'oneslash-design-system/components/toaster';\nimport AppShell from 'oneslash-design-system/components/appShell';\nimport Navigation from 'oneslash-design-system/components/navigation';\nimport MenuItem from 'oneslash-design-system/components/menuItem';\nimport TitleBar from 'oneslash-design-system/components/titleBar';\nimport Button from 'oneslash-design-system/components/button';\nimport Popover from 'oneslash-design-system/components/popover';\nimport Menu from 'oneslash-design-system/components/menu';\nimport Line from 'oneslash-design-system/components/line';\nimport Message from 'oneslash-design-system/components/message';\nimport UserImage from 'oneslash-design-system/components/userImage';\nimport TimeStamp from 'oneslash-design-system/components/timeStamp';\nimport Tag from 'oneslash-design-system/components/tag';\nimport Paragraph from 'oneslash-design-system/components/paragraph';\nimport Markdown from 'oneslash-design-system/components/markdown';\nimport SourceCard from 'oneslash-design-system/components/sourceCard';\nimport Composer from 'oneslash-design-system/components/composer';\nimport StepList from 'oneslash-design-system/components/stepList';\nimport { Cluster, Grid, Stack } from 'oneslash-design-system/components/layout';\n\n// A real app reads these from the session.\nconst me = 'Dana Lee';\nconst agentName = 'Acme Agent';\nconst workspaces = ['Acme Design', 'Acme Engineering', 'Acme Marketing'];\nconst all = `All ${workspaces.length} Workspaces`;\n\nconst question = { from: me, at: new Date('2026-11-16T14:40:00Z'), text: 'Who owns the press kit for the launch?' };\nconst answeredAt = new Date('2026-11-16T14:41:00Z');\n// The agent writes markdown. Markdown sets it in ODS parts, so no mark shows as raw text.\nconst answer = [\n '**Mia Park** owns the press kit. Here is how it came to her:',\n '',\n '1. Ben Carter handed it to her in #launch on Nov 12, 2026.',\n '2. The [launch plan](https://acme.example/docs/launch-plan) lists her as its owner.',\n '3. It is due Nov 19, 2026.',\n].join('\\n');\n\ntype Kind = 'chat' | 'docs' | 'tasks';\nconst kinds = {\n chat: { label: 'Chat', icon: MessageSquare },\n docs: { label: 'Docs', icon: BookOpen },\n tasks: { label: 'Tasks', icon: ListChecks },\n};\n\n// Each card links to the thing it read.\nconst sources: { kind: Kind; title: string; where: string; href: string }[] = [\n { kind: 'chat', title: 'Press kit hand-off', where: 'Acme Marketing · #launch · Nov 12', href: '/chat/launch/m-2210' },\n { kind: 'docs', title: 'Launch plan', where: 'Acme Marketing', href: '/docs/launch-plan' },\n { kind: 'tasks', title: 'Write the press kit', where: 'Acme Design · Due Nov 19', href: '/tasks/press-kit' },\n];\n\n// 'From Chat · Docs · Tasks': each kind once, in the order it first appears.\nconst kindsTag = `From ${sources.map((s) => kinds[s.kind].label).filter((l, i, list) => list.indexOf(l) === i).join(' · ')}`;\n\n// The next question and the agent's run on it. 'nothing' is the end of a run that found nothing in the scope.\ntype Phase = 'running' | 'stopping' | 'stopped' | 'nothing';\ntype Turn = { id: string; text: string; scope: string | null; phase: Phase; seconds: number };\ntype Focusable = HTMLButtonElement | HTMLAnchorElement | null;\n\n// The places. A real app lets each link go to its page.\nconst sidebar = (\n <Navigation aria-label=\"Main\">\n {[\n ['Home', 'House', '/'],\n ['Ask', 'MessageCircle', '/ask'],\n ['Docs', 'BookOpen', '/docs'],\n ].map(([label, icon, href]) => (\n <MenuItem\n key={href}\n size=\"small\"\n label={label}\n iconName={icon}\n href={href}\n isSelected={href === '/ask'}\n aria-current={href === '/ask' ? 'page' : undefined}\n onClick={(event: { preventDefault: () => void }) => event.preventDefault()}\n />\n ))}\n </Navigation>\n);\n\nexport default function AskPageAnswered() {\n const [navOpen, setNavOpen] = useState(false);\n // null means every workspace.\n const [scope, setScope] = useState<string | null>(null);\n const [anchor, setAnchor] = useState<HTMLElement | null>(null);\n const [open, setOpen] = useState(false);\n const [turns, setTurns] = useState<Turn[]>([]);\n const [text, setText] = useState('');\n const [saving, setSaving] = useState(false);\n const [saved, setSaved] = useState(false);\n const openButton = useRef<Focusable>(null);\n const timer = useRef<ReturnType<typeof setTimeout>>();\n const run = useRef<ReturnType<typeof setTimeout>>();\n const tick = useRef<ReturnType<typeof setInterval>>();\n const field = useRef<HTMLTextAreaElement>(null);\n const toastIds = useRef<string[]>([]);\n // Where focus goes after the next render, once the element it goes to is on screen.\n const focusNext = useRef<() => void>();\n const label = scope ?? all;\n\n // On unmount it stops the request and closes every toast it opened.\n useEffect(() => () => {\n clearTimeout(timer.current);\n clearTimeout(run.current);\n clearInterval(tick.current);\n toastIds.current.forEach((id) => dismissToast(id));\n toastIds.current = [];\n }, []);\n\n useEffect(() => {\n const move = focusNext.current;\n focusNext.current = undefined;\n move?.();\n });\n\n function choose(next: string | null) {\n setScope(next);\n setOpen(false);\n }\n\n // The answer goes to Docs, away from this page, so a toast says where it went.\n // 'Save to Docs' gives way to a link to the new doc, and focus goes to it.\n function saveToDocs() {\n if (saving || saved) return;\n setSaving(true);\n // Stands in for the request to the server.\n timer.current = setTimeout(() => {\n setSaving(false);\n setSaved(true);\n toastIds.current.push(toast({ type: 'success', message: 'Answer saved to Docs.' }));\n focusNext.current = () => openButton.current?.focus({ preventScroll: true });\n }, 1200);\n }\n\n const running = turns.some((t) => t.phase === 'running' || t.phase === 'stopping');\n\n // Changes the last turn, the one the agent is working on.\n function setLast(change: Partial<Turn>) {\n setTurns((list) => list.map((t, i) => (i === list.length - 1 ? { ...t, ...change } : t)));\n }\n\n function endRun() {\n clearTimeout(run.current);\n clearInterval(tick.current);\n }\n\n // The question shows at once, and the agent's progress row takes the place of its answer while it works.\n // This run finds nothing in the scope, so its answer says so in one plain sentence and shows no sources.\n function send() {\n if (running) return;\n setTurns((list) => [...list, { id: `t${list.length + 1}`, text: text.trim(), scope, phase: 'running', seconds: 0 }]);\n setText('');\n tick.current = setInterval(() => setTurns((list) => list.map((t, i) => (i === list.length - 1 ? { ...t, seconds: t.seconds + 1 } : t))), 1000);\n // Stands in for the agent's run.\n run.current = setTimeout(() => {\n endRun();\n setLast({ phase: 'nothing' });\n }, 3000);\n }\n\n // Stop asks the server to end the run. The row says it stopped only once the run has ended,\n // then focus goes back to the question box, since Stop is gone.\n function stop() {\n clearTimeout(run.current);\n setLast({ phase: 'stopping' });\n run.current = setTimeout(() => {\n endRun();\n setLast({ phase: 'stopped' });\n focusNext.current = () => field.current?.focus({ preventScroll: true });\n }, 1200);\n }\n\n return (\n <AppShell title=\"Ask\" navOpen={navOpen} onNavOpenChange={setNavOpen} sidebar={sidebar}>\n <Stack gap=\"large\">\n <TitleBar\n title=\"Ask\"\n actions={\n // The label is the scope. The chevron says it opens a menu.\n <Button\n size=\"small\"\n type=\"tertiary\"\n state={open ? 'selected' : 'enabled'}\n label={label}\n actionIcon=\"ChevronDown\"\n aria-label={`${label}, change where ${agentName} looks`}\n aria-haspopup=\"menu\"\n aria-expanded={open}\n onClickButton={(e: { currentTarget: HTMLElement }) => {\n setAnchor(e.currentTarget);\n setOpen((o) => !o);\n }}\n />\n }\n />\n {/* A real app keeps the conversation when the person leaves, and gives the list that holds the rows role=\"log\". */}\n <Stack gap=\"small\">\n <Message\n aria-label={question.from}\n avatar={<UserImage userHandle={question.from} decorative />}\n name={question.from}\n meta={<TimeStamp createdAt={question.at} dateFormat=\"absolute\" data=\"time\" />}\n >\n <Paragraph measure=\"none\">{question.text}</Paragraph>\n </Message>\n <Message\n aria-label={`${agentName}, agent`}\n avatar={<UserImage userHandle={agentName} icon={Bot} decorative />}\n name={agentName}\n meta={\n <>\n <Tag variant=\"contained\" size=\"small\" label=\"Agent\" />\n <TimeStamp createdAt={answeredAt} dateFormat=\"absolute\" data=\"time\" />\n <Paragraph size=\"caption\" tone=\"secondary\" measure=\"none\">Model name</Paragraph>\n </>\n }\n // The sources sit directly under the answer they support.\n footer={\n <Stack gap=\"medium\">\n <Cluster>\n <Tag variant=\"contained\" size=\"small\" color=\"success\" icon={Plug} label={kindsTag} />\n </Cluster>\n <Grid columns={2} gap=\"medium\">\n {sources.map((s) => (\n <SourceCard key={s.href} icon={kinds[s.kind].icon} title={s.title} meta={`${kinds[s.kind].label} · ${s.where}`} href={s.href} />\n ))}\n </Grid>\n <Cluster>\n {saved ? (\n <Button ref={openButton} size=\"small\" type=\"tertiary\" state=\"enabled\" label=\"Open in Docs\" decoIcon=\"FileText\" href=\"/docs/press-kit-owner\" />\n ) : (\n <Button size=\"small\" type=\"secondary\" state=\"enabled\" label=\"Save to Docs\" decoIcon=\"BookmarkPlus\" loading={saving} onClickButton={saveToDocs} />\n )}\n </Cluster>\n </Stack>\n }\n >\n <Markdown id=\"ask-page-answered-answer\" text={answer} headingLevel={3} />\n </Message>\n {turns.map((t) => {\n const place = t.scope ?? `all ${workspaces.length} of your workspaces`;\n const working = t.phase === 'running' || t.phase === 'stopping';\n return (\n <Stack key={t.id} gap=\"small\">\n <Message\n aria-label={me}\n avatar={<UserImage userHandle={me} decorative />}\n name={me}\n meta={<TimeStamp createdAt={new Date('2026-11-16T14:45:00Z')} dateFormat=\"absolute\" data=\"time\" />}\n >\n <Paragraph measure=\"none\">{t.text}</Paragraph>\n </Message>\n <Message\n aria-label={`${agentName}, agent`}\n avatar={<UserImage userHandle={agentName} icon={Bot} decorative />}\n name={agentName}\n meta={\n <>\n <Tag variant=\"contained\" size=\"small\" label=\"Agent\" />\n <TimeStamp createdAt={new Date('2026-11-16T14:45:00Z')} dateFormat=\"absolute\" data=\"time\" />\n <Paragraph size=\"caption\" tone=\"secondary\" measure=\"none\">Model name</Paragraph>\n </>\n }\n // The only Stop, on the row for the whole run. It shows loading while the run is stopping.\n footer={working ? (\n <Cluster>\n <Button size=\"small\" type=\"secondary\" state=\"enabled\" label=\"Stop\" loading={t.phase === 'stopping'} onClickButton={stop} />\n </Cluster>\n ) : undefined}\n >\n {working ? (\n // A real app wraps this part in a polite live region, since StepList has none.\n <Stack gap=\"medium\">\n <Paragraph size=\"caption\" tone=\"secondary\" measure=\"none\">{`Working for ${t.seconds} ${t.seconds === 1 ? 'second' : 'seconds'}`}</Paragraph>\n <StepList\n aria-label={`${agentName}'s steps`}\n steps={[\n { label: 'Read your question', status: 'done' },\n { label: `Looking in the docs, chats and tasks of ${place}`, status: 'running' },\n ]}\n />\n </Stack>\n ) : t.phase === 'stopped' ? (\n <Paragraph measure=\"none\">Stopped. Nothing was changed.</Paragraph>\n ) : (\n // It read nothing it could use, so the answer has no sources section.\n <Paragraph measure=\"none\">{`I found nothing about this in the docs, chats and tasks of ${place}. Try other words, or change where I look.`}</Paragraph>\n )}\n </Message>\n </Stack>\n );\n })}\n </Stack>\n <Stack gap=\"small\">\n {/* Where the agent looks, said above the box it is asked in. */}\n <Paragraph size=\"body2\" tone=\"secondary\" measure=\"none\">\n {scope ? `${agentName} looks in the docs, chats and tasks of ${scope}.` : `${agentName} looks in the docs, chats and tasks of all ${workspaces.length} of your workspaces.`}\n </Paragraph>\n <Composer\n ref={field}\n id=\"ask-page-answered-question\"\n aria-label={`Ask ${agentName}`}\n placeholder={`Ask ${agentName}`}\n value={text}\n onChange={setText}\n onSubmit={send}\n />\n </Stack>\n </Stack>\n <Popover open={open} anchorEl={anchor} onClose={() => setOpen(false)} returnFocus>\n <Menu navigable aria-label={`Where ${agentName} looks`} width={220}>\n <MenuItem size=\"small\" label={all} isSelected={scope === null} role=\"menuitemradio\" onClick={() => choose(null)} />\n <Line />\n {workspaces.map((w) => (\n <MenuItem key={w} size=\"small\" label={w} isSelected={scope === w} role=\"menuitemradio\" onClick={() => choose(w)} />\n ))}\n </Menu>\n </Popover>\n {/* A real app mounts one Toaster near its root. */}\n <Toaster />\n </AppShell>\n );\n}\n",
|
|
1033
1034
|
"uses": [
|
|
1034
1035
|
"AppShell",
|
|
1035
1036
|
"Button",
|
|
@@ -1037,6 +1038,7 @@
|
|
|
1037
1038
|
"Composer",
|
|
1038
1039
|
"Grid",
|
|
1039
1040
|
"Line",
|
|
1041
|
+
"Markdown",
|
|
1040
1042
|
"Menu",
|
|
1041
1043
|
"MenuItem",
|
|
1042
1044
|
"Message",
|
|
@@ -1121,16 +1123,21 @@
|
|
|
1121
1123
|
"Show a person who cannot change billing every section as text, with no Buttons, and one line: 'Only admins can change billing.'",
|
|
1122
1124
|
"Say who pays and where for a plan billed elsewhere: 'Ben Carter pays for this plan through an app store.' Say who can change it.",
|
|
1123
1125
|
"Leave out every control, price, card and invoice on a plan billed elsewhere.",
|
|
1124
|
-
"Show a status as the case 'Status in a row' says: 'Past due' and 'Canceling' as dots, 'Paid' as text."
|
|
1126
|
+
"Show a status as the case 'Status in a row' says: 'Past due' and 'Canceling' as dots, 'Paid' as text.",
|
|
1127
|
+
"Say the day a trial ends and the amount charged then, with how it is counted.",
|
|
1128
|
+
"Show a trial as a grey dot `Tag` 'Trial' by the plan name, as the case 'Status in a row' says. Then say 'Acme is on a free trial of Pro until Dec 1, 2026.' and 'Then Acme pays $24.00 each month: 3 members at $8.00 per member per month.'",
|
|
1129
|
+
"Offer a primary 'Add Payment Method' when a trial has no card. With a card, say 'Your card is charged $24.00 on Dec 1, 2026.' and offer a tertiary 'End Trial'.",
|
|
1130
|
+
"Confirm 'End Trial' in a small `Modal` titled 'End Trial': 'Acme moves to Free now. Nothing is charged.' 'Cancel' comes first, as the rule 'A confirm says exactly what will happen' says."
|
|
1125
1131
|
],
|
|
1126
1132
|
"dont": [
|
|
1127
1133
|
"Do not collect or show a card number. A card is only 'Visa ending in 4821', and it changes on the payment provider's own page.",
|
|
1128
1134
|
"Do not show Change Plan, Update or End Plan to someone who cannot use them. Show the text and the line that says who can.",
|
|
1129
1135
|
"Do not leave a failed payment without the date it must be fixed by.",
|
|
1130
1136
|
"Do not end the plan on the first click. Ask in a Modal first.",
|
|
1131
|
-
"Do not name the action 'Cancel Plan'. It would sit beside 'Cancel' in the confirm.",
|
|
1137
|
+
"Do not name the action 'Cancel Plan' or 'Cancel Trial'. It would sit beside 'Cancel' in the confirm.",
|
|
1132
1138
|
"Do not show a plan billed elsewhere with a 'Change Plan' Button that does nothing. Say where to change it.",
|
|
1133
|
-
"Do not write 'Canceled' for a plan that is still on. Say 'Canceling' and when it ends."
|
|
1139
|
+
"Do not write 'Canceled' for a plan that is still on. Say 'Canceling' and when it ends.",
|
|
1140
|
+
"Do not say 'Your trial ends soon' with no date or no amount."
|
|
1134
1141
|
],
|
|
1135
1142
|
"native": "On Apple a plan bought in the app is managed in the system subscription sheet. Show who pays and open that sheet from one Button, never a card form.",
|
|
1136
1143
|
"options": [
|
|
@@ -1138,7 +1145,7 @@
|
|
|
1138
1145
|
"id": "self-serve",
|
|
1139
1146
|
"title": "An admin pays here",
|
|
1140
1147
|
"useWhen": "The person who manages billing changes the plan, the card and the cancel on this page.",
|
|
1141
|
-
"source": "'use client';\nimport { useEffect, useRef, useState } from 'react';\nimport Modal from 'oneslash-design-system/components/modal';\nimport Alert from 'oneslash-design-system/components/alert';\nimport Surface from 'oneslash-design-system/components/surface';\nimport Heading from 'oneslash-design-system/components/heading';\nimport Paragraph from 'oneslash-design-system/components/paragraph';\nimport Progress from 'oneslash-design-system/components/progress';\nimport Tag from 'oneslash-design-system/components/tag';\nimport Link from 'oneslash-design-system/components/link';\nimport Button from 'oneslash-design-system/components/button';\nimport SettingsSection from 'oneslash-design-system/components/settingsSection';\nimport TitleBar from 'oneslash-design-system/components/titleBar';\nimport TableContainer from 'oneslash-design-system/components/tableContainer';\nimport TableHeader from 'oneslash-design-system/components/tableHeader';\nimport TableHeaderCell from 'oneslash-design-system/components/tableHeaderCell';\nimport TableRow from 'oneslash-design-system/components/tableRow';\nimport TableCell from 'oneslash-design-system/components/tableCell';\nimport { formatMoney } from 'oneslash-design-system/components/formatNumber';\nimport { Center, Cluster, Stack } from 'oneslash-design-system/components/layout';\n\n// A real app passes the router from its framework, such as Next's useRouter().\nconst router = { push: (url: string) => console.info(`Go to ${url}`) };\n\n// A real app reads this from the person's role. Only an admin can change billing.\nconst isAdmin = true;\n\n// A real app reads this from the server: set when the last payment failed.\nconst failedPayment: { fixBy: string } | null = { fixBy: 'Nov 30, 2026' };\n\nconst invoices = [\n { id: 'inv-0', date: 'Nov 1, 2026', amount: 24, status: 'Paid' },\n { id: '
|
|
1148
|
+
"source": "'use client';\nimport { useEffect, useRef, useState } from 'react';\nimport Modal from 'oneslash-design-system/components/modal';\nimport Alert from 'oneslash-design-system/components/alert';\nimport Surface from 'oneslash-design-system/components/surface';\nimport Heading from 'oneslash-design-system/components/heading';\nimport Paragraph from 'oneslash-design-system/components/paragraph';\nimport Progress from 'oneslash-design-system/components/progress';\nimport Tag from 'oneslash-design-system/components/tag';\nimport Link from 'oneslash-design-system/components/link';\nimport Button from 'oneslash-design-system/components/button';\nimport SettingsSection from 'oneslash-design-system/components/settingsSection';\nimport TitleBar from 'oneslash-design-system/components/titleBar';\nimport TableContainer from 'oneslash-design-system/components/tableContainer';\nimport TableHeader from 'oneslash-design-system/components/tableHeader';\nimport TableHeaderCell from 'oneslash-design-system/components/tableHeaderCell';\nimport TableRow from 'oneslash-design-system/components/tableRow';\nimport TableCell from 'oneslash-design-system/components/tableCell';\nimport { formatMoney } from 'oneslash-design-system/components/formatNumber';\nimport { Center, Cluster, Stack } from 'oneslash-design-system/components/layout';\n\n// A real app passes the router from its framework, such as Next's useRouter().\nconst router = { push: (url: string) => console.info(`Go to ${url}`) };\n\n// A real app reads this from the person's role. Only an admin can change billing.\nconst isAdmin = true;\n\n// A real app reads this from the server: set when the last payment failed.\nconst failedPayment: { fixBy: string } | null = { fixBy: 'Nov 30, 2026' };\n\nconst invoices = [\n { id: 'inv-0', kind: 'charge', date: 'Nov 1, 2026', amount: 24, status: 'Paid' },\n { id: 'ref-1', kind: 'refund', date: 'Oct 16, 2026', amount: -12, status: 'Issued' },\n { id: 'inv-1', kind: 'charge', date: 'Oct 1, 2026', amount: 24, status: 'Paid' },\n];\n\nexport default function BillingPageSelfServe() {\n const [canceling, setCanceling] = useState(false);\n const [confirmOpen, setConfirmOpen] = useState(false);\n const [busy, setBusy] = useState(false);\n const timer = useRef<ReturnType<typeof setTimeout>>();\n\n // Stops the request if the example goes away before it ends.\n useEffect(() => () => clearTimeout(timer.current), []);\n\n // Stands in for the request to the server.\n function request(done: () => void) {\n if (busy) return;\n setBusy(true);\n timer.current = setTimeout(() => {\n setBusy(false);\n done();\n }, 1200);\n }\n\n // Escape, a click outside and Cancel all close it, except while the request runs.\n function handleClose() {\n if (busy) return;\n setConfirmOpen(false);\n }\n\n return (\n <Center width=\"page\">\n <Stack gap=\"xlarge\">\n <TitleBar title=\"Billing\" />\n {failedPayment && (\n <Alert type=\"error\" variant=\"inline\" autoDismiss={false} message={`Your last payment did not go through. Update the payment method by ${failedPayment.fixBy} to keep Pro.`} />\n )}\n <SettingsSection id=\"billing-page-plan\" title=\"Plan\" description=\"What Acme pays for.\">\n <Stack gap=\"small\">\n <Cluster gap=\"small\">\n <Heading level={3} size=\"h6\">Pro</Heading>\n {failedPayment && <Tag variant=\"dot\" size=\"small\" color=\"error\" label=\"Past due\" />}\n {canceling && <Tag variant=\"dot\" size=\"small\" color=\"warning\" label=\"Canceling\" />}\n </Cluster>\n <Paragraph size=\"body2\" measure=\"none\">{`${formatMoney(8)} per member per month`}</Paragraph>\n <Paragraph tone=\"secondary\" size=\"body2\" measure=\"none\">{canceling ? 'Pro ends on Dec 1, 2026.' : 'Renews on Dec 1, 2026.'}</Paragraph>\n </Stack>\n {isAdmin ? (\n <Cluster gap=\"small\">\n {canceling ? (\n <Button size=\"small\" type=\"primary\" state=\"enabled\" label=\"Resume Plan\" loading={busy} onClickButton={() => request(() => setCanceling(false))} />\n ) : (\n <Button size=\"small\" type=\"secondary\" state=\"enabled\" label=\"Change Plan\" onClickButton={() => router.push('/settings/billing/plans')} />\n )}\n </Cluster>\n ) : (\n <Paragraph tone=\"secondary\" size=\"body2\" measure=\"none\">Only admins can change billing.</Paragraph>\n )}\n </SettingsSection>\n <SettingsSection id=\"billing-page-usage\" title=\"Usage\" description=\"This month.\">\n <Stack gap=\"medium\">\n <Progress label=\"AI agent responses\" value={312} max={1000} unit=\"responses\" />\n <Paragraph tone=\"secondary\" size=\"body2\" measure=\"none\">Resets on Dec 1.</Paragraph>\n <Progress label=\"Members\" value={3} max={null} unit=\"members\" />\n </Stack>\n </SettingsSection>\n <SettingsSection id=\"billing-page-payment\" title=\"Payment method\" description=\"Pays for Acme's plan.\">\n <Surface padding=\"small\">\n <Cluster justify=\"between\" gap=\"medium\">\n <Stack gap=\"small\">\n <Paragraph measure=\"none\">Visa ending in 4821</Paragraph>\n <Paragraph tone=\"secondary\" size=\"body2\" measure=\"none\">Expires 08/28</Paragraph>\n </Stack>\n {isAdmin && (\n // A real app hands off to its payment provider's own page here. The page never takes card details.\n <Button size=\"small\" type=\"tertiary\" state=\"enabled\" label=\"Update\" aria-label=\"Update Visa ending in 4821, opens in a new tab\" actionIcon=\"ExternalLink\" href=\"https://acme.example/billing/payment-method\" openInNewTab />\n )}\n </Cluster>\n </Surface>\n {/* Pro needs a card, so there is no Remove here. */}\n <Paragraph tone=\"secondary\" size=\"body2\" measure=\"none\">Pro needs a card on file. Downgrade to Free to remove it.</Paragraph>\n </SettingsSection>\n <SettingsSection id=\"billing-page-invoices\" title=\"Invoices\" description=\"The last three.\">\n <TableContainer aria-label=\"Recent invoices\" minWidth=\"520px\">\n <TableHeader>\n <TableRow>\n <TableHeaderCell width=\"140px\">Date</TableHeaderCell>\n <TableHeaderCell width=\"110px\" align=\"right\">Amount</TableHeaderCell>\n <TableHeaderCell>Status</TableHeaderCell>\n <TableHeaderCell width=\"130px\">Download</TableHeaderCell>\n </TableRow>\n </TableHeader>\n {invoices.map((inv) => (\n <TableRow key={inv.id}>\n <TableCell width=\"140px\">{inv.date}</TableCell>\n <TableCell width=\"110px\" align=\"right\">{formatMoney(inv.amount)}</TableCell>\n <TableCell><Tag variant=\"textOnly\" size=\"small\" label={inv.status} /></TableCell>\n <TableCell width=\"130px\">\n {/* A real app links to the file on its own server. */}\n <Button size=\"small\" type=\"tertiary\" state=\"enabled\" label=\"Download\" aria-label={`Download ${inv.kind === 'refund' ? 'refund' : 'invoice'} for ${inv.date}, opens in a new tab`} actionIcon=\"ExternalLink\" href={`https://acme.example/invoices/${inv.id}.pdf`} openInNewTab />\n </TableCell>\n </TableRow>\n ))}\n </TableContainer>\n <Link href=\"/settings/billing/invoices\" size=\"body2\">See All Invoices</Link>\n </SettingsSection>\n {isAdmin && !canceling && (\n // The last section on the page, in the danger color, as the case 'Danger zone' says.\n <SettingsSection id=\"billing-page-cancel\" tone=\"danger\" title=\"End plan\" description=\"Pro stays on until Dec 1, 2026.\">\n <Paragraph size=\"body2\" measure=\"none\">Acme goes back to Free on Dec 1, 2026. Its members and messages stay.</Paragraph>\n <Cluster>\n <Button size=\"small\" type=\"secondary\" state=\"enabled\" label=\"End Plan\" onClickButton={() => setConfirmOpen(true)} />\n </Cluster>\n </SettingsSection>\n )}\n </Stack>\n <Modal\n isOpen={confirmOpen}\n size=\"small\"\n title=\"End Plan\"\n onClose={handleClose}\n actions={\n <>\n <Button size=\"small\" type=\"tertiary\" state={busy ? 'disabled' : 'enabled'} label=\"Cancel\" onClickButton={handleClose} />\n <Button size=\"small\" type=\"primary\" state=\"enabled\" label=\"End Plan\" loading={busy} onClickButton={() => request(() => { setConfirmOpen(false); setCanceling(true); })} />\n </>\n }\n >\n <Paragraph measure=\"none\">Pro stays on until Dec 1, 2026. After that Acme is on Free, which allows 3 members and 50 AI agent responses a month.</Paragraph>\n <Paragraph tone=\"secondary\" size=\"body2\" measure=\"none\">Nothing is deleted. You can resume the plan until then.</Paragraph>\n </Modal>\n </Center>\n );\n}\n",
|
|
1142
1149
|
"uses": [
|
|
1143
1150
|
"Alert",
|
|
1144
1151
|
"Button",
|
|
@@ -1176,6 +1183,28 @@
|
|
|
1176
1183
|
"Stack",
|
|
1177
1184
|
"TitleBar"
|
|
1178
1185
|
]
|
|
1186
|
+
},
|
|
1187
|
+
{
|
|
1188
|
+
"id": "trial",
|
|
1189
|
+
"title": "A free trial",
|
|
1190
|
+
"useWhen": "The workspace is in a free trial of a paid plan.",
|
|
1191
|
+
"source": "'use client';\nimport { useEffect, useRef, useState } from 'react';\nimport Modal from 'oneslash-design-system/components/modal';\nimport Surface from 'oneslash-design-system/components/surface';\nimport Heading from 'oneslash-design-system/components/heading';\nimport Paragraph from 'oneslash-design-system/components/paragraph';\nimport Progress from 'oneslash-design-system/components/progress';\nimport Tag from 'oneslash-design-system/components/tag';\nimport Button from 'oneslash-design-system/components/button';\nimport EmptyBox from 'oneslash-design-system/components/emptyBox';\nimport SettingsSection from 'oneslash-design-system/components/settingsSection';\nimport TitleBar from 'oneslash-design-system/components/titleBar';\nimport { formatMoney } from 'oneslash-design-system/components/formatNumber';\nimport { Center, Cluster, Stack } from 'oneslash-design-system/components/layout';\n\n// A real app passes the router from its framework, such as Next's useRouter().\nconst router = { push: (url: string) => console.info(`Go to ${url}`) };\n\n// A real app reads these from the server. The price and the members match the case 'Plan picker'.\nconst members = 3;\nconst pricePerMember = 8;\nconst trialEnds = 'Dec 1, 2026';\n\n// A real app reads this from the server: null when no card is on file.\nconst card: string | null = 'Visa ending in 4821';\n\nexport default function BillingPageTrial() {\n const [trial, setTrial] = useState(true);\n const [confirmOpen, setConfirmOpen] = useState(false);\n const [busy, setBusy] = useState(false);\n const timer = useRef<ReturnType<typeof setTimeout>>();\n const planHeading = useRef<HTMLHeadingElement>(null);\n // Where focus goes after the next render, once the element it goes to is on screen.\n const focusNext = useRef<() => void>();\n\n // Stops the request if the example goes away before it ends.\n useEffect(() => () => clearTimeout(timer.current), []);\n\n useEffect(() => {\n const move = focusNext.current;\n focusNext.current = undefined;\n move?.();\n });\n\n // Escape, a click outside and Cancel all close it, except while the request runs.\n function handleClose() {\n if (busy) return;\n setConfirmOpen(false);\n }\n\n // Stands in for the request to the server. End Trial is gone after it, so focus goes to the plan, which now reads Free.\n function endTrial() {\n if (busy) return;\n setBusy(true);\n timer.current = setTimeout(() => {\n setBusy(false);\n setConfirmOpen(false);\n setTrial(false);\n focusNext.current = () => planHeading.current?.focus({ preventScroll: true });\n }, 1200);\n }\n\n return (\n <Center width=\"page\">\n <Stack gap=\"xlarge\">\n <TitleBar title=\"Billing\" />\n <SettingsSection id=\"billing-page-trial-plan\" title=\"Plan\" description=\"What Acme pays for.\">\n {trial ? (\n <Stack gap=\"small\">\n <Cluster gap=\"small\">\n <Heading ref={planHeading} tabIndex={-1} level={3} size=\"h6\">Pro</Heading>\n <Tag variant=\"dot\" size=\"small\" label=\"Trial\" />\n </Cluster>\n <Paragraph size=\"body2\" measure=\"none\">{`Acme is on a free trial of Pro until ${trialEnds}.`}</Paragraph>\n {/* The day it ends, the amount then, and how it is counted. */}\n <Paragraph size=\"body2\" measure=\"none\">\n {`Then Acme pays ${formatMoney(members * pricePerMember)} each month: ${members} members at ${formatMoney(pricePerMember)} per member per month.`}\n </Paragraph>\n {card && (\n <Paragraph tone=\"secondary\" size=\"body2\" measure=\"none\">{`Your card is charged ${formatMoney(members * pricePerMember)} on ${trialEnds}.`}</Paragraph>\n )}\n </Stack>\n ) : (\n <Stack gap=\"small\">\n <Heading ref={planHeading} tabIndex={-1} level={3} size=\"h6\">Free</Heading>\n <Paragraph size=\"body2\" measure=\"none\">{`${formatMoney(0)} per month`}</Paragraph>\n <Paragraph tone=\"secondary\" size=\"body2\" measure=\"none\">The trial ended. Nothing was charged.</Paragraph>\n </Stack>\n )}\n <Cluster gap=\"small\">\n {!trial ? (\n <Button size=\"small\" type=\"secondary\" state=\"enabled\" label=\"Change Plan\" onClickButton={() => router.push('/settings/billing/plans')} />\n ) : card ? (\n <Button size=\"small\" type=\"tertiary\" state=\"enabled\" label=\"End Trial\" onClickButton={() => setConfirmOpen(true)} />\n ) : (\n // A real app hands off to its payment provider's own page here. The page never takes card details.\n <Button size=\"small\" type=\"primary\" state=\"enabled\" label=\"Add Payment Method\" aria-label=\"Add payment method, opens in a new tab\" actionIcon=\"ExternalLink\" href=\"https://acme.example/billing/payment-method\" openInNewTab />\n )}\n </Cluster>\n </SettingsSection>\n <SettingsSection id=\"billing-page-trial-usage\" title=\"Usage\" description=\"This month.\">\n <Stack gap=\"medium\">\n <Progress label=\"AI agent responses\" value={312} max={1000} unit=\"responses\" />\n <Paragraph tone=\"secondary\" size=\"body2\" measure=\"none\">Resets on Dec 1.</Paragraph>\n <Progress label=\"Members\" value={members} max={null} unit=\"members\" />\n </Stack>\n </SettingsSection>\n <SettingsSection id=\"billing-page-trial-payment\" title=\"Payment method\" description=\"Pays for Acme's plan.\">\n {card ? (\n <Surface padding=\"small\">\n <Cluster justify=\"between\" gap=\"medium\">\n <Stack gap=\"small\">\n <Paragraph measure=\"none\">{card}</Paragraph>\n <Paragraph tone=\"secondary\" size=\"body2\" measure=\"none\">Expires 08/28</Paragraph>\n </Stack>\n {/* A real app hands off to its payment provider's own page here. */}\n <Button size=\"small\" type=\"tertiary\" state=\"enabled\" label=\"Update\" aria-label={`Update ${card}, opens in a new tab`} actionIcon=\"ExternalLink\" href=\"https://acme.example/billing/payment-method\" openInNewTab />\n </Cluster>\n </Surface>\n ) : (\n <Paragraph measure=\"none\">No payment method.</Paragraph>\n )}\n </SettingsSection>\n <SettingsSection id=\"billing-page-trial-invoices\" title=\"Invoices\" description=\"The last three.\">\n {/* A trial has paid nothing yet. The line says when the first invoice arrives. */}\n <EmptyBox size=\"small\" text=\"No invoices yet\" secondText=\"Your first invoice appears here after your first payment.\" />\n </SettingsSection>\n </Stack>\n <Modal\n isOpen={confirmOpen}\n size=\"small\"\n title=\"End Trial\"\n onClose={handleClose}\n actions={\n <>\n {/* 'Cancel' comes first, as in every confirm. */}\n <Button size=\"small\" type=\"tertiary\" state={busy ? 'disabled' : 'enabled'} label=\"Cancel\" onClickButton={handleClose} />\n <Button size=\"small\" type=\"primary\" state=\"enabled\" label=\"End Trial\" loading={busy} onClickButton={endTrial} />\n </>\n }\n >\n <Paragraph measure=\"none\">Acme moves to Free now. Nothing is charged.</Paragraph>\n <Paragraph tone=\"secondary\" size=\"body2\" measure=\"none\">Its members and messages stay.</Paragraph>\n </Modal>\n </Center>\n );\n}\n",
|
|
1192
|
+
"uses": [
|
|
1193
|
+
"Button",
|
|
1194
|
+
"Center",
|
|
1195
|
+
"Cluster",
|
|
1196
|
+
"EmptyBox",
|
|
1197
|
+
"Heading",
|
|
1198
|
+
"Modal",
|
|
1199
|
+
"Paragraph",
|
|
1200
|
+
"Progress",
|
|
1201
|
+
"SettingsSection",
|
|
1202
|
+
"Stack",
|
|
1203
|
+
"Surface",
|
|
1204
|
+
"Tag",
|
|
1205
|
+
"TitleBar",
|
|
1206
|
+
"formatMoney"
|
|
1207
|
+
]
|
|
1179
1208
|
}
|
|
1180
1209
|
]
|
|
1181
1210
|
},
|
|
@@ -1598,7 +1627,7 @@
|
|
|
1598
1627
|
"area": "menu",
|
|
1599
1628
|
"situation": "A person filters a list by a word, and the list should keep its room when they are not typing.",
|
|
1600
1629
|
"do": [
|
|
1601
|
-
"Use an `IconButton` with `iconName=\"Search\"` beside the list's heading, and open a `<Popover returnFocus>` with a search `TextField` from it.",
|
|
1630
|
+
"Use an `IconButton` with `iconName=\"Search\"` beside the list's heading, and open a `<Popover returnFocus aria-label=\"Search\">` with a search `TextField` from it.",
|
|
1602
1631
|
"Keep the words in the page, not in the Popover. The list stays filtered while the Popover is closed.",
|
|
1603
1632
|
"Show that a search is on: `color=\"secondary\"` on the button, and a line such as '2 of 5 invoices match \"north\".'.",
|
|
1604
1633
|
"Say the current search in the button's `ariaLabel`: 'Search: north'. It is plain 'Search' when no search is on.",
|
|
@@ -1620,7 +1649,7 @@
|
|
|
1620
1649
|
"id": "popover",
|
|
1621
1650
|
"title": "Search button with a Popover",
|
|
1622
1651
|
"useWhen": "A list has a header with little room, and a search is a filter the person sets once in a while.",
|
|
1623
|
-
"source": "'use client';\nimport { useRef, useState } from 'react';\nimport Heading from 'oneslash-design-system/components/heading';\nimport Paragraph from 'oneslash-design-system/components/paragraph';\nimport TextField from 'oneslash-design-system/components/textField';\nimport IconButton from 'oneslash-design-system/components/iconButton';\nimport Button from 'oneslash-design-system/components/button';\nimport Tooltip from 'oneslash-design-system/components/tooltip';\nimport Popover from 'oneslash-design-system/components/popover';\nimport Menu from 'oneslash-design-system/components/menu';\nimport List from 'oneslash-design-system/components/list';\nimport Surface from 'oneslash-design-system/components/surface';\nimport EmptyBox from 'oneslash-design-system/components/emptyBox';\nimport { Center, Cluster, Stack } from 'oneslash-design-system/components/layout';\n\n// A real app reads these from the server.\nconst invoices = ['Northwind, March', 'Harbor Studio, March', 'Lumen Labs, February', 'Northstar Dental, February', 'Pine and Co, January'];\n\nexport default function CollapsibleSearchPopover() {\n // The filter belongs to the page, not to the Popover: it stays when the Popover closes.\n const [query, setQuery] = useState('north');\n const [anchor, setAnchor] = useState<HTMLElement | null>(null);\n const [open, setOpen] = useState(false);\n const trigger = useRef<HTMLButtonElement | HTMLAnchorElement>(null);\n const words = query.trim();\n const on = words !== '';\n const found = invoices.filter((name) => name.toLowerCase().includes(words.toLowerCase()));\n\n function toggle(anchorEl: HTMLElement) {\n setAnchor(anchorEl);\n setOpen((o) => !o);\n }\n\n // Escape clears the search and closes. The field handles it before the Popover's own Escape, which only closes.\n // Enter closes and keeps the filter. A click outside and Tab close and keep it too.\n function keyDown(e: { key: string; preventDefault(): void }) {\n if (e.key === 'Escape') {\n e.preventDefault();\n setQuery('');\n setOpen(false);\n } else if (e.key === 'Enter') {\n e.preventDefault();\n setOpen(false);\n }\n }\n\n // The field is closed, so 'Clear Search' clears the filter and focus goes to the search button.\n function clearSearch() {\n setQuery('');\n trigger.current?.focus();\n }\n\n return (\n <Center width=\"page\">\n <Stack gap=\"large\">\n <Cluster gap=\"small\">\n <Heading level={1} size=\"h5\">Invoices</Heading>\n {/* A search that is on shows in a filled button and says what it is looking for. */}\n <Tooltip title={on ? `Search: ${words}` : 'Search'}>\n <IconButton\n ref={trigger}\n color={on ? 'secondary' : 'iconOnly'}\n state={open ? 'selected' : 'enabled'}\n size=\"small\"\n iconName=\"Search\"\n ariaLabel={on ? `Search: ${words}` : 'Search'}\n aria-haspopup=\"dialog\"\n aria-expanded={open}\n onClick={(e: { currentTarget: HTMLElement }) => toggle(e.currentTarget)}\n />\n </Tooltip>\n </Cluster>\n <Paragraph tone=\"secondary\" size=\"body2\" measure=\"none\">\n {on ? `${found.length} of ${invoices.length} invoices match \"${words}\".` : `All ${invoices.length} invoices.`}\n </Paragraph>\n {found.length > 0 ? (\n <Surface>\n <List items={found} size=\"body1\" />\n </Surface>\n ) : (\n <Surface align=\"center\" minHeight=\"short\">\n <EmptyBox\n size=\"large\"\n icon=\"Search\"\n text={`No invoices match \"${words}\"`}\n secondText=\"Check the spelling, or search for fewer words.\"\n action={<Button size=\"medium\" type=\"secondary\" state=\"enabled\" label=\"Clear Search\" onClickButton={clearSearch} />}\n />\n </Surface>\n )}\n </Stack>\n <Popover open={open} anchorEl={anchor} onClose={() => setOpen(false)} returnFocus>\n {/* Menu gives the Popover its surface and a width. It holds a field here, not items. */}\n <Menu width={288}>\n <TextField\n id=\"collapsible-search-query\"\n type=\"search\"\n size=\"small\"\n autoFocus\n aria-label=\"Search invoices\"\n placeholder=\"Search invoices\"\n value={query}\n onChange={(e) => setQuery(e.target.value)}\n onKeyDown={keyDown}\n />\n </Menu>\n </Popover>\n </Center>\n );\n}\n",
|
|
1652
|
+
"source": "'use client';\nimport { useRef, useState } from 'react';\nimport Heading from 'oneslash-design-system/components/heading';\nimport Paragraph from 'oneslash-design-system/components/paragraph';\nimport TextField from 'oneslash-design-system/components/textField';\nimport IconButton from 'oneslash-design-system/components/iconButton';\nimport Button from 'oneslash-design-system/components/button';\nimport Tooltip from 'oneslash-design-system/components/tooltip';\nimport Popover from 'oneslash-design-system/components/popover';\nimport Menu from 'oneslash-design-system/components/menu';\nimport List from 'oneslash-design-system/components/list';\nimport Surface from 'oneslash-design-system/components/surface';\nimport EmptyBox from 'oneslash-design-system/components/emptyBox';\nimport { Center, Cluster, Stack } from 'oneslash-design-system/components/layout';\n\n// A real app reads these from the server.\nconst invoices = ['Northwind, March', 'Harbor Studio, March', 'Lumen Labs, February', 'Northstar Dental, February', 'Pine and Co, January'];\n\nexport default function CollapsibleSearchPopover() {\n // The filter belongs to the page, not to the Popover: it stays when the Popover closes.\n const [query, setQuery] = useState('north');\n const [anchor, setAnchor] = useState<HTMLElement | null>(null);\n const [open, setOpen] = useState(false);\n const trigger = useRef<HTMLButtonElement | HTMLAnchorElement>(null);\n const words = query.trim();\n const on = words !== '';\n const found = invoices.filter((name) => name.toLowerCase().includes(words.toLowerCase()));\n\n function toggle(anchorEl: HTMLElement) {\n setAnchor(anchorEl);\n setOpen((o) => !o);\n }\n\n // Escape clears the search and closes. The field handles it before the Popover's own Escape, which only closes.\n // Enter closes and keeps the filter. A click outside and Tab close and keep it too.\n function keyDown(e: { key: string; preventDefault(): void }) {\n if (e.key === 'Escape') {\n e.preventDefault();\n setQuery('');\n setOpen(false);\n } else if (e.key === 'Enter') {\n e.preventDefault();\n setOpen(false);\n }\n }\n\n // The field is closed, so 'Clear Search' clears the filter and focus goes to the search button.\n function clearSearch() {\n setQuery('');\n trigger.current?.focus();\n }\n\n return (\n <Center width=\"page\">\n <Stack gap=\"large\">\n <Cluster gap=\"small\">\n <Heading level={1} size=\"h5\">Invoices</Heading>\n {/* A search that is on shows in a filled button and says what it is looking for. */}\n <Tooltip title={on ? `Search: ${words}` : 'Search'}>\n <IconButton\n ref={trigger}\n color={on ? 'secondary' : 'iconOnly'}\n state={open ? 'selected' : 'enabled'}\n size=\"small\"\n iconName=\"Search\"\n ariaLabel={on ? `Search: ${words}` : 'Search'}\n aria-haspopup=\"dialog\"\n aria-expanded={open}\n onClick={(e: { currentTarget: HTMLElement }) => toggle(e.currentTarget)}\n />\n </Tooltip>\n </Cluster>\n <Paragraph tone=\"secondary\" size=\"body2\" measure=\"none\">\n {on ? `${found.length} of ${invoices.length} invoices match \"${words}\".` : `All ${invoices.length} invoices.`}\n </Paragraph>\n {found.length > 0 ? (\n <Surface>\n <List items={found} size=\"body1\" />\n </Surface>\n ) : (\n <Surface align=\"center\" minHeight=\"short\">\n <EmptyBox\n size=\"large\"\n icon=\"Search\"\n text={`No invoices match \"${words}\"`}\n secondText=\"Check the spelling, or search for fewer words.\"\n action={<Button size=\"medium\" type=\"secondary\" state=\"enabled\" label=\"Clear Search\" onClickButton={clearSearch} />}\n />\n </Surface>\n )}\n </Stack>\n <Popover open={open} anchorEl={anchor} onClose={() => setOpen(false)} returnFocus aria-label=\"Search\">\n {/* Menu gives the Popover its surface and a width. It holds a field here, not items. */}\n <Menu width={288}>\n <TextField\n id=\"collapsible-search-query\"\n type=\"search\"\n size=\"small\"\n autoFocus\n aria-label=\"Search invoices\"\n placeholder=\"Search invoices\"\n value={query}\n onChange={(e) => setQuery(e.target.value)}\n onKeyDown={keyDown}\n />\n </Menu>\n </Popover>\n </Center>\n );\n}\n",
|
|
1624
1653
|
"uses": [
|
|
1625
1654
|
"Button",
|
|
1626
1655
|
"Center",
|
|
@@ -2000,6 +2029,71 @@
|
|
|
2000
2029
|
}
|
|
2001
2030
|
]
|
|
2002
2031
|
},
|
|
2032
|
+
{
|
|
2033
|
+
"id": "cookie-choice",
|
|
2034
|
+
"title": "Cookie choice",
|
|
2035
|
+
"kind": "design",
|
|
2036
|
+
"level": "organism",
|
|
2037
|
+
"area": "marketing",
|
|
2038
|
+
"situation": "A site sets cookies it does not need to run, and asks the visitor whether it may.",
|
|
2039
|
+
"do": [
|
|
2040
|
+
"Ask only when the site sets a cookie it does not need. A cookie that keeps a person logged in needs no question.",
|
|
2041
|
+
"Put the banner in a `Surface` at the top of the page, in the normal flow, before the `SiteHeader`, so Tab reaches it first and it covers nothing.",
|
|
2042
|
+
"Name it with a `Heading level={2}` 'Cookies on Acme', and say in one `Paragraph` what each choice does: 'Acme uses cookies to keep you logged in. Accept All also allows cookies that count visits and cookies for marketing. Reject All turns both off.'",
|
|
2043
|
+
"Make Reject as easy as Accept: 'Accept All' and 'Reject All' are both secondary, side by side, then a tertiary 'Choose Cookies'.",
|
|
2044
|
+
"Remove the banner on any choice and move focus to the page's `main`. Give `PageShell` a `ref` and `tabIndex={-1}`.",
|
|
2045
|
+
"Show the choices in a `Modal` 'Cookie Settings' with one `Switch` for each kind: 'Needed to run the site' on and `disabled`, then 'Visit counts' and 'Marketing'.",
|
|
2046
|
+
"Leave every choice off until the visitor turns it on.",
|
|
2047
|
+
"Give the group one Save Button, 'Save Choices', with 'Cancel' beside it, as the rule 'A setting saves in place, or with one Save Button' says. Every Switch here waits for it, and none saves on its own.",
|
|
2048
|
+
"Keep it disabled until a switch changes from what was saved, then show 'Saved' in place of the label for 2 seconds. From the banner nothing is saved yet, so 'Save Choices' is enabled at once.",
|
|
2049
|
+
"Link 'Cookie Settings' in the footer to the page that holds the choice, such as the privacy page, and open the `Modal` there. The visitor can change the choice at any time."
|
|
2050
|
+
],
|
|
2051
|
+
"dont": [
|
|
2052
|
+
"Do not fix a banner over the page. It hides content at 375px and at 400% zoom.",
|
|
2053
|
+
"Do not make 'Accept' the only primary Button. Consent is not the page's main action.",
|
|
2054
|
+
"Do not block the page behind a wall until the visitor chooses.",
|
|
2055
|
+
"Do not turn a switch on before the visitor chooses.",
|
|
2056
|
+
"Do not hide Reject in the settings. It sits beside Accept."
|
|
2057
|
+
],
|
|
2058
|
+
"native": "An app uses the system tracking prompt (App Tracking Transparency on Apple) and never a banner.",
|
|
2059
|
+
"options": [
|
|
2060
|
+
{
|
|
2061
|
+
"id": "banner",
|
|
2062
|
+
"title": "Banner at the top of the page",
|
|
2063
|
+
"useWhen": "The site sets cookies it does not need to run, such as for visit counts, and the visitor has not chosen yet.",
|
|
2064
|
+
"source": "'use client';\nimport { useEffect, useRef, useState } from 'react';\nimport Surface from 'oneslash-design-system/components/surface';\nimport Heading from 'oneslash-design-system/components/heading';\nimport Paragraph from 'oneslash-design-system/components/paragraph';\nimport Button from 'oneslash-design-system/components/button';\nimport Modal from 'oneslash-design-system/components/modal';\nimport Switch from 'oneslash-design-system/components/switch';\nimport SiteHeader from 'oneslash-design-system/components/siteHeader';\nimport PageShell from 'oneslash-design-system/components/pageShell';\nimport { Center, Cluster, Stack } from 'oneslash-design-system/components/layout';\n\nconst links = [\n { label: 'Features', href: '#features' },\n { label: 'Pricing', href: '#pricing' },\n { label: 'Docs', href: '#docs' },\n];\n\nexport default function CookieChoiceBanner() {\n const [chosen, setChosen] = useState(false);\n const [choosing, setChoosing] = useState(false);\n // Every optional cookie starts off. Only the visitor turns one on.\n const [visits, setVisits] = useState(false);\n const [marketing, setMarketing] = useState(false);\n const main = useRef<HTMLElement>(null);\n\n // The banner is gone, so focus moves to the page the visitor came to read.\n // This runs after the Modal has tried to give focus back to 'Choose Cookies', which is gone too.\n useEffect(() => {\n if (chosen) main.current?.focus({ preventScroll: true });\n }, [chosen]);\n\n // A real site keeps the choice in the browser, and sets a visit count or marketing cookie only when it is on.\n function choose(next: { visits: boolean; marketing: boolean }) {\n setVisits(next.visits);\n setMarketing(next.marketing);\n setChoosing(false);\n setChosen(true);\n }\n\n // Cancel puts every switch back off. The banner stays until the visitor chooses.\n function handleCancel() {\n setVisits(false);\n setMarketing(false);\n setChoosing(false);\n }\n\n return (\n <>\n {/* In the page flow, before the header, so Tab reaches it first. It never covers the page, and the page stays usable. */}\n {!chosen && (\n <Center width=\"page\">\n <Surface padding=\"small\">\n <Stack gap=\"medium\">\n <Stack gap=\"small\">\n <Heading level={2} size=\"h6\">Cookies on Acme</Heading>\n <Paragraph size=\"body2\" measure=\"none\">Acme uses cookies to keep you logged in. Accept All also allows cookies that count visits and cookies for marketing. Reject All turns both off.</Paragraph>\n </Stack>\n {/* Accept and Reject have the same weight, side by side. Neither is the page's main action. */}\n <Cluster gap=\"small\">\n <Button size=\"medium\" type=\"secondary\" state=\"enabled\" label=\"Accept All\" onClickButton={() => choose({ visits: true, marketing: true })} />\n <Button size=\"medium\" type=\"secondary\" state=\"enabled\" label=\"Reject All\" onClickButton={() => choose({ visits: false, marketing: false })} />\n <Button size=\"medium\" type=\"tertiary\" state=\"enabled\" label=\"Choose Cookies\" onClickButton={() => setChoosing(true)} />\n </Cluster>\n </Stack>\n </Surface>\n </Center>\n )}\n <SiteHeader\n brand={{ href: '#top', name: 'Acme' }}\n links={links}\n actions={<Button size=\"medium\" type=\"tertiary\" state=\"enabled\" label=\"Log In\" href=\"#log-in\" />}\n phoneAction={<Button size=\"medium\" type=\"primary\" state=\"enabled\" label=\"Sign Up\" href=\"#sign-up\" />}\n mainId=\"cookie-choice-banner-main\"\n />\n {/* tabIndex -1 lets the skip link and the banner move focus here. */}\n <PageShell ref={main} id=\"cookie-choice-banner-main\" tabIndex={-1}>\n <Stack gap=\"large\">\n <Heading level={1} size=\"h5\">Share files and decide together</Heading>\n <Paragraph tone=\"secondary\" measure=\"none\">Acme keeps a small team's files, notes and decisions in one place.</Paragraph>\n </Stack>\n </PageShell>\n <Modal\n isOpen={choosing}\n size=\"small\"\n title=\"Cookie Settings\"\n onClose={handleCancel}\n actions={\n <>\n <Button size=\"small\" type=\"tertiary\" state=\"enabled\" label=\"Cancel\" onClickButton={handleCancel} />\n {/* No choice is saved yet, so Save is enabled at once: saving every switch off is a choice. */}\n <Button size=\"small\" type=\"primary\" state=\"enabled\" label=\"Save Choices\" onClickButton={() => choose({ visits, marketing })} />\n </>\n }\n >\n <Stack gap=\"medium\">\n <Switch id=\"cookie-choice-banner-needed\" label=\"Needed to run the site\" description=\"Keeps you logged in. Always on.\" checked disabled onChange={() => {}} />\n <Switch id=\"cookie-choice-banner-visits\" label=\"Visit counts\" checked={visits} onChange={setVisits} />\n <Switch id=\"cookie-choice-banner-marketing\" label=\"Marketing\" checked={marketing} onChange={setMarketing} />\n </Stack>\n </Modal>\n </>\n );\n}\n",
|
|
2065
|
+
"uses": [
|
|
2066
|
+
"Button",
|
|
2067
|
+
"Center",
|
|
2068
|
+
"Cluster",
|
|
2069
|
+
"Heading",
|
|
2070
|
+
"Modal",
|
|
2071
|
+
"PageShell",
|
|
2072
|
+
"Paragraph",
|
|
2073
|
+
"SiteHeader",
|
|
2074
|
+
"Stack",
|
|
2075
|
+
"Surface",
|
|
2076
|
+
"Switch"
|
|
2077
|
+
]
|
|
2078
|
+
},
|
|
2079
|
+
{
|
|
2080
|
+
"id": "settings",
|
|
2081
|
+
"title": "Settings from the footer",
|
|
2082
|
+
"useWhen": "The visitor opens 'Cookie Settings' from the footer to change a choice.",
|
|
2083
|
+
"source": "'use client';\nimport { useEffect, useRef, useState } from 'react';\nimport Modal from 'oneslash-design-system/components/modal';\nimport Switch from 'oneslash-design-system/components/switch';\nimport Button from 'oneslash-design-system/components/button';\nimport Heading from 'oneslash-design-system/components/heading';\nimport Paragraph from 'oneslash-design-system/components/paragraph';\nimport SiteFooter from 'oneslash-design-system/components/siteFooter';\nimport { Center, Stack } from 'oneslash-design-system/components/layout';\n\ntype Choices = { visits: boolean; marketing: boolean };\n\nexport default function CookieChoiceSettings() {\n // Opens on the Modal, as if the visitor just chose 'Cookie Settings' in the footer.\n const [open, setOpen] = useState(true);\n // The visitor's last choice, kept in the browser. Here they chose Reject All, so every optional cookie is off.\n const [saved, setSaved] = useState<Choices>({ visits: false, marketing: false });\n const [draft, setDraft] = useState<Choices>(saved);\n const [justSaved, setJustSaved] = useState(false);\n const savedTimer = useRef<ReturnType<typeof setTimeout>>();\n // Save is disabled while the switches match what was saved, and while 'Saved' shows it stays enabled.\n const changed = draft.visits !== saved.visits || draft.marketing !== saved.marketing;\n\n // Stops the 'Saved' timer if the example goes away before it ends.\n useEffect(() => () => clearTimeout(savedTimer.current), []);\n\n // One Save for the group. The choice is kept in the browser, so it saves at once, and 'Saved' shows for 2 seconds.\n // A press while 'Saved' shows and nothing changed does nothing.\n function handleSave() {\n if (!changed) return;\n setSaved(draft);\n setJustSaved(true);\n clearTimeout(savedTimer.current);\n savedTimer.current = setTimeout(() => setJustSaved(false), 2000);\n }\n\n // Cancel, Escape and a click outside drop what was not saved.\n function handleClose() {\n setDraft(saved);\n setJustSaved(false);\n setOpen(false);\n }\n\n return (\n <>\n <Stack gap=\"huge\">\n <Center width=\"page\">\n <Stack gap=\"large\">\n <Heading level={1} size=\"h5\">Privacy</Heading>\n <Paragraph tone=\"secondary\" measure=\"none\">Acme uses cookies to keep you logged in. Visit counts and marketing stay off until you turn them on.</Paragraph>\n </Stack>\n </Center>\n {/* The footer's 'Cookie Settings' link comes to this page, which opens the Modal. The visitor can change the choice at any time. */}\n <SiteFooter\n brand={{ href: '#top', name: 'Acme' }}\n links={[\n { label: 'Terms', href: '#terms' },\n { label: 'Privacy', href: '#privacy' },\n { label: 'Cookie Settings', href: '#cookie-settings' },\n ]}\n legal=\"© 2026 Acme. All rights reserved.\"\n />\n </Stack>\n <Modal\n isOpen={open}\n size=\"small\"\n title=\"Cookie Settings\"\n onClose={handleClose}\n actions={\n <>\n <Button size=\"small\" type=\"tertiary\" state=\"enabled\" label=\"Cancel\" onClickButton={handleClose} />\n <Button size=\"small\" type=\"primary\" state={changed || justSaved ? 'enabled' : 'disabled'} label={justSaved ? 'Saved' : 'Save Choices'} onClickButton={handleSave} />\n </>\n }\n >\n <Stack gap=\"medium\">\n <Switch id=\"cookie-choice-settings-needed\" label=\"Needed to run the site\" description=\"Keeps you logged in. Always on.\" checked disabled onChange={() => {}} />\n <Switch id=\"cookie-choice-settings-visits\" label=\"Visit counts\" checked={draft.visits} onChange={(visits) => setDraft((d) => ({ ...d, visits }))} />\n <Switch id=\"cookie-choice-settings-marketing\" label=\"Marketing\" checked={draft.marketing} onChange={(marketing) => setDraft((d) => ({ ...d, marketing }))} />\n </Stack>\n </Modal>\n </>\n );\n}\n",
|
|
2084
|
+
"uses": [
|
|
2085
|
+
"Button",
|
|
2086
|
+
"Center",
|
|
2087
|
+
"Heading",
|
|
2088
|
+
"Modal",
|
|
2089
|
+
"Paragraph",
|
|
2090
|
+
"SiteFooter",
|
|
2091
|
+
"Stack",
|
|
2092
|
+
"Switch"
|
|
2093
|
+
]
|
|
2094
|
+
}
|
|
2095
|
+
]
|
|
2096
|
+
},
|
|
2003
2097
|
{
|
|
2004
2098
|
"id": "create-modal",
|
|
2005
2099
|
"title": "Create modal",
|
|
@@ -2166,7 +2260,7 @@
|
|
|
2166
2260
|
"id": "numbers-first",
|
|
2167
2261
|
"title": "Numbers first",
|
|
2168
2262
|
"useWhen": "The page reports how things went, for a lead who checks on a team.",
|
|
2169
|
-
"source": "'use client';\nimport { useEffect, useRef, useState } from 'react';\nimport AppShell from 'oneslash-design-system/components/appShell';\nimport TitleBar from 'oneslash-design-system/components/titleBar';\nimport SegmentedControl from 'oneslash-design-system/components/segmentedControl';\nimport SettingsSection from 'oneslash-design-system/components/settingsSection';\nimport Navigation from 'oneslash-design-system/components/navigation';\nimport MenuItem from 'oneslash-design-system/components/menuItem';\nimport StatTile from 'oneslash-design-system/components/statTile';\nimport Progress from 'oneslash-design-system/components/progress';\nimport Skeleton from 'oneslash-design-system/components/skeleton';\nimport Alert from 'oneslash-design-system/components/alert';\nimport Button from 'oneslash-design-system/components/button';\nimport Paragraph from 'oneslash-design-system/components/paragraph';\nimport EmptyBox from 'oneslash-design-system/components/emptyBox';\nimport List from 'oneslash-design-system/components/list';\nimport BarChart from 'oneslash-design-system/components/barChart';\nimport { formatCount } from 'oneslash-design-system/components/formatNumber';\nimport { Cluster, Grid, Stack } from 'oneslash-design-system/components/layout';\n\ntype Range = 'week' | 'month' | 'quarter';\nconst ranges = [\n { value: 'week', label: 'Week' },\n { value: 'month', label: 'Month' },\n { value: 'quarter', label: 'Quarter' },\n];\n\n// A real app counts these on the server. One range drives every number on the page.\nconst data = {\n week: {\n stats: { comments: [1240, 1106], done: [312, 280], people: [18, 18], reply: [8_640_000, 9_200_000] },\n projects: [['Website', 540], ['Mobile App', 380], ['Docs', 320]],\n waiting: [\n ['Ben Carter asked for the new screens', '/comments/1'],\n ['Omar Reyes mentioned you in Launch plan', '/comments/2'],\n ['Review the pricing copy', '/comments/3'],\n ],\n questions: [],\n },\n month: {\n stats: { comments: [4820, 5210], done: [1190, 1004], people: [31, 27], reply: [7_800_000, 8_100_000] },\n projects: [['Website', 2010], ['Mobile App', 1500], ['Docs', 910], ['Help Center', 400]],\n waiting: [\n ['Ben Carter asked for the new screens', '/comments/1'],\n ['Omar Reyes mentioned you in Launch plan', '/comments/2'],\n ['Review the pricing copy', '/comments/3'],\n ['Confirm the release date', '/comments/4'],\n ['Approve the new onboarding text', '/comments/5'],\n ],\n questions: [['Is the new pricing public before Friday?', '/questions/1'], ['Who approves the final copy?', '/questions/2']],\n },\n quarter: {\n stats: { comments: [15_880, 12_410], done: [3950, 3210], people: [44, 36], reply: [7_200_000, 7_900_000] },\n projects: [['Website', 6100], ['Mobile App', 4800], ['Docs', 3100], ['Help Center', 1880]],\n waiting: [\n ['Ben Carter asked for the new screens', '/comments/1'],\n ['Omar Reyes mentioned you in Launch plan', '/comments/2'],\n ['Review the pricing copy', '/comments/3'],\n ['Confirm the release date', '/comments/4'],\n ],\n questions: [['Is the new pricing public before Friday?', '/questions/1'], ['Who approves the final copy?', '/questions/2'], ['Which logo should the launch page use?', '/questions/3']],\n },\n} as const;\n\nconst noun: Record<Range, string> = { week: 'this week', month: 'this month', quarter: 'this quarter' };\n\nconst months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];\n// 'Nov 14' for the day `back` days before Nov 16, 2026. Written from UTC, so the server and the browser agree.\nfunction day(back: number) {\n const d = new Date(Date.UTC(2026, 10, 16 - back));\n return `${months[d.getUTCMonth()]} ${d.getUTCDate()}`;\n}\n\n// New comments per day, adding up to the tile above. The quarter is counted by week: 13 weeks, the last from Nov 10 to Nov 16.\nconst week = [152, 168, 149, 181, 190, 186, 214];\nconst month = [144, 157, 148, 162, 153, 145, 159, 150, 164, 155, 147, 160, 152, 166, 157, 149, 162, 153, 168, 159, 151, 164, 155, ...week];\nconst quarter = [1181, 1234, 1216, 1198, 1251, 1233, 1215, 1197, 1250, 1232, 1214, 1219, 1240];\nconst perDay: Record<Range, { label: string; value: number }[]> = {\n week: week.map((value, i) => ({ label: day(6 - i), value })),\n month: month.map((value, i) => ({ label: day(29 - i), value })),\n quarter: quarter.map((value, i) => ({ label: day(6 + (12 - i) * 7), value })),\n};\n\n// The summary says what changed, written from the same data the chart draws.\nfunction summary(range: Range) {\n const points = perDay[range];\n const first = points[0];\n const last = points[points.length - 1];\n const when = (p: { label: string }) => (range === 'quarter' ? `in the week of ${p.label}` : `on ${p.label}`);\n const move = last.value > first.value ? 'rose' : last.value < first.value ? 'fell' : 'stayed';\n return move === 'stayed'\n ? `Comments stayed at ${formatCount(first.value)} from ${first.label} to ${last.label}.`\n : `Comments ${move} from ${formatCount(first.value)} ${when(first)} to ${formatCount(last.value)} ${when(last)}.`;\n}\n\nexport default function DashboardNumbersFirst() {\n const [range, setRange] = useState<Range>('week');\n // The numbers load again when the range changes.\n const [loading, setLoading] = useState(false);\n // The projects section fails first, so the rest of the page shows that one section can fail alone.\n const [projectsFailed, setProjectsFailed] = useState(true);\n const [retrying, setRetrying] = useState(false);\n // The chart starts loaded. A real app sets this when the chart's request fails.\n const [trendFailed, setTrendFailed] = useState(false);\n const [trendRetrying, setTrendRetrying] = useState(false);\n const [navOpen, setNavOpen] = useState(false);\n const timer = useRef<ReturnType<typeof setTimeout>>();\n const retryTimer = useRef<ReturnType<typeof setTimeout>>();\n const trendTimer = useRef<ReturnType<typeof setTimeout>>();\n\n // Stops the requests if the example goes away before they end.\n useEffect(() => () => {\n clearTimeout(timer.current);\n clearTimeout(retryTimer.current);\n clearTimeout(trendTimer.current);\n }, []);\n\n function changeRange(next: string) {\n clearTimeout(timer.current);\n setRange(next as Range);\n setLoading(true);\n // Stands in for the request to the server.\n timer.current = setTimeout(() => setLoading(false), 600);\n }\n\n function tryAgain() {\n if (retrying) return;\n setRetrying(true);\n retryTimer.current = setTimeout(() => {\n setRetrying(false);\n setProjectsFailed(false);\n }, 1200);\n }\n\n function tryTrendAgain() {\n if (trendRetrying) return;\n setTrendRetrying(true);\n trendTimer.current = setTimeout(() => {\n setTrendRetrying(false);\n setTrendFailed(false);\n }, 1200);\n }\n\n const d = data[range];\n const period = range;\n const projectTotal = d.projects.reduce((sum, p) => sum + p[1], 0);\n const waitingCount: number = d.waiting.length;\n\n const sidebar = (\n <Navigation aria-label=\"Main\">\n <Paragraph size=\"body1\" measure=\"none\">Acme</Paragraph>\n {[\n ['Dashboard', 'LayoutDashboard', '/dashboard'],\n ['Comments', 'MessageSquare', '/comments'],\n ['Projects', 'FolderKanban', '/projects'],\n ].map(([label, icon, href]) => (\n <MenuItem\n key={href}\n size=\"small\"\n label={label}\n iconName={icon}\n href={href}\n isSelected={href === '/dashboard'}\n aria-current={href === '/dashboard' ? 'page' : undefined}\n onClick={(event: { preventDefault: () => void }) => {\n // A real app lets the link go to its page. The example stays here.\n event.preventDefault();\n }}\n />\n ))}\n </Navigation>\n );\n\n const statRow = (\n <SettingsSection key=\"stats\" title={`Numbers ${noun[range]}`} id=\"dashboard-stats\">\n <Grid compact columns={4}>\n <StatTile label=\"New comments\" value={d.stats.comments[0]} previous={d.stats.comments[1]} period={period} loading={loading} />\n <StatTile label=\"Marked done\" value={d.stats.done[0]} previous={d.stats.done[1]} period={period} loading={loading} />\n <StatTile label=\"People engaged\" value={d.stats.people[0]} previous={d.stats.people[1]} period={period} loading={loading} />\n <StatTile label=\"Average reply time\" value={d.stats.reply[0]} format=\"duration\" previous={d.stats.reply[1]} period={period} loading={loading} />\n </Grid>\n </SettingsSection>\n );\n\n // A trend over the range goes under the stat row, over the same range.\n const trend = (\n <SettingsSection key=\"trend\" title={`Comments ${noun[range]}`} id=\"dashboard-trend\">\n {trendFailed ? (\n <>\n {/* Only the chart failed, as the case 'Load failure' says. The rest of the page still shows. */}\n <Alert type=\"error\" variant=\"inline\" message=\"Could not load comments.\" autoDismiss={false} />\n <Cluster>\n <Button size=\"small\" type=\"primary\" state=\"enabled\" label=\"Try Again\" loading={trendRetrying} onClickButton={tryTrendAgain} />\n </Cluster>\n </>\n ) : (\n <BarChart\n id=\"dashboard-comments-per-day\"\n title={range === 'quarter' ? 'Comments per week' : 'Comments per day'}\n summary={summary(range)}\n data={perDay[range]}\n unit=\"comments\"\n labelHeader={range === 'quarter' ? 'Week of' : 'Date'}\n loading={loading}\n emptyText={`No comments ${noun[range]}`}\n />\n )}\n </SettingsSection>\n );\n\n const projects = (\n <SettingsSection key=\"projects\" title=\"Projects\" description={`${formatCount(projectTotal)} comments ${noun[range]}, by project`} id=\"dashboard-projects\">\n {projectsFailed ? (\n <>\n {/* Only this section failed. The rest of the page still shows. */}\n <Alert type=\"error\" variant=\"inline\" message=\"Could not load projects.\" autoDismiss={false} />\n <Cluster>\n <Button size=\"small\" type=\"primary\" state=\"enabled\" label=\"Try Again\" loading={retrying} onClickButton={tryAgain} />\n </Cluster>\n </>\n ) : loading ? (\n <Skeleton variant=\"text\" lines={3} label=\"Loading projects\" />\n ) : (\n <List\n size=\"body2\"\n items={d.projects.map(([name, count]) => (\n <Progress key={name} kind=\"share\" label={name} value={count} max={projectTotal} unit=\"comments\" />\n ))}\n />\n )}\n </SettingsSection>\n );\n\n const waiting = (\n <SettingsSection key=\"waiting\" title={loading ? 'Waiting on you' : `${formatCount(waitingCount)} ${waitingCount === 1 ? 'comment' : 'comments'} waiting on you`} description={`Asked of you ${noun[range]}`} id=\"dashboard-waiting\">\n {loading ? (\n <Skeleton variant=\"text\" lines={3} label=\"Loading what waits on you\" />\n ) : (\n <Stack gap=\"small\">\n {d.waiting.map(([text, href]) => (\n <MenuItem\n key={href}\n size=\"medium\"\n label={text}\n href={href}\n onClick={(event: { preventDefault: () => void }) => {\n // A real app lets the link go to its page. The example stays here.\n event.preventDefault();\n }}\n />\n ))}\n </Stack>\n )}\n </SettingsSection>\n );\n\n const questions = (\n <SettingsSection key=\"questions\" title=\"Questions from your agents\" id=\"dashboard-questions\">\n {loading ? (\n <Skeleton variant=\"text\" lines={2} label=\"Loading questions\" />\n ) : d.questions.length === 0 ? (\n // A section with nothing keeps its place and says what will fill it.\n <EmptyBox size=\"small\" text={`No questions from your agents ${noun[range]}`} secondText=\"Questions your agents ask you appear here.\" />\n ) : (\n <Stack gap=\"small\">\n {d.questions.map(([text, href]) => (\n <MenuItem\n key={href}\n size=\"medium\"\n label={text}\n href={href}\n onClick={(event: { preventDefault: () => void }) => {\n // A real app lets the link go to its page. The example stays here.\n event.preventDefault();\n }}\n />\n ))}\n </Stack>\n )}\n </SettingsSection>\n );\n\n return (\n <AppShell title=\"Dashboard\" navOpen={navOpen} onNavOpenChange={setNavOpen} sidebar={sidebar}>\n <Stack gap=\"xlarge\">\n {/* One range drives every number below, and each heading says which one. */}\n {/* Below md the range switch takes its own line under the title. */}\n <TitleBar\n title=\"Dashboard\"\n actionsBelow\n actions={<SegmentedControl size=\"small\" width=\"fit\" aria-label=\"Range\" options={ranges} value={range} onChange={changeRange} />}\n />\n {statRow}\n {trend}\n {projects}\n {waiting}\n {questions}\n </Stack>\n </AppShell>\n );\n}\n",
|
|
2263
|
+
"source": "'use client';\nimport { useEffect, useRef, useState } from 'react';\nimport AppShell from 'oneslash-design-system/components/appShell';\nimport TitleBar from 'oneslash-design-system/components/titleBar';\nimport SegmentedControl from 'oneslash-design-system/components/segmentedControl';\nimport SettingsSection from 'oneslash-design-system/components/settingsSection';\nimport Navigation from 'oneslash-design-system/components/navigation';\nimport MenuItem from 'oneslash-design-system/components/menuItem';\nimport StatTile from 'oneslash-design-system/components/statTile';\nimport Progress from 'oneslash-design-system/components/progress';\nimport Skeleton from 'oneslash-design-system/components/skeleton';\nimport Alert from 'oneslash-design-system/components/alert';\nimport Button from 'oneslash-design-system/components/button';\nimport Paragraph from 'oneslash-design-system/components/paragraph';\nimport EmptyBox from 'oneslash-design-system/components/emptyBox';\nimport List from 'oneslash-design-system/components/list';\nimport BarChart from 'oneslash-design-system/components/barChart';\nimport { formatCount } from 'oneslash-design-system/components/formatNumber';\nimport { Cluster, Grid, Stack } from 'oneslash-design-system/components/layout';\n\ntype Range = 'week' | 'month' | 'quarter';\nconst ranges = [\n { value: 'week', label: 'Week' },\n { value: 'month', label: 'Month' },\n { value: 'quarter', label: 'Quarter' },\n];\n\n// A real app counts these on the server. One range drives every number on the page.\nconst data = {\n week: {\n stats: { comments: [1240, 1106], done: [312, 280], people: [18, 18], reply: [8_640_000, 9_200_000] },\n projects: [['Website', 540], ['Mobile App', 380], ['Docs', 320]],\n waiting: [\n ['Ben Carter asked for the new screens', '/comments/1'],\n ['Omar Reyes mentioned you in Launch plan', '/comments/2'],\n ['Review the pricing copy', '/comments/3'],\n ],\n questions: [],\n },\n month: {\n stats: { comments: [4820, 5210], done: [1190, 1004], people: [31, 27], reply: [7_800_000, 8_100_000] },\n projects: [['Website', 2010], ['Mobile App', 1500], ['Docs', 910], ['Help Center', 400]],\n waiting: [\n ['Ben Carter asked for the new screens', '/comments/1'],\n ['Omar Reyes mentioned you in Launch plan', '/comments/2'],\n ['Review the pricing copy', '/comments/3'],\n ['Confirm the release date', '/comments/4'],\n ['Approve the new onboarding text', '/comments/5'],\n ],\n questions: [['Is the new pricing public before Friday?', '/questions/1'], ['Who approves the final copy?', '/questions/2']],\n },\n quarter: {\n stats: { comments: [15_880, 12_410], done: [3950, 3210], people: [44, 36], reply: [7_200_000, 7_900_000] },\n projects: [['Website', 6100], ['Mobile App', 4800], ['Docs', 3100], ['Help Center', 1880]],\n waiting: [\n ['Ben Carter asked for the new screens', '/comments/1'],\n ['Omar Reyes mentioned you in Launch plan', '/comments/2'],\n ['Review the pricing copy', '/comments/3'],\n ['Confirm the release date', '/comments/4'],\n ],\n questions: [['Is the new pricing public before Friday?', '/questions/1'], ['Who approves the final copy?', '/questions/2'], ['Which logo should the launch page use?', '/questions/3']],\n },\n} as const;\n\nconst noun: Record<Range, string> = { week: 'this week', month: 'this month', quarter: 'this quarter' };\n\nconst months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];\n// 'Nov 14' for the day `back` days before Nov 16, 2026. Written from UTC, so the server and the browser agree.\nfunction day(back: number) {\n const d = new Date(Date.UTC(2026, 10, 16 - back));\n return `${months[d.getUTCMonth()]} ${d.getUTCDate()}`;\n}\n\n// New comments per day, adding up to the tile above. The quarter is counted by week: 13 weeks, the last from Nov 10 to Nov 16.\nconst week = [152, 168, 149, 181, 190, 186, 214];\nconst month = [144, 157, 148, 162, 153, 145, 159, 150, 164, 155, 147, 160, 152, 166, 157, 149, 162, 153, 168, 159, 151, 164, 155, ...week];\nconst quarter = [1181, 1234, 1216, 1198, 1251, 1233, 1215, 1197, 1250, 1232, 1214, 1219, 1240];\nconst perDay: Record<Range, { label: string; value: number }[]> = {\n week: week.map((value, i) => ({ label: day(6 - i), value })),\n month: month.map((value, i) => ({ label: day(29 - i), value })),\n quarter: quarter.map((value, i) => ({ label: day(6 + (12 - i) * 7), value })),\n};\n\n// The summary says what changed, written from the same data the chart draws.\nfunction summary(range: Range) {\n const points = perDay[range];\n const first = points[0];\n const last = points[points.length - 1];\n const when = (p: { label: string }) => (range === 'quarter' ? `in the week of ${p.label}` : `on ${p.label}`);\n const move = last.value > first.value ? 'rose' : last.value < first.value ? 'fell' : 'stayed';\n return move === 'stayed'\n ? `Comments stayed at ${formatCount(first.value)} from ${first.label} to ${last.label}.`\n : `Comments ${move} from ${formatCount(first.value)} ${when(first)} to ${formatCount(last.value)} ${when(last)}.`;\n}\n\nexport default function DashboardNumbersFirst() {\n const [range, setRange] = useState<Range>('week');\n // The numbers load again when the range changes.\n const [loading, setLoading] = useState(false);\n // The projects section fails first, so the rest of the page shows that one section can fail alone.\n const [projectsFailed, setProjectsFailed] = useState(true);\n const [retrying, setRetrying] = useState(false);\n // The chart starts loaded. A real app sets this when the chart's request fails.\n const [trendFailed, setTrendFailed] = useState(false);\n const [trendRetrying, setTrendRetrying] = useState(false);\n const [navOpen, setNavOpen] = useState(false);\n const timer = useRef<ReturnType<typeof setTimeout>>();\n const retryTimer = useRef<ReturnType<typeof setTimeout>>();\n const trendTimer = useRef<ReturnType<typeof setTimeout>>();\n\n // Stops the requests if the example goes away before they end.\n useEffect(() => () => {\n clearTimeout(timer.current);\n clearTimeout(retryTimer.current);\n clearTimeout(trendTimer.current);\n }, []);\n\n function changeRange(next: string) {\n clearTimeout(timer.current);\n setRange(next as Range);\n setLoading(true);\n // Stands in for the request to the server.\n timer.current = setTimeout(() => setLoading(false), 600);\n }\n\n function tryAgain() {\n if (retrying) return;\n setRetrying(true);\n retryTimer.current = setTimeout(() => {\n setRetrying(false);\n setProjectsFailed(false);\n }, 1200);\n }\n\n function tryTrendAgain() {\n if (trendRetrying) return;\n setTrendRetrying(true);\n trendTimer.current = setTimeout(() => {\n setTrendRetrying(false);\n setTrendFailed(false);\n }, 1200);\n }\n\n const d = data[range];\n const period = range;\n const projectTotal = d.projects.reduce((sum, p) => sum + p[1], 0);\n const waitingCount: number = d.waiting.length;\n\n const sidebar = (\n <Navigation aria-label=\"Main\">\n <Paragraph size=\"body1\" measure=\"none\">Acme</Paragraph>\n {[\n ['Dashboard', 'LayoutDashboard', '/dashboard'],\n ['Comments', 'MessageSquare', '/comments'],\n ['Projects', 'FolderKanban', '/projects'],\n ].map(([label, icon, href]) => (\n <MenuItem\n key={href}\n size=\"small\"\n label={label}\n iconName={icon}\n href={href}\n isSelected={href === '/dashboard'}\n aria-current={href === '/dashboard' ? 'page' : undefined}\n onClick={(event: { preventDefault: () => void }) => {\n // A real app lets the link go to its page. The example stays here.\n event.preventDefault();\n }}\n />\n ))}\n </Navigation>\n );\n\n const statRow = (\n <SettingsSection key=\"stats\" title={`Numbers ${noun[range]}`} id=\"dashboard-stats\">\n <Grid compact columns={4} from=\"lg\">\n <StatTile label=\"New comments\" value={d.stats.comments[0]} previous={d.stats.comments[1]} period={period} loading={loading} />\n <StatTile label=\"Marked done\" value={d.stats.done[0]} previous={d.stats.done[1]} period={period} loading={loading} />\n <StatTile label=\"People engaged\" value={d.stats.people[0]} previous={d.stats.people[1]} period={period} loading={loading} />\n <StatTile label=\"Average reply time\" value={d.stats.reply[0]} format=\"duration\" previous={d.stats.reply[1]} period={period} loading={loading} />\n </Grid>\n </SettingsSection>\n );\n\n // A trend over the range goes under the stat row, over the same range.\n const trend = (\n <SettingsSection key=\"trend\" title={`Comments ${noun[range]}`} id=\"dashboard-trend\">\n {trendFailed ? (\n <>\n {/* Only the chart failed, as the case 'Load failure' says. The rest of the page still shows. */}\n <Alert type=\"error\" variant=\"inline\" message=\"Could not load comments.\" autoDismiss={false} />\n <Cluster>\n <Button size=\"small\" type=\"primary\" state=\"enabled\" label=\"Try Again\" loading={trendRetrying} onClickButton={tryTrendAgain} />\n </Cluster>\n </>\n ) : (\n <BarChart\n id=\"dashboard-comments-per-day\"\n title={range === 'quarter' ? 'Comments per week' : 'Comments per day'}\n summary={summary(range)}\n data={perDay[range]}\n unit=\"comments\"\n labelHeader={range === 'quarter' ? 'Week of' : 'Date'}\n loading={loading}\n emptyText={`No comments ${noun[range]}`}\n />\n )}\n </SettingsSection>\n );\n\n const projects = (\n <SettingsSection key=\"projects\" title=\"Projects\" description={`${formatCount(projectTotal)} comments ${noun[range]}, by project`} id=\"dashboard-projects\">\n {projectsFailed ? (\n <>\n {/* Only this section failed. The rest of the page still shows. */}\n <Alert type=\"error\" variant=\"inline\" message=\"Could not load projects.\" autoDismiss={false} />\n <Cluster>\n <Button size=\"small\" type=\"primary\" state=\"enabled\" label=\"Try Again\" loading={retrying} onClickButton={tryAgain} />\n </Cluster>\n </>\n ) : loading ? (\n <Skeleton variant=\"text\" lines={3} label=\"Loading projects\" />\n ) : (\n <List\n size=\"body2\"\n items={d.projects.map(([name, count]) => (\n <Progress key={name} kind=\"share\" label={name} value={count} max={projectTotal} unit=\"comments\" />\n ))}\n />\n )}\n </SettingsSection>\n );\n\n const waiting = (\n <SettingsSection key=\"waiting\" title={loading ? 'Waiting on you' : `${formatCount(waitingCount)} ${waitingCount === 1 ? 'comment' : 'comments'} waiting on you`} description={`Asked of you ${noun[range]}`} id=\"dashboard-waiting\">\n {loading ? (\n <Skeleton variant=\"text\" lines={3} label=\"Loading what waits on you\" />\n ) : (\n <Stack gap=\"small\">\n {d.waiting.map(([text, href]) => (\n <MenuItem\n key={href}\n size=\"medium\"\n label={text}\n href={href}\n onClick={(event: { preventDefault: () => void }) => {\n // A real app lets the link go to its page. The example stays here.\n event.preventDefault();\n }}\n />\n ))}\n </Stack>\n )}\n </SettingsSection>\n );\n\n const questions = (\n <SettingsSection key=\"questions\" title=\"Questions from your agents\" id=\"dashboard-questions\">\n {loading ? (\n <Skeleton variant=\"text\" lines={2} label=\"Loading questions\" />\n ) : d.questions.length === 0 ? (\n // A section with nothing keeps its place and says what will fill it.\n <EmptyBox size=\"small\" text={`No questions from your agents ${noun[range]}`} secondText=\"Questions your agents ask you appear here.\" />\n ) : (\n <Stack gap=\"small\">\n {d.questions.map(([text, href]) => (\n <MenuItem\n key={href}\n size=\"medium\"\n label={text}\n href={href}\n onClick={(event: { preventDefault: () => void }) => {\n // A real app lets the link go to its page. The example stays here.\n event.preventDefault();\n }}\n />\n ))}\n </Stack>\n )}\n </SettingsSection>\n );\n\n return (\n <AppShell title=\"Dashboard\" navOpen={navOpen} onNavOpenChange={setNavOpen} sidebar={sidebar}>\n <Stack gap=\"xlarge\">\n {/* One range drives every number below, and each heading says which one. */}\n {/* Below md the range switch takes its own line under the title. */}\n <TitleBar\n title=\"Dashboard\"\n actionsBelow\n actions={<SegmentedControl size=\"small\" width=\"fit\" aria-label=\"Range\" options={ranges} value={range} onChange={changeRange} />}\n />\n {statRow}\n {trend}\n {projects}\n {waiting}\n {questions}\n </Stack>\n </AppShell>\n );\n}\n",
|
|
2170
2264
|
"uses": [
|
|
2171
2265
|
"Alert",
|
|
2172
2266
|
"AppShell",
|
|
@@ -2193,7 +2287,7 @@
|
|
|
2193
2287
|
"id": "work-first",
|
|
2194
2288
|
"title": "Work first",
|
|
2195
2289
|
"useWhen": "The person starts their day here, so what waits on them comes before the numbers.",
|
|
2196
|
-
"source": "'use client';\nimport { useEffect, useRef, useState } from 'react';\nimport AppShell from 'oneslash-design-system/components/appShell';\nimport TitleBar from 'oneslash-design-system/components/titleBar';\nimport SegmentedControl from 'oneslash-design-system/components/segmentedControl';\nimport SettingsSection from 'oneslash-design-system/components/settingsSection';\nimport Navigation from 'oneslash-design-system/components/navigation';\nimport MenuItem from 'oneslash-design-system/components/menuItem';\nimport StatTile from 'oneslash-design-system/components/statTile';\nimport Progress from 'oneslash-design-system/components/progress';\nimport Skeleton from 'oneslash-design-system/components/skeleton';\nimport Alert from 'oneslash-design-system/components/alert';\nimport Button from 'oneslash-design-system/components/button';\nimport Paragraph from 'oneslash-design-system/components/paragraph';\nimport EmptyBox from 'oneslash-design-system/components/emptyBox';\nimport List from 'oneslash-design-system/components/list';\nimport { formatCount } from 'oneslash-design-system/components/formatNumber';\nimport { Cluster, Grid, Stack } from 'oneslash-design-system/components/layout';\n\ntype Range = 'week' | 'month' | 'quarter';\nconst ranges = [\n { value: 'week', label: 'Week' },\n { value: 'month', label: 'Month' },\n { value: 'quarter', label: 'Quarter' },\n];\n\n// A real app counts these on the server. One range drives every number on the page.\nconst data = {\n week: {\n stats: { comments: [1240, 1106], done: [312, 280], people: [18, 18], reply: [8_640_000, 9_200_000] },\n projects: [['Website', 540], ['Mobile App', 380], ['Docs', 320]],\n waiting: [\n ['Ben Carter asked for the new screens', '/comments/1'],\n ['Omar Reyes mentioned you in Launch plan', '/comments/2'],\n ['Review the pricing copy', '/comments/3'],\n ],\n questions: [],\n },\n month: {\n stats: { comments: [4820, 5210], done: [1190, 1004], people: [31, 27], reply: [7_800_000, 8_100_000] },\n projects: [['Website', 2010], ['Mobile App', 1500], ['Docs', 910], ['Help Center', 400]],\n waiting: [\n ['Ben Carter asked for the new screens', '/comments/1'],\n ['Omar Reyes mentioned you in Launch plan', '/comments/2'],\n ['Review the pricing copy', '/comments/3'],\n ['Confirm the release date', '/comments/4'],\n ['Approve the new onboarding text', '/comments/5'],\n ],\n questions: [['Is the new pricing public before Friday?', '/questions/1'], ['Who approves the final copy?', '/questions/2']],\n },\n quarter: {\n stats: { comments: [15_880, 12_410], done: [3950, 3210], people: [44, 36], reply: [7_200_000, 7_900_000] },\n projects: [['Website', 6100], ['Mobile App', 4800], ['Docs', 3100], ['Help Center', 1880]],\n waiting: [\n ['Ben Carter asked for the new screens', '/comments/1'],\n ['Omar Reyes mentioned you in Launch plan', '/comments/2'],\n ['Review the pricing copy', '/comments/3'],\n ['Confirm the release date', '/comments/4'],\n ],\n questions: [['Is the new pricing public before Friday?', '/questions/1'], ['Who approves the final copy?', '/questions/2'], ['Which logo should the launch page use?', '/questions/3']],\n },\n} as const;\n\nconst noun: Record<Range, string> = { week: 'this week', month: 'this month', quarter: 'this quarter' };\n\nexport default function DashboardWorkFirst() {\n const [range, setRange] = useState<Range>('week');\n // The numbers load again when the range changes.\n const [loading, setLoading] = useState(false);\n // The projects section fails first, so the rest of the page shows that one section can fail alone.\n const [projectsFailed, setProjectsFailed] = useState(true);\n const [retrying, setRetrying] = useState(false);\n const [navOpen, setNavOpen] = useState(false);\n const timer = useRef<ReturnType<typeof setTimeout>>();\n const retryTimer = useRef<ReturnType<typeof setTimeout>>();\n\n // Stops the requests if the example goes away before they end.\n useEffect(() => () => {\n clearTimeout(timer.current);\n clearTimeout(retryTimer.current);\n }, []);\n\n function changeRange(next: string) {\n clearTimeout(timer.current);\n setRange(next as Range);\n setLoading(true);\n // Stands in for the request to the server.\n timer.current = setTimeout(() => setLoading(false), 600);\n }\n\n function tryAgain() {\n if (retrying) return;\n setRetrying(true);\n retryTimer.current = setTimeout(() => {\n setRetrying(false);\n setProjectsFailed(false);\n }, 1200);\n }\n\n const d = data[range];\n const period = range;\n const projectTotal = d.projects.reduce((sum, p) => sum + p[1], 0);\n const waitingCount: number = d.waiting.length;\n\n const sidebar = (\n <Navigation aria-label=\"Main\">\n <Paragraph size=\"body1\" measure=\"none\">Acme</Paragraph>\n {[\n ['Dashboard', 'LayoutDashboard', '/dashboard'],\n ['Comments', 'MessageSquare', '/comments'],\n ['Projects', 'FolderKanban', '/projects'],\n ].map(([label, icon, href]) => (\n <MenuItem\n key={href}\n size=\"small\"\n label={label}\n iconName={icon}\n href={href}\n isSelected={href === '/dashboard'}\n aria-current={href === '/dashboard' ? 'page' : undefined}\n onClick={(event: { preventDefault: () => void }) => {\n // A real app lets the link go to its page. The example stays here.\n event.preventDefault();\n }}\n />\n ))}\n </Navigation>\n );\n\n const statRow = (\n <SettingsSection key=\"stats\" title={`Numbers ${noun[range]}`} id=\"dashboard-stats\">\n <Grid compact columns={4}>\n <StatTile label=\"New comments\" value={d.stats.comments[0]} previous={d.stats.comments[1]} period={period} loading={loading} />\n <StatTile label=\"Marked done\" value={d.stats.done[0]} previous={d.stats.done[1]} period={period} loading={loading} />\n <StatTile label=\"People engaged\" value={d.stats.people[0]} previous={d.stats.people[1]} period={period} loading={loading} />\n <StatTile label=\"Average reply time\" value={d.stats.reply[0]} format=\"duration\" previous={d.stats.reply[1]} period={period} loading={loading} />\n </Grid>\n </SettingsSection>\n );\n\n const projects = (\n <SettingsSection key=\"projects\" title=\"Projects\" description={`${formatCount(projectTotal)} comments ${noun[range]}, by project`} id=\"dashboard-projects\">\n {projectsFailed ? (\n <>\n {/* Only this section failed. The rest of the page still shows. */}\n <Alert type=\"error\" variant=\"inline\" message=\"Could not load projects.\" autoDismiss={false} />\n <Cluster>\n <Button size=\"small\" type=\"primary\" state=\"enabled\" label=\"Try Again\" loading={retrying} onClickButton={tryAgain} />\n </Cluster>\n </>\n ) : loading ? (\n <Skeleton variant=\"text\" lines={3} label=\"Loading projects\" />\n ) : (\n <List\n size=\"body2\"\n items={d.projects.map(([name, count]) => (\n <Progress key={name} kind=\"share\" label={name} value={count} max={projectTotal} unit=\"comments\" />\n ))}\n />\n )}\n </SettingsSection>\n );\n\n const waiting = (\n <SettingsSection key=\"waiting\" title={loading ? 'Waiting on you' : `${formatCount(waitingCount)} ${waitingCount === 1 ? 'comment' : 'comments'} waiting on you`} description={`Asked of you ${noun[range]}`} id=\"dashboard-waiting\">\n {loading ? (\n <Skeleton variant=\"text\" lines={3} label=\"Loading what waits on you\" />\n ) : (\n <Stack gap=\"small\">\n {d.waiting.map(([text, href]) => (\n <MenuItem\n key={href}\n size=\"medium\"\n label={text}\n href={href}\n onClick={(event: { preventDefault: () => void }) => {\n // A real app lets the link go to its page. The example stays here.\n event.preventDefault();\n }}\n />\n ))}\n </Stack>\n )}\n </SettingsSection>\n );\n\n const questions = (\n <SettingsSection key=\"questions\" title=\"Questions from your agents\" id=\"dashboard-questions\">\n {loading ? (\n <Skeleton variant=\"text\" lines={2} label=\"Loading questions\" />\n ) : d.questions.length === 0 ? (\n // A section with nothing keeps its place and says what will fill it.\n <EmptyBox size=\"small\" text={`No questions from your agents ${noun[range]}`} secondText=\"Questions your agents ask you appear here.\" />\n ) : (\n <Stack gap=\"small\">\n {d.questions.map(([text, href]) => (\n <MenuItem\n key={href}\n size=\"medium\"\n label={text}\n href={href}\n onClick={(event: { preventDefault: () => void }) => {\n // A real app lets the link go to its page. The example stays here.\n event.preventDefault();\n }}\n />\n ))}\n </Stack>\n )}\n </SettingsSection>\n );\n\n return (\n <AppShell title=\"Dashboard\" navOpen={navOpen} onNavOpenChange={setNavOpen} sidebar={sidebar}>\n <Stack gap=\"xlarge\">\n {/* One range drives every number below, and each heading says which one. */}\n {/* Below md the range switch takes its own line under the title. */}\n <TitleBar\n title=\"Dashboard\"\n actionsBelow\n actions={<SegmentedControl size=\"small\" width=\"fit\" aria-label=\"Range\" options={ranges} value={range} onChange={changeRange} />}\n />\n {waiting}\n {questions}\n {statRow}\n {projects}\n </Stack>\n </AppShell>\n );\n}\n",
|
|
2290
|
+
"source": "'use client';\nimport { useEffect, useRef, useState } from 'react';\nimport AppShell from 'oneslash-design-system/components/appShell';\nimport TitleBar from 'oneslash-design-system/components/titleBar';\nimport SegmentedControl from 'oneslash-design-system/components/segmentedControl';\nimport SettingsSection from 'oneslash-design-system/components/settingsSection';\nimport Navigation from 'oneslash-design-system/components/navigation';\nimport MenuItem from 'oneslash-design-system/components/menuItem';\nimport StatTile from 'oneslash-design-system/components/statTile';\nimport Progress from 'oneslash-design-system/components/progress';\nimport Skeleton from 'oneslash-design-system/components/skeleton';\nimport Alert from 'oneslash-design-system/components/alert';\nimport Button from 'oneslash-design-system/components/button';\nimport Paragraph from 'oneslash-design-system/components/paragraph';\nimport EmptyBox from 'oneslash-design-system/components/emptyBox';\nimport List from 'oneslash-design-system/components/list';\nimport { formatCount } from 'oneslash-design-system/components/formatNumber';\nimport { Cluster, Grid, Stack } from 'oneslash-design-system/components/layout';\n\ntype Range = 'week' | 'month' | 'quarter';\nconst ranges = [\n { value: 'week', label: 'Week' },\n { value: 'month', label: 'Month' },\n { value: 'quarter', label: 'Quarter' },\n];\n\n// A real app counts these on the server. One range drives every number on the page.\nconst data = {\n week: {\n stats: { comments: [1240, 1106], done: [312, 280], people: [18, 18], reply: [8_640_000, 9_200_000] },\n projects: [['Website', 540], ['Mobile App', 380], ['Docs', 320]],\n waiting: [\n ['Ben Carter asked for the new screens', '/comments/1'],\n ['Omar Reyes mentioned you in Launch plan', '/comments/2'],\n ['Review the pricing copy', '/comments/3'],\n ],\n questions: [],\n },\n month: {\n stats: { comments: [4820, 5210], done: [1190, 1004], people: [31, 27], reply: [7_800_000, 8_100_000] },\n projects: [['Website', 2010], ['Mobile App', 1500], ['Docs', 910], ['Help Center', 400]],\n waiting: [\n ['Ben Carter asked for the new screens', '/comments/1'],\n ['Omar Reyes mentioned you in Launch plan', '/comments/2'],\n ['Review the pricing copy', '/comments/3'],\n ['Confirm the release date', '/comments/4'],\n ['Approve the new onboarding text', '/comments/5'],\n ],\n questions: [['Is the new pricing public before Friday?', '/questions/1'], ['Who approves the final copy?', '/questions/2']],\n },\n quarter: {\n stats: { comments: [15_880, 12_410], done: [3950, 3210], people: [44, 36], reply: [7_200_000, 7_900_000] },\n projects: [['Website', 6100], ['Mobile App', 4800], ['Docs', 3100], ['Help Center', 1880]],\n waiting: [\n ['Ben Carter asked for the new screens', '/comments/1'],\n ['Omar Reyes mentioned you in Launch plan', '/comments/2'],\n ['Review the pricing copy', '/comments/3'],\n ['Confirm the release date', '/comments/4'],\n ],\n questions: [['Is the new pricing public before Friday?', '/questions/1'], ['Who approves the final copy?', '/questions/2'], ['Which logo should the launch page use?', '/questions/3']],\n },\n} as const;\n\nconst noun: Record<Range, string> = { week: 'this week', month: 'this month', quarter: 'this quarter' };\n\nexport default function DashboardWorkFirst() {\n const [range, setRange] = useState<Range>('week');\n // The numbers load again when the range changes.\n const [loading, setLoading] = useState(false);\n // The projects section fails first, so the rest of the page shows that one section can fail alone.\n const [projectsFailed, setProjectsFailed] = useState(true);\n const [retrying, setRetrying] = useState(false);\n const [navOpen, setNavOpen] = useState(false);\n const timer = useRef<ReturnType<typeof setTimeout>>();\n const retryTimer = useRef<ReturnType<typeof setTimeout>>();\n\n // Stops the requests if the example goes away before they end.\n useEffect(() => () => {\n clearTimeout(timer.current);\n clearTimeout(retryTimer.current);\n }, []);\n\n function changeRange(next: string) {\n clearTimeout(timer.current);\n setRange(next as Range);\n setLoading(true);\n // Stands in for the request to the server.\n timer.current = setTimeout(() => setLoading(false), 600);\n }\n\n function tryAgain() {\n if (retrying) return;\n setRetrying(true);\n retryTimer.current = setTimeout(() => {\n setRetrying(false);\n setProjectsFailed(false);\n }, 1200);\n }\n\n const d = data[range];\n const period = range;\n const projectTotal = d.projects.reduce((sum, p) => sum + p[1], 0);\n const waitingCount: number = d.waiting.length;\n\n const sidebar = (\n <Navigation aria-label=\"Main\">\n <Paragraph size=\"body1\" measure=\"none\">Acme</Paragraph>\n {[\n ['Dashboard', 'LayoutDashboard', '/dashboard'],\n ['Comments', 'MessageSquare', '/comments'],\n ['Projects', 'FolderKanban', '/projects'],\n ].map(([label, icon, href]) => (\n <MenuItem\n key={href}\n size=\"small\"\n label={label}\n iconName={icon}\n href={href}\n isSelected={href === '/dashboard'}\n aria-current={href === '/dashboard' ? 'page' : undefined}\n onClick={(event: { preventDefault: () => void }) => {\n // A real app lets the link go to its page. The example stays here.\n event.preventDefault();\n }}\n />\n ))}\n </Navigation>\n );\n\n const statRow = (\n <SettingsSection key=\"stats\" title={`Numbers ${noun[range]}`} id=\"dashboard-stats\">\n <Grid compact columns={4} from=\"lg\">\n <StatTile label=\"New comments\" value={d.stats.comments[0]} previous={d.stats.comments[1]} period={period} loading={loading} />\n <StatTile label=\"Marked done\" value={d.stats.done[0]} previous={d.stats.done[1]} period={period} loading={loading} />\n <StatTile label=\"People engaged\" value={d.stats.people[0]} previous={d.stats.people[1]} period={period} loading={loading} />\n <StatTile label=\"Average reply time\" value={d.stats.reply[0]} format=\"duration\" previous={d.stats.reply[1]} period={period} loading={loading} />\n </Grid>\n </SettingsSection>\n );\n\n const projects = (\n <SettingsSection key=\"projects\" title=\"Projects\" description={`${formatCount(projectTotal)} comments ${noun[range]}, by project`} id=\"dashboard-projects\">\n {projectsFailed ? (\n <>\n {/* Only this section failed. The rest of the page still shows. */}\n <Alert type=\"error\" variant=\"inline\" message=\"Could not load projects.\" autoDismiss={false} />\n <Cluster>\n <Button size=\"small\" type=\"primary\" state=\"enabled\" label=\"Try Again\" loading={retrying} onClickButton={tryAgain} />\n </Cluster>\n </>\n ) : loading ? (\n <Skeleton variant=\"text\" lines={3} label=\"Loading projects\" />\n ) : (\n <List\n size=\"body2\"\n items={d.projects.map(([name, count]) => (\n <Progress key={name} kind=\"share\" label={name} value={count} max={projectTotal} unit=\"comments\" />\n ))}\n />\n )}\n </SettingsSection>\n );\n\n const waiting = (\n <SettingsSection key=\"waiting\" title={loading ? 'Waiting on you' : `${formatCount(waitingCount)} ${waitingCount === 1 ? 'comment' : 'comments'} waiting on you`} description={`Asked of you ${noun[range]}`} id=\"dashboard-waiting\">\n {loading ? (\n <Skeleton variant=\"text\" lines={3} label=\"Loading what waits on you\" />\n ) : (\n <Stack gap=\"small\">\n {d.waiting.map(([text, href]) => (\n <MenuItem\n key={href}\n size=\"medium\"\n label={text}\n href={href}\n onClick={(event: { preventDefault: () => void }) => {\n // A real app lets the link go to its page. The example stays here.\n event.preventDefault();\n }}\n />\n ))}\n </Stack>\n )}\n </SettingsSection>\n );\n\n const questions = (\n <SettingsSection key=\"questions\" title=\"Questions from your agents\" id=\"dashboard-questions\">\n {loading ? (\n <Skeleton variant=\"text\" lines={2} label=\"Loading questions\" />\n ) : d.questions.length === 0 ? (\n // A section with nothing keeps its place and says what will fill it.\n <EmptyBox size=\"small\" text={`No questions from your agents ${noun[range]}`} secondText=\"Questions your agents ask you appear here.\" />\n ) : (\n <Stack gap=\"small\">\n {d.questions.map(([text, href]) => (\n <MenuItem\n key={href}\n size=\"medium\"\n label={text}\n href={href}\n onClick={(event: { preventDefault: () => void }) => {\n // A real app lets the link go to its page. The example stays here.\n event.preventDefault();\n }}\n />\n ))}\n </Stack>\n )}\n </SettingsSection>\n );\n\n return (\n <AppShell title=\"Dashboard\" navOpen={navOpen} onNavOpenChange={setNavOpen} sidebar={sidebar}>\n <Stack gap=\"xlarge\">\n {/* One range drives every number below, and each heading says which one. */}\n {/* Below md the range switch takes its own line under the title. */}\n <TitleBar\n title=\"Dashboard\"\n actionsBelow\n actions={<SegmentedControl size=\"small\" width=\"fit\" aria-label=\"Range\" options={ranges} value={range} onChange={changeRange} />}\n />\n {waiting}\n {questions}\n {statRow}\n {projects}\n </Stack>\n </AppShell>\n );\n}\n",
|
|
2197
2291
|
"uses": [
|
|
2198
2292
|
"Alert",
|
|
2199
2293
|
"AppShell",
|
|
@@ -2261,7 +2355,7 @@
|
|
|
2261
2355
|
"id": "paged",
|
|
2262
2356
|
"title": "Pages from the server",
|
|
2263
2357
|
"useWhen": "There are more rows than fit on a page, they come from the server, and the page holds 25 of them.",
|
|
2264
|
-
"source": "'use client';\nimport { useEffect, useRef, useState } from 'react';\nimport Toaster, { toast, dismissToast } from 'oneslash-design-system/components/toaster';\nimport TitleBar from 'oneslash-design-system/components/titleBar';\nimport Paragraph from 'oneslash-design-system/components/paragraph';\nimport Skeleton from 'oneslash-design-system/components/skeleton';\nimport Surface from 'oneslash-design-system/components/surface';\nimport EmptyBox from 'oneslash-design-system/components/emptyBox';\nimport Button from 'oneslash-design-system/components/button';\nimport IconButton from 'oneslash-design-system/components/iconButton';\nimport Tooltip from 'oneslash-design-system/components/tooltip';\nimport TextField from 'oneslash-design-system/components/textField';\nimport Popover from 'oneslash-design-system/components/popover';\nimport Menu from 'oneslash-design-system/components/menu';\nimport MenuItem from 'oneslash-design-system/components/menuItem';\nimport Line from 'oneslash-design-system/components/line';\nimport Tag from 'oneslash-design-system/components/tag';\nimport Pagination from 'oneslash-design-system/components/pagination';\nimport TableContainer from 'oneslash-design-system/components/tableContainer';\nimport TableHeader from 'oneslash-design-system/components/tableHeader';\nimport TableHeaderCell from 'oneslash-design-system/components/tableHeaderCell';\nimport TableRow from 'oneslash-design-system/components/tableRow';\nimport TableCell from 'oneslash-design-system/components/tableCell';\nimport { formatCount, formatMoney } from 'oneslash-design-system/components/formatNumber';\nimport { Center, Cluster, Stack } from 'oneslash-design-system/components/layout';\n\ntype Status = 'Paid' | 'Past due' | 'Refunded';\ntype Invoice = { id: string; number: string; customer: string; day: number; date: string; cents: number; status: Status };\ntype SortBy = 'customer' | 'date' | 'amount';\ntype Focusable = HTMLButtonElement | HTMLAnchorElement | null;\n\nconst customers = ['Northwind', 'Harbor Studio', 'Lumen Labs', 'Pine and Co', 'Cedar Works', 'Bright Dental', 'Maple Design', 'Atlas Freight', 'Juniper Foods', 'Orchard Legal'];\nconst monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];\n\n// A real app asks the server for one page. This makes the 290 invoices the server would hold, newest first.\nconst all: Invoice[] = Array.from({ length: 290 }, (_, i) => {\n const day = new Date(Date.UTC(2026, 10, 28 - i));\n return {\n id: `inv-${i}`,\n number: `INV-${1290 - i}`,\n customer: customers[(i * 7 + 3) % customers.length],\n day: i,\n date: `${monthNames[day.getUTCMonth()]} ${day.getUTCDate()}, ${day.getUTCFullYear()}`,\n cents: 2400 + ((i * 5303) % 40000),\n status: i % 11 === 4 ? 'Past due' : i % 9 === 5 ? 'Refunded' : 'Paid',\n };\n});\n\nconst statuses: Status[] = ['Paid', 'Past due', 'Refunded'];\nconst PAGE_SIZE = 25;\n\nexport default function DataTablePagePaged() {\n const [query, setQuery] = useState('');\n const [status, setStatus] = useState<Status | null>(null);\n // Opens newest first.\n const [sort, setSort] = useState<{ by: SortBy; dir: 'ascending' | 'descending' }>({ by: 'date', dir: 'descending' });\n const [page, setPage] = useState(1);\n const [loading, setLoading] = useState(false);\n const [failed, setFailed] = useState(false);\n\n const [searchAnchor, setSearchAnchor] = useState<HTMLElement | null>(null);\n const [searchOpen, setSearchOpen] = useState(false);\n const [filterAnchor, setFilterAnchor] = useState<HTMLElement | null>(null);\n const [filterOpen, setFilterOpen] = useState(false);\n const [menuRow, setMenuRow] = useState<Invoice | null>(null);\n const [menuAnchor, setMenuAnchor] = useState<HTMLElement | null>(null);\n const [menuOpen, setMenuOpen] = useState(false);\n\n const timer = useRef<ReturnType<typeof setTimeout>>();\n const failedOnce = useRef(false);\n const mounted = useRef(true);\n const toastIds = useRef<string[]>([]);\n const searchButton = useRef<Focusable>(null);\n\n // On unmount it stops the request and closes every toast it opened.\n useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n clearTimeout(timer.current);\n toastIds.current.forEach((id) => dismissToast(id));\n toastIds.current = [];\n };\n }, []);\n\n // The server sorts and filters, so the page asks it again for every change. The header and the pager stay while it answers.\n function request(forPage: number) {\n clearTimeout(timer.current);\n setLoading(true);\n timer.current = setTimeout(() => {\n setLoading(false);\n // The failure stays on screen, with its Button, until the new answer arrives.\n setFailed(false);\n // Stands in for a network failure, once: page 3 fails the first time it is asked for.\n if (forPage === 3 && !failedOnce.current) {\n failedOnce.current = true;\n setFailed(true);\n }\n }, 600);\n }\n\n // A sort, a search or a filter goes back to page 1: page 4 of the old list means nothing in the new one.\n // A real app waits a moment after the last key before it asks the server for a search.\n function change(next: { query?: string; status?: Status | null; sort?: { by: SortBy; dir: 'ascending' | 'descending' } }) {\n if (next.query !== undefined) setQuery(next.query);\n if (next.status !== undefined) setStatus(next.status);\n if (next.sort !== undefined) setSort(next.sort);\n setPage(1);\n request(1);\n }\n\n function goToPage(next: number) {\n setPage(next);\n request(next);\n }\n\n // The first press on a column sorts it A to Z, and the next one reverses it.\n function handleSort(by: SortBy) {\n change({ sort: { by, dir: sort.by === by && sort.dir === 'ascending' ? 'descending' : 'ascending' } });\n }\n\n const words = query.trim();\n const found = all\n .filter((inv) => (status === null || inv.status === status) && (words === '' || `${inv.number} ${inv.customer}`.toLowerCase().includes(words.toLowerCase())))\n .sort((a, b) => {\n const order = sort.by === 'customer' ? a.customer.localeCompare(b.customer) : sort.by === 'amount' ? a.cents - b.cents : b.day - a.day;\n return (sort.dir === 'ascending' ? order : -order) || a.day - b.day;\n });\n const pageCount = Math.ceil(found.length / PAGE_SIZE);\n const rows = found.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);\n const filtering = words !== '' || status !== null;\n\n // The line under the title says the total, and what the search and the filter leave.\n const matching = [words !== '' ? `\"${words}\"` : null, status !== null ? status.toLowerCase() : null].filter(Boolean).join(', ');\n const countLine = filtering ? `${formatCount(found.length)} of ${formatCount(all.length)} invoices match ${matching}.` : `${formatCount(all.length)} ${all.length === 1 ? 'invoice' : 'invoices'}`;\n\n // The Button clears the words and the filter. Focus goes to the search button, because the field is in the closed Popover.\n function clearFilter() {\n change({ query: '', status: null });\n searchButton.current?.focus();\n }\n\n function openMenu(inv: Invoice, anchor: HTMLElement) {\n if (menuOpen && menuRow?.id === inv.id) {\n setMenuOpen(false);\n return;\n }\n setMenuRow(inv);\n setMenuAnchor(anchor);\n setMenuOpen(true);\n }\n\n function choose(action: (inv: Invoice) => void) {\n if (!menuRow) return;\n const inv = menuRow;\n setMenuOpen(false);\n action(inv);\n }\n\n function sendReceipt(inv: Invoice) {\n toastIds.current.push(toast({ type: 'success', message: `Receipt for ${inv.number} sent to ${inv.customer}.` }));\n }\n\n // Only reads 'copied' when the number reached the clipboard.\n function copyNumber(inv: Invoice) {\n const failedCopy = () => {\n if (!mounted.current) return;\n toastIds.current.push(toast({ type: 'error', message: `Copying is blocked here. Select the number and copy it: ${inv.number}` }));\n };\n if (!navigator.clipboard) return failedCopy();\n navigator.clipboard.writeText(inv.number).then(() => {\n if (!mounted.current) return;\n toastIds.current.push(toast({ type: 'success', message: 'Invoice number copied.' }));\n }, failedCopy);\n }\n\n // The sorted column has `sort`; the others leave it unset, so exactly one header carries `aria-sort`.\n function sortHeader(by: SortBy, label: string, width?: string, align?: 'right') {\n const active = sort.by === by;\n const button = (\n <Button\n size=\"small\"\n type=\"tertiary\"\n state={active ? 'selected' : 'enabled'}\n label={label}\n decoIcon={active ? (sort.dir === 'ascending' ? 'ArrowUp' : 'ArrowDown') : undefined}\n onClickButton={() => handleSort(by)}\n />\n );\n return (\n <TableHeaderCell width={width} align={align} sort={active ? sort.dir : undefined}>\n {align === 'right' ? <Cluster justify=\"end\">{button}</Cluster> : button}\n </TableHeaderCell>\n );\n }\n\n function statusTag(s: Status) {\n // The case 'Status in a row': a dot and a color only for a state that needs action.\n return s === 'Past due' ? <Tag variant=\"dot\" size=\"small\" color=\"error\" label={s} /> : <Tag variant=\"textOnly\" size=\"small\" label={s} />;\n }\n\n return (\n <Center width=\"page\">\n {/* A real app mounts one Toaster near its root. */}\n <Toaster />\n <Stack gap=\"large\">\n <Stack gap=\"small\">\n <TitleBar title=\"Invoices\" id=\"data-table-page-paged-top\" />\n {loading ? <Skeleton variant=\"text\" width=\"medium\" /> : <Paragraph tone=\"secondary\" size=\"body2\" measure=\"none\">{countLine}</Paragraph>}\n </Stack>\n\n {/* Search and the filter sit above the table, as the cases 'Collapsible search' and 'Filter menu' say. */}\n <Cluster gap=\"small\" justify=\"end\">\n <Tooltip title={words !== '' ? `Search: ${words}` : 'Search'}>\n <IconButton\n ref={searchButton}\n color={words !== '' ? 'secondary' : 'iconOnly'}\n state={searchOpen ? 'selected' : 'enabled'}\n size=\"small\"\n iconName=\"Search\"\n ariaLabel={words !== '' ? `Search: ${words}` : 'Search'}\n aria-haspopup=\"dialog\"\n aria-expanded={searchOpen}\n onClick={(e: { currentTarget: HTMLElement }) => {\n setSearchAnchor(e.currentTarget);\n setSearchOpen((o) => !o);\n }}\n />\n </Tooltip>\n <Tooltip title={status ? status : 'Filter by status'}>\n <IconButton\n color={status ? 'secondary' : 'iconOnly'}\n state={filterOpen ? 'selected' : 'enabled'}\n size=\"small\"\n iconName=\"ListFilter\"\n ariaLabel={status ? `Filter by status: ${status}` : 'Filter by status'}\n aria-haspopup=\"menu\"\n aria-expanded={filterOpen}\n onClick={(e: { currentTarget: HTMLElement }) => {\n setFilterAnchor(e.currentTarget);\n setFilterOpen((o) => !o);\n }}\n />\n </Tooltip>\n </Cluster>\n\n {all.length === 0 ? (\n // A new workspace has none. The case 'Empty list' says what to write.\n <Surface minHeight=\"tall\" align=\"center\">\n <EmptyBox size=\"large\" text=\"No invoices yet\" secondText=\"Your first invoice appears here after your first payment.\" />\n </Surface>\n ) : failed ? (\n // The table's place: the header goes too, because nothing is left to sort. The pager stays.\n <Surface minHeight=\"tall\" align=\"center\">\n <EmptyBox\n size=\"large\"\n icon=\"CloudOff\"\n text=\"Could not load invoices\"\n secondText=\"Check your connection and try again.\"\n action={<Button size=\"medium\" type=\"primary\" state=\"enabled\" label=\"Try Again\" loading={loading} onClickButton={() => request(page)} />}\n />\n </Surface>\n ) : !loading && found.length === 0 ? (\n <Surface minHeight=\"tall\" align=\"center\">\n <EmptyBox\n size=\"large\"\n icon=\"Search\"\n text={words !== '' ? `No ${status ? `${status.toLowerCase()} ` : ''}invoices match \"${words}\"` : `No ${status?.toLowerCase()} invoices`}\n secondText={words !== '' ? 'Check the spelling, or search for fewer words.' : 'Choose another status, or clear the filter.'}\n action={<Button size=\"medium\" type=\"secondary\" state=\"enabled\" label={status !== null ? 'Clear Filter' : 'Clear Search'} onClickButton={clearFilter} />}\n />\n </Surface>\n ) : (\n <TableContainer aria-label=\"Invoices\" minWidth=\"640px\">\n <TableHeader>\n <TableRow>\n <TableHeaderCell width=\"110px\">Invoice</TableHeaderCell>\n {sortHeader('customer', 'Customer')}\n {sortHeader('date', 'Date', '140px')}\n {sortHeader('amount', 'Amount', '130px', 'right')}\n <TableHeaderCell width=\"120px\">Status</TableHeaderCell>\n <TableHeaderCell width=\"90px\">Actions</TableHeaderCell>\n </TableRow>\n </TableHeader>\n {loading\n ? Array.from({ length: 10 }, (_, i) => (\n <TableRow key={i}>\n {/* One status for the ten rows: the Skeleton with a label is announced once. */}\n <TableCell width=\"110px\">{i === 0 ? <Skeleton label=\"Loading invoices\" /> : <Skeleton />}</TableCell>\n <TableCell><Skeleton width=\"large\" /></TableCell>\n <TableCell width=\"140px\"><Skeleton /></TableCell>\n <TableCell width=\"130px\"><Skeleton /></TableCell>\n <TableCell width=\"120px\"><Skeleton width=\"large\" /></TableCell>\n <TableCell width=\"90px\"><Skeleton width=\"small\" /></TableCell>\n </TableRow>\n ))\n : rows.map((inv) => (\n <TableRow key={inv.id}>\n <TableCell width=\"110px\">{inv.number}</TableCell>\n <TableCell>{inv.customer}</TableCell>\n <TableCell width=\"140px\">{inv.date}</TableCell>\n {/* A table shows the exact amount, right-aligned. */}\n <TableCell width=\"130px\" align=\"right\">{formatMoney(inv.cents / 100)}</TableCell>\n <TableCell width=\"120px\">{statusTag(inv.status)}</TableCell>\n <TableCell width=\"90px\">\n <Tooltip title=\"More\">\n <IconButton\n color=\"iconOnly\"\n state={menuOpen && menuRow?.id === inv.id ? 'selected' : 'enabled'}\n size=\"small\"\n iconName=\"Ellipsis\"\n ariaLabel={`More actions for ${inv.number}`}\n aria-haspopup=\"menu\"\n aria-expanded={menuOpen && menuRow?.id === inv.id}\n onClick={(e: { currentTarget: HTMLElement }) => openMenu(inv, e.currentTarget)}\n />\n </Tooltip>\n </TableCell>\n </TableRow>\n ))}\n </TableContainer>\n )}\n\n {/* It shows nothing with one page. A real app also passes `getHref`, so each page has an address. */}\n <Pagination aria-label=\"Invoice pages\" page={page} pageCount={pageCount} onPageChange={goToPage} scrollTargetId=\"data-table-page-paged-top\" />\n </Stack>\n\n <Popover open={searchOpen} anchorEl={searchAnchor} onClose={() => setSearchOpen(false)} returnFocus>\n <Menu width={288}>\n <TextField\n id=\"data-table-page-paged-search\"\n type=\"search\"\n size=\"small\"\n autoFocus\n aria-label=\"Search invoices\"\n placeholder=\"Search invoices\"\n value={query}\n onChange={(e) => change({ query: e.target.value })}\n onKeyDown={(e) => {\n // Escape clears the search and closes. Enter closes and keeps it.\n if (e.key === 'Escape') {\n e.preventDefault();\n change({ query: '' });\n setSearchOpen(false);\n } else if (e.key === 'Enter') {\n e.preventDefault();\n setSearchOpen(false);\n }\n }}\n />\n </Menu>\n </Popover>\n <Popover open={filterOpen} anchorEl={filterAnchor} onClose={() => setFilterOpen(false)} returnFocus>\n <Menu navigable aria-label=\"Filter by status\" width={200}>\n {statuses.map((s) => (\n <MenuItem\n key={s}\n size=\"small\"\n label={s === 'Past due' ? 'Past Due' : s}\n isSelected={s === status}\n role=\"menuitemradio\"\n onClick={() => {\n setFilterOpen(false);\n change({ status: s });\n }}\n />\n ))}\n {status && <Line />}\n {status && (\n <MenuItem\n size=\"small\"\n iconName=\"X\"\n label=\"Clear Filter\"\n onClick={() => {\n setFilterOpen(false);\n change({ status: null });\n }}\n />\n )}\n </Menu>\n </Popover>\n <Popover open={menuOpen} anchorEl={menuAnchor} onClose={() => setMenuOpen(false)} returnFocus>\n <Menu navigable aria-label={menuRow ? `Actions for ${menuRow.number}` : 'Invoice actions'} width={220}>\n <MenuItem size=\"small\" iconName=\"Copy\" label=\"Copy Invoice Number\" onClick={() => choose(copyNumber)} />\n <MenuItem size=\"small\" iconName=\"Mail\" label=\"Send Receipt\" onClick={() => choose(sendReceipt)} />\n </Menu>\n </Popover>\n </Center>\n );\n}\n",
|
|
2358
|
+
"source": "'use client';\nimport { useEffect, useRef, useState } from 'react';\nimport Toaster, { toast, dismissToast } from 'oneslash-design-system/components/toaster';\nimport TitleBar from 'oneslash-design-system/components/titleBar';\nimport Paragraph from 'oneslash-design-system/components/paragraph';\nimport Skeleton from 'oneslash-design-system/components/skeleton';\nimport Surface from 'oneslash-design-system/components/surface';\nimport EmptyBox from 'oneslash-design-system/components/emptyBox';\nimport Button from 'oneslash-design-system/components/button';\nimport IconButton from 'oneslash-design-system/components/iconButton';\nimport Tooltip from 'oneslash-design-system/components/tooltip';\nimport TextField from 'oneslash-design-system/components/textField';\nimport Popover from 'oneslash-design-system/components/popover';\nimport Menu from 'oneslash-design-system/components/menu';\nimport MenuItem from 'oneslash-design-system/components/menuItem';\nimport Line from 'oneslash-design-system/components/line';\nimport Tag from 'oneslash-design-system/components/tag';\nimport Pagination from 'oneslash-design-system/components/pagination';\nimport TableContainer from 'oneslash-design-system/components/tableContainer';\nimport TableHeader from 'oneslash-design-system/components/tableHeader';\nimport TableHeaderCell from 'oneslash-design-system/components/tableHeaderCell';\nimport TableRow from 'oneslash-design-system/components/tableRow';\nimport TableCell from 'oneslash-design-system/components/tableCell';\nimport { formatCount, formatMoney } from 'oneslash-design-system/components/formatNumber';\nimport { Center, Cluster, Stack } from 'oneslash-design-system/components/layout';\n\ntype Status = 'Paid' | 'Past due' | 'Refunded';\ntype Invoice = { id: string; number: string; customer: string; day: number; date: string; cents: number; status: Status };\ntype SortBy = 'customer' | 'date' | 'amount';\ntype Focusable = HTMLButtonElement | HTMLAnchorElement | null;\n\nconst customers = ['Northwind', 'Harbor Studio', 'Lumen Labs', 'Pine and Co', 'Cedar Works', 'Bright Dental', 'Maple Design', 'Atlas Freight', 'Juniper Foods', 'Orchard Legal'];\nconst monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];\n\n// A real app asks the server for one page. This makes the 290 invoices the server would hold, newest first.\nconst all: Invoice[] = Array.from({ length: 290 }, (_, i) => {\n const day = new Date(Date.UTC(2026, 10, 28 - i));\n return {\n id: `inv-${i}`,\n number: `INV-${1290 - i}`,\n customer: customers[(i * 7 + 3) % customers.length],\n day: i,\n date: `${monthNames[day.getUTCMonth()]} ${day.getUTCDate()}, ${day.getUTCFullYear()}`,\n cents: 2400 + ((i * 5303) % 40000),\n status: i % 11 === 4 ? 'Past due' : i % 9 === 5 ? 'Refunded' : 'Paid',\n };\n});\n\nconst statuses: Status[] = ['Paid', 'Past due', 'Refunded'];\nconst PAGE_SIZE = 25;\n\nexport default function DataTablePagePaged() {\n const [query, setQuery] = useState('');\n const [status, setStatus] = useState<Status | null>(null);\n // Opens newest first.\n const [sort, setSort] = useState<{ by: SortBy; dir: 'ascending' | 'descending' }>({ by: 'date', dir: 'descending' });\n const [page, setPage] = useState(1);\n const [loading, setLoading] = useState(false);\n const [failed, setFailed] = useState(false);\n\n const [searchAnchor, setSearchAnchor] = useState<HTMLElement | null>(null);\n const [searchOpen, setSearchOpen] = useState(false);\n const [filterAnchor, setFilterAnchor] = useState<HTMLElement | null>(null);\n const [filterOpen, setFilterOpen] = useState(false);\n const [menuRow, setMenuRow] = useState<Invoice | null>(null);\n const [menuAnchor, setMenuAnchor] = useState<HTMLElement | null>(null);\n const [menuOpen, setMenuOpen] = useState(false);\n\n const timer = useRef<ReturnType<typeof setTimeout>>();\n const failedOnce = useRef(false);\n const mounted = useRef(true);\n const toastIds = useRef<string[]>([]);\n const searchButton = useRef<Focusable>(null);\n\n // On unmount it stops the request and closes every toast it opened.\n useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n clearTimeout(timer.current);\n toastIds.current.forEach((id) => dismissToast(id));\n toastIds.current = [];\n };\n }, []);\n\n // The server sorts and filters, so the page asks it again for every change. The header and the pager stay while it answers.\n function request(forPage: number) {\n clearTimeout(timer.current);\n setLoading(true);\n timer.current = setTimeout(() => {\n setLoading(false);\n // The failure stays on screen, with its Button, until the new answer arrives.\n setFailed(false);\n // Stands in for a network failure, once: page 3 fails the first time it is asked for.\n if (forPage === 3 && !failedOnce.current) {\n failedOnce.current = true;\n setFailed(true);\n }\n }, 600);\n }\n\n // A sort, a search or a filter goes back to page 1: page 4 of the old list means nothing in the new one.\n // A real app waits a moment after the last key before it asks the server for a search.\n function change(next: { query?: string; status?: Status | null; sort?: { by: SortBy; dir: 'ascending' | 'descending' } }) {\n if (next.query !== undefined) setQuery(next.query);\n if (next.status !== undefined) setStatus(next.status);\n if (next.sort !== undefined) setSort(next.sort);\n setPage(1);\n request(1);\n }\n\n function goToPage(next: number) {\n setPage(next);\n request(next);\n }\n\n // The first press on a column sorts it A to Z, and the next one reverses it.\n function handleSort(by: SortBy) {\n change({ sort: { by, dir: sort.by === by && sort.dir === 'ascending' ? 'descending' : 'ascending' } });\n }\n\n const words = query.trim();\n const found = all\n .filter((inv) => (status === null || inv.status === status) && (words === '' || `${inv.number} ${inv.customer}`.toLowerCase().includes(words.toLowerCase())))\n .sort((a, b) => {\n const order = sort.by === 'customer' ? a.customer.localeCompare(b.customer) : sort.by === 'amount' ? a.cents - b.cents : b.day - a.day;\n return (sort.dir === 'ascending' ? order : -order) || a.day - b.day;\n });\n const pageCount = Math.ceil(found.length / PAGE_SIZE);\n const rows = found.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);\n const filtering = words !== '' || status !== null;\n\n // The line under the title says the total, and what the search and the filter leave.\n const matching = [words !== '' ? `\"${words}\"` : null, status !== null ? status.toLowerCase() : null].filter(Boolean).join(', ');\n const countLine = filtering ? `${formatCount(found.length)} of ${formatCount(all.length)} invoices match ${matching}.` : `${formatCount(all.length)} ${all.length === 1 ? 'invoice' : 'invoices'}`;\n\n // The Button clears the words and the filter. Focus goes to the search button, because the field is in the closed Popover.\n function clearFilter() {\n change({ query: '', status: null });\n searchButton.current?.focus();\n }\n\n function openMenu(inv: Invoice, anchor: HTMLElement) {\n if (menuOpen && menuRow?.id === inv.id) {\n setMenuOpen(false);\n return;\n }\n setMenuRow(inv);\n setMenuAnchor(anchor);\n setMenuOpen(true);\n }\n\n function choose(action: (inv: Invoice) => void) {\n if (!menuRow) return;\n const inv = menuRow;\n setMenuOpen(false);\n action(inv);\n }\n\n function sendReceipt(inv: Invoice) {\n toastIds.current.push(toast({ type: 'success', message: `Receipt for ${inv.number} sent to ${inv.customer}.` }));\n }\n\n // Only reads 'copied' when the number reached the clipboard.\n function copyNumber(inv: Invoice) {\n const failedCopy = () => {\n if (!mounted.current) return;\n toastIds.current.push(toast({ type: 'error', message: `Copying is blocked here. Select the number and copy it: ${inv.number}` }));\n };\n if (!navigator.clipboard) return failedCopy();\n navigator.clipboard.writeText(inv.number).then(() => {\n if (!mounted.current) return;\n toastIds.current.push(toast({ type: 'success', message: 'Invoice number copied.' }));\n }, failedCopy);\n }\n\n // The sorted column has `sort`; the others leave it unset, so exactly one header carries `aria-sort`.\n function sortHeader(by: SortBy, label: string, width?: string, align?: 'right') {\n const active = sort.by === by;\n const button = (\n <Button\n size=\"small\"\n type=\"tertiary\"\n state={active ? 'selected' : 'enabled'}\n label={label}\n decoIcon={active ? (sort.dir === 'ascending' ? 'ArrowUp' : 'ArrowDown') : undefined}\n onClickButton={() => handleSort(by)}\n />\n );\n return (\n <TableHeaderCell width={width} align={align} sort={active ? sort.dir : undefined}>\n {align === 'right' ? <Cluster justify=\"end\">{button}</Cluster> : button}\n </TableHeaderCell>\n );\n }\n\n function statusTag(s: Status) {\n // The case 'Status in a row': a dot and a color only for a state that needs action.\n return s === 'Past due' ? <Tag variant=\"dot\" size=\"small\" color=\"error\" label={s} /> : <Tag variant=\"textOnly\" size=\"small\" label={s} />;\n }\n\n return (\n <Center width=\"page\">\n {/* A real app mounts one Toaster near its root. */}\n <Toaster />\n <Stack gap=\"large\">\n <Stack gap=\"small\">\n <TitleBar title=\"Invoices\" id=\"data-table-page-paged-top\" />\n {loading ? <Skeleton variant=\"text\" width=\"medium\" /> : <Paragraph tone=\"secondary\" size=\"body2\" measure=\"none\">{countLine}</Paragraph>}\n </Stack>\n\n {/* Search and the filter sit above the table, as the cases 'Collapsible search' and 'Filter menu' say. */}\n <Cluster gap=\"small\" justify=\"end\">\n <Tooltip title={words !== '' ? `Search: ${words}` : 'Search'}>\n <IconButton\n ref={searchButton}\n color={words !== '' ? 'secondary' : 'iconOnly'}\n state={searchOpen ? 'selected' : 'enabled'}\n size=\"small\"\n iconName=\"Search\"\n ariaLabel={words !== '' ? `Search: ${words}` : 'Search'}\n aria-haspopup=\"dialog\"\n aria-expanded={searchOpen}\n onClick={(e: { currentTarget: HTMLElement }) => {\n setSearchAnchor(e.currentTarget);\n setSearchOpen((o) => !o);\n }}\n />\n </Tooltip>\n <Tooltip title={status ? status : 'Filter by status'}>\n <IconButton\n color={status ? 'secondary' : 'iconOnly'}\n state={filterOpen ? 'selected' : 'enabled'}\n size=\"small\"\n iconName=\"ListFilter\"\n ariaLabel={status ? `Filter by status: ${status}` : 'Filter by status'}\n aria-haspopup=\"menu\"\n aria-expanded={filterOpen}\n onClick={(e: { currentTarget: HTMLElement }) => {\n setFilterAnchor(e.currentTarget);\n setFilterOpen((o) => !o);\n }}\n />\n </Tooltip>\n </Cluster>\n\n {all.length === 0 ? (\n // A new workspace has none. The case 'Empty list' says what to write.\n <Surface minHeight=\"tall\" align=\"center\">\n <EmptyBox size=\"large\" text=\"No invoices yet\" secondText=\"Your first invoice appears here after your first payment.\" />\n </Surface>\n ) : failed ? (\n // The table's place: the header goes too, because nothing is left to sort. The pager stays.\n <Surface minHeight=\"tall\" align=\"center\">\n <EmptyBox\n size=\"large\"\n icon=\"CloudOff\"\n text=\"Could not load invoices\"\n secondText=\"Check your connection and try again.\"\n action={<Button size=\"medium\" type=\"primary\" state=\"enabled\" label=\"Try Again\" loading={loading} onClickButton={() => request(page)} />}\n />\n </Surface>\n ) : !loading && found.length === 0 ? (\n <Surface minHeight=\"tall\" align=\"center\">\n <EmptyBox\n size=\"large\"\n icon=\"Search\"\n text={words !== '' ? `No ${status ? `${status.toLowerCase()} ` : ''}invoices match \"${words}\"` : `No ${status?.toLowerCase()} invoices`}\n secondText={words !== '' ? 'Check the spelling, or search for fewer words.' : 'Choose another status, or clear the filter.'}\n action={<Button size=\"medium\" type=\"secondary\" state=\"enabled\" label={status !== null ? 'Clear Filter' : 'Clear Search'} onClickButton={clearFilter} />}\n />\n </Surface>\n ) : (\n <TableContainer aria-label=\"Invoices\" minWidth=\"640px\">\n <TableHeader>\n <TableRow>\n <TableHeaderCell width=\"110px\">Invoice</TableHeaderCell>\n {sortHeader('customer', 'Customer')}\n {sortHeader('date', 'Date', '140px')}\n {sortHeader('amount', 'Amount', '130px', 'right')}\n <TableHeaderCell width=\"120px\">Status</TableHeaderCell>\n <TableHeaderCell width=\"90px\">Actions</TableHeaderCell>\n </TableRow>\n </TableHeader>\n {loading\n ? Array.from({ length: 10 }, (_, i) => (\n <TableRow key={i}>\n {/* One status for the ten rows: the Skeleton with a label is announced once. */}\n <TableCell width=\"110px\">{i === 0 ? <Skeleton label=\"Loading invoices\" /> : <Skeleton />}</TableCell>\n <TableCell><Skeleton width=\"large\" /></TableCell>\n <TableCell width=\"140px\"><Skeleton /></TableCell>\n <TableCell width=\"130px\"><Skeleton /></TableCell>\n <TableCell width=\"120px\"><Skeleton width=\"large\" /></TableCell>\n <TableCell width=\"90px\"><Skeleton width=\"small\" /></TableCell>\n </TableRow>\n ))\n : rows.map((inv) => (\n <TableRow key={inv.id}>\n <TableCell width=\"110px\">{inv.number}</TableCell>\n <TableCell>{inv.customer}</TableCell>\n <TableCell width=\"140px\">{inv.date}</TableCell>\n {/* A table shows the exact amount, right-aligned. */}\n <TableCell width=\"130px\" align=\"right\">{formatMoney(inv.cents / 100)}</TableCell>\n <TableCell width=\"120px\">{statusTag(inv.status)}</TableCell>\n <TableCell width=\"90px\">\n <Tooltip title=\"More\">\n <IconButton\n color=\"iconOnly\"\n state={menuOpen && menuRow?.id === inv.id ? 'selected' : 'enabled'}\n size=\"small\"\n iconName=\"Ellipsis\"\n ariaLabel={`More actions for ${inv.number}`}\n aria-haspopup=\"menu\"\n aria-expanded={menuOpen && menuRow?.id === inv.id}\n onClick={(e: { currentTarget: HTMLElement }) => openMenu(inv, e.currentTarget)}\n />\n </Tooltip>\n </TableCell>\n </TableRow>\n ))}\n </TableContainer>\n )}\n\n {/* It shows nothing with one page. A real app also passes `getHref`, so each page has an address. */}\n <Pagination aria-label=\"Invoice pages\" page={page} pageCount={pageCount} onPageChange={goToPage} scrollTargetId=\"data-table-page-paged-top\" />\n </Stack>\n\n <Popover open={searchOpen} anchorEl={searchAnchor} onClose={() => setSearchOpen(false)} returnFocus aria-label=\"Search\">\n <Menu width={288}>\n <TextField\n id=\"data-table-page-paged-search\"\n type=\"search\"\n size=\"small\"\n autoFocus\n aria-label=\"Search invoices\"\n placeholder=\"Search invoices\"\n value={query}\n onChange={(e) => change({ query: e.target.value })}\n onKeyDown={(e) => {\n // Escape clears the search and closes. Enter closes and keeps it.\n if (e.key === 'Escape') {\n e.preventDefault();\n change({ query: '' });\n setSearchOpen(false);\n } else if (e.key === 'Enter') {\n e.preventDefault();\n setSearchOpen(false);\n }\n }}\n />\n </Menu>\n </Popover>\n <Popover open={filterOpen} anchorEl={filterAnchor} onClose={() => setFilterOpen(false)} returnFocus>\n <Menu navigable aria-label=\"Filter by status\" width={200}>\n {statuses.map((s) => (\n <MenuItem\n key={s}\n size=\"small\"\n label={s === 'Past due' ? 'Past Due' : s}\n isSelected={s === status}\n role=\"menuitemradio\"\n onClick={() => {\n setFilterOpen(false);\n change({ status: s });\n }}\n />\n ))}\n {status && <Line />}\n {status && (\n <MenuItem\n size=\"small\"\n iconName=\"X\"\n label=\"Clear Filter\"\n onClick={() => {\n setFilterOpen(false);\n change({ status: null });\n }}\n />\n )}\n </Menu>\n </Popover>\n <Popover open={menuOpen} anchorEl={menuAnchor} onClose={() => setMenuOpen(false)} returnFocus>\n <Menu navigable aria-label={menuRow ? `Actions for ${menuRow.number}` : 'Invoice actions'} width={220}>\n <MenuItem size=\"small\" iconName=\"Copy\" label=\"Copy Invoice Number\" onClick={() => choose(copyNumber)} />\n <MenuItem size=\"small\" iconName=\"Mail\" label=\"Send Receipt\" onClick={() => choose(sendReceipt)} />\n </Menu>\n </Popover>\n </Center>\n );\n}\n",
|
|
2265
2359
|
"uses": [
|
|
2266
2360
|
"Button",
|
|
2267
2361
|
"Center",
|
|
@@ -2297,7 +2391,7 @@
|
|
|
2297
2391
|
"id": "all-rows",
|
|
2298
2392
|
"title": "All rows, sorted in place",
|
|
2299
2393
|
"useWhen": "There are under about 50 rows, so the page holds them all and sorts and filters them at once.",
|
|
2300
|
-
"source": "'use client';\nimport { useEffect, useRef, useState } from 'react';\nimport Toaster, { toast, dismissToast } from 'oneslash-design-system/components/toaster';\nimport TitleBar from 'oneslash-design-system/components/titleBar';\nimport Paragraph from 'oneslash-design-system/components/paragraph';\nimport Surface from 'oneslash-design-system/components/surface';\nimport EmptyBox from 'oneslash-design-system/components/emptyBox';\nimport Button from 'oneslash-design-system/components/button';\nimport IconButton from 'oneslash-design-system/components/iconButton';\nimport Tooltip from 'oneslash-design-system/components/tooltip';\nimport TextField from 'oneslash-design-system/components/textField';\nimport Popover from 'oneslash-design-system/components/popover';\nimport Menu from 'oneslash-design-system/components/menu';\nimport MenuItem from 'oneslash-design-system/components/menuItem';\nimport Line from 'oneslash-design-system/components/line';\nimport Tag from 'oneslash-design-system/components/tag';\nimport TableContainer from 'oneslash-design-system/components/tableContainer';\nimport TableHeader from 'oneslash-design-system/components/tableHeader';\nimport TableHeaderCell from 'oneslash-design-system/components/tableHeaderCell';\nimport TableRow from 'oneslash-design-system/components/tableRow';\nimport TableCell from 'oneslash-design-system/components/tableCell';\nimport { formatCount, formatMoney } from 'oneslash-design-system/components/formatNumber';\nimport { Center, Cluster, Stack } from 'oneslash-design-system/components/layout';\n\ntype Status = 'Paid' | 'Past due' | 'Refunded';\ntype Invoice = { id: string; number: string; customer: string; day: number; date: string; cents: number; status: Status };\ntype SortBy = 'customer' | 'date' | 'amount';\ntype Focusable = HTMLButtonElement | HTMLAnchorElement | null;\n\nconst customers = ['Northwind', 'Harbor Studio', 'Lumen Labs', 'Pine and Co', 'Cedar Works', 'Bright Dental', 'Maple Design', 'Atlas Freight', 'Juniper Foods', 'Orchard Legal'];\nconst monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];\n\n// A real app reads all of them in one request: 42 is few enough to hold, sort and filter in the page.\nconst all: Invoice[] = Array.from({ length: 42 }, (_, i) => {\n const day = new Date(Date.UTC(2026, 10, 28 - i));\n return {\n id: `inv-${i}`,\n number: `INV-${1042 - i}`,\n customer: customers[(i * 7 + 3) % customers.length],\n day: i,\n date: `${monthNames[day.getUTCMonth()]} ${day.getUTCDate()}, ${day.getUTCFullYear()}`,\n cents: 2400 + ((i * 5303) % 40000),\n status: i % 11 === 4 ? 'Past due' : i % 9 === 5 ? 'Refunded' : 'Paid',\n };\n});\n\nconst statuses: Status[] = ['Paid', 'Past due', 'Refunded'];\n\nexport default function DataTablePageAllRows() {\n const [query, setQuery] = useState('');\n const [status, setStatus] = useState<Status | null>(null);\n // Opens newest first.\n const [sort, setSort] = useState<{ by: SortBy; dir: 'ascending' | 'descending' }>({ by: 'date', dir: 'descending' });\n\n const [searchAnchor, setSearchAnchor] = useState<HTMLElement | null>(null);\n const [searchOpen, setSearchOpen] = useState(false);\n const [filterAnchor, setFilterAnchor] = useState<HTMLElement | null>(null);\n const [filterOpen, setFilterOpen] = useState(false);\n const [menuRow, setMenuRow] = useState<Invoice | null>(null);\n const [menuAnchor, setMenuAnchor] = useState<HTMLElement | null>(null);\n const [menuOpen, setMenuOpen] = useState(false);\n\n const mounted = useRef(true);\n const toastIds = useRef<string[]>([]);\n const searchButton = useRef<Focusable>(null);\n\n // On unmount it closes every toast it opened.\n useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n toastIds.current.forEach((id) => dismissToast(id));\n toastIds.current = [];\n };\n }, []);\n\n // The first press on a column sorts it A to Z, and the next one reverses it. The rows are here, so it answers at once.\n function handleSort(by: SortBy) {\n setSort((current) => ({ by, dir: current.by === by && current.dir === 'ascending' ? 'descending' : 'ascending' }));\n }\n\n const words = query.trim();\n const rows = all\n .filter((inv) => (status === null || inv.status === status) && (words === '' || `${inv.number} ${inv.customer}`.toLowerCase().includes(words.toLowerCase())))\n .sort((a, b) => {\n const order = sort.by === 'customer' ? a.customer.localeCompare(b.customer) : sort.by === 'amount' ? a.cents - b.cents : b.day - a.day;\n return (sort.dir === 'ascending' ? order : -order) || a.day - b.day;\n });\n const filtering = words !== '' || status !== null;\n\n // The line under the title says the total, and what the search and the filter leave.\n const matching = [words !== '' ? `\"${words}\"` : null, status !== null ? status.toLowerCase() : null].filter(Boolean).join(', ');\n const countLine = filtering ? `${formatCount(rows.length)} of ${formatCount(all.length)} invoices match ${matching}.` : `${formatCount(all.length)} ${all.length === 1 ? 'invoice' : 'invoices'}`;\n\n // The Button clears the words and the filter. Focus goes to the search button, because the field is in the closed Popover.\n function clearFilter() {\n setQuery('');\n setStatus(null);\n searchButton.current?.focus();\n }\n\n function openMenu(inv: Invoice, anchor: HTMLElement) {\n if (menuOpen && menuRow?.id === inv.id) {\n setMenuOpen(false);\n return;\n }\n setMenuRow(inv);\n setMenuAnchor(anchor);\n setMenuOpen(true);\n }\n\n function choose(action: (inv: Invoice) => void) {\n if (!menuRow) return;\n const inv = menuRow;\n setMenuOpen(false);\n action(inv);\n }\n\n function sendReceipt(inv: Invoice) {\n toastIds.current.push(toast({ type: 'success', message: `Receipt for ${inv.number} sent to ${inv.customer}.` }));\n }\n\n // Only reads 'copied' when the number reached the clipboard.\n function copyNumber(inv: Invoice) {\n const failedCopy = () => {\n if (!mounted.current) return;\n toastIds.current.push(toast({ type: 'error', message: `Copying is blocked here. Select the number and copy it: ${inv.number}` }));\n };\n if (!navigator.clipboard) return failedCopy();\n navigator.clipboard.writeText(inv.number).then(() => {\n if (!mounted.current) return;\n toastIds.current.push(toast({ type: 'success', message: 'Invoice number copied.' }));\n }, failedCopy);\n }\n\n // The sorted column has `sort`; the others leave it unset, so exactly one header carries `aria-sort`.\n function sortHeader(by: SortBy, label: string, width?: string, align?: 'right') {\n const active = sort.by === by;\n const button = (\n <Button\n size=\"small\"\n type=\"tertiary\"\n state={active ? 'selected' : 'enabled'}\n label={label}\n decoIcon={active ? (sort.dir === 'ascending' ? 'ArrowUp' : 'ArrowDown') : undefined}\n onClickButton={() => handleSort(by)}\n />\n );\n return (\n <TableHeaderCell width={width} align={align} sort={active ? sort.dir : undefined}>\n {align === 'right' ? <Cluster justify=\"end\">{button}</Cluster> : button}\n </TableHeaderCell>\n );\n }\n\n function statusTag(s: Status) {\n // The case 'Status in a row': a dot and a color only for a state that needs action.\n return s === 'Past due' ? <Tag variant=\"dot\" size=\"small\" color=\"error\" label={s} /> : <Tag variant=\"textOnly\" size=\"small\" label={s} />;\n }\n\n return (\n <Center width=\"page\">\n {/* A real app mounts one Toaster near its root. */}\n <Toaster />\n <Stack gap=\"large\">\n <Stack gap=\"small\">\n <TitleBar title=\"Invoices\" />\n <Paragraph tone=\"secondary\" size=\"body2\" measure=\"none\">{countLine}</Paragraph>\n </Stack>\n\n {/* Search and the filter sit above the table, as the cases 'Collapsible search' and 'Filter menu' say. */}\n <Cluster gap=\"small\" justify=\"end\">\n <Tooltip title={words !== '' ? `Search: ${words}` : 'Search'}>\n <IconButton\n ref={searchButton}\n color={words !== '' ? 'secondary' : 'iconOnly'}\n state={searchOpen ? 'selected' : 'enabled'}\n size=\"small\"\n iconName=\"Search\"\n ariaLabel={words !== '' ? `Search: ${words}` : 'Search'}\n aria-haspopup=\"dialog\"\n aria-expanded={searchOpen}\n onClick={(e: { currentTarget: HTMLElement }) => {\n setSearchAnchor(e.currentTarget);\n setSearchOpen((o) => !o);\n }}\n />\n </Tooltip>\n <Tooltip title={status ? status : 'Filter by status'}>\n <IconButton\n color={status ? 'secondary' : 'iconOnly'}\n state={filterOpen ? 'selected' : 'enabled'}\n size=\"small\"\n iconName=\"ListFilter\"\n ariaLabel={status ? `Filter by status: ${status}` : 'Filter by status'}\n aria-haspopup=\"menu\"\n aria-expanded={filterOpen}\n onClick={(e: { currentTarget: HTMLElement }) => {\n setFilterAnchor(e.currentTarget);\n setFilterOpen((o) => !o);\n }}\n />\n </Tooltip>\n </Cluster>\n\n {all.length === 0 ? (\n // A new workspace has none. The case 'Empty list' says what to write.\n <Surface minHeight=\"tall\" align=\"center\">\n <EmptyBox size=\"large\" text=\"No invoices yet\" secondText=\"Your first invoice appears here after your first payment.\" />\n </Surface>\n ) : rows.length === 0 ? (\n <Surface minHeight=\"tall\" align=\"center\">\n <EmptyBox\n size=\"large\"\n icon=\"Search\"\n text={words !== '' ? `No ${status ? `${status.toLowerCase()} ` : ''}invoices match \"${words}\"` : `No ${status?.toLowerCase()} invoices`}\n secondText={words !== '' ? 'Check the spelling, or search for fewer words.' : 'Choose another status, or clear the filter.'}\n action={<Button size=\"medium\" type=\"secondary\" state=\"enabled\" label={status !== null ? 'Clear Filter' : 'Clear Search'} onClickButton={clearFilter} />}\n />\n </Surface>\n ) : (\n <TableContainer aria-label=\"Invoices\" minWidth=\"640px\">\n <TableHeader>\n <TableRow>\n <TableHeaderCell width=\"110px\">Invoice</TableHeaderCell>\n {sortHeader('customer', 'Customer')}\n {sortHeader('date', 'Date', '140px')}\n {sortHeader('amount', 'Amount', '130px', 'right')}\n <TableHeaderCell width=\"120px\">Status</TableHeaderCell>\n <TableHeaderCell width=\"90px\">Actions</TableHeaderCell>\n </TableRow>\n </TableHeader>\n {rows.map((inv) => (\n <TableRow key={inv.id}>\n <TableCell width=\"110px\">{inv.number}</TableCell>\n <TableCell>{inv.customer}</TableCell>\n <TableCell width=\"140px\">{inv.date}</TableCell>\n {/* A table shows the exact amount, right-aligned. */}\n <TableCell width=\"130px\" align=\"right\">{formatMoney(inv.cents / 100)}</TableCell>\n <TableCell width=\"120px\">{statusTag(inv.status)}</TableCell>\n <TableCell width=\"90px\">\n <Tooltip title=\"More\">\n <IconButton\n color=\"iconOnly\"\n state={menuOpen && menuRow?.id === inv.id ? 'selected' : 'enabled'}\n size=\"small\"\n iconName=\"Ellipsis\"\n ariaLabel={`More actions for ${inv.number}`}\n aria-haspopup=\"menu\"\n aria-expanded={menuOpen && menuRow?.id === inv.id}\n onClick={(e: { currentTarget: HTMLElement }) => openMenu(inv, e.currentTarget)}\n />\n </Tooltip>\n </TableCell>\n </TableRow>\n ))}\n </TableContainer>\n )}\n </Stack>\n\n <Popover open={searchOpen} anchorEl={searchAnchor} onClose={() => setSearchOpen(false)} returnFocus>\n <Menu width={288}>\n <TextField\n id=\"data-table-page-all-rows-search\"\n type=\"search\"\n size=\"small\"\n autoFocus\n aria-label=\"Search invoices\"\n placeholder=\"Search invoices\"\n value={query}\n onChange={(e) => setQuery(e.target.value)}\n onKeyDown={(e) => {\n // Escape clears the search and closes. Enter closes and keeps it.\n if (e.key === 'Escape') {\n e.preventDefault();\n setQuery('');\n setSearchOpen(false);\n } else if (e.key === 'Enter') {\n e.preventDefault();\n setSearchOpen(false);\n }\n }}\n />\n </Menu>\n </Popover>\n <Popover open={filterOpen} anchorEl={filterAnchor} onClose={() => setFilterOpen(false)} returnFocus>\n <Menu navigable aria-label=\"Filter by status\" width={200}>\n {statuses.map((s) => (\n <MenuItem\n key={s}\n size=\"small\"\n label={s === 'Past due' ? 'Past Due' : s}\n isSelected={s === status}\n role=\"menuitemradio\"\n onClick={() => {\n setFilterOpen(false);\n setStatus(s);\n }}\n />\n ))}\n {status && <Line />}\n {status && (\n <MenuItem\n size=\"small\"\n iconName=\"X\"\n label=\"Clear Filter\"\n onClick={() => {\n setFilterOpen(false);\n setStatus(null);\n }}\n />\n )}\n </Menu>\n </Popover>\n <Popover open={menuOpen} anchorEl={menuAnchor} onClose={() => setMenuOpen(false)} returnFocus>\n <Menu navigable aria-label={menuRow ? `Actions for ${menuRow.number}` : 'Invoice actions'} width={220}>\n <MenuItem size=\"small\" iconName=\"Copy\" label=\"Copy Invoice Number\" onClick={() => choose(copyNumber)} />\n <MenuItem size=\"small\" iconName=\"Mail\" label=\"Send Receipt\" onClick={() => choose(sendReceipt)} />\n </Menu>\n </Popover>\n </Center>\n );\n}\n",
|
|
2394
|
+
"source": "'use client';\nimport { useEffect, useRef, useState } from 'react';\nimport Toaster, { toast, dismissToast } from 'oneslash-design-system/components/toaster';\nimport TitleBar from 'oneslash-design-system/components/titleBar';\nimport Paragraph from 'oneslash-design-system/components/paragraph';\nimport Surface from 'oneslash-design-system/components/surface';\nimport EmptyBox from 'oneslash-design-system/components/emptyBox';\nimport Button from 'oneslash-design-system/components/button';\nimport IconButton from 'oneslash-design-system/components/iconButton';\nimport Tooltip from 'oneslash-design-system/components/tooltip';\nimport TextField from 'oneslash-design-system/components/textField';\nimport Popover from 'oneslash-design-system/components/popover';\nimport Menu from 'oneslash-design-system/components/menu';\nimport MenuItem from 'oneslash-design-system/components/menuItem';\nimport Line from 'oneslash-design-system/components/line';\nimport Tag from 'oneslash-design-system/components/tag';\nimport TableContainer from 'oneslash-design-system/components/tableContainer';\nimport TableHeader from 'oneslash-design-system/components/tableHeader';\nimport TableHeaderCell from 'oneslash-design-system/components/tableHeaderCell';\nimport TableRow from 'oneslash-design-system/components/tableRow';\nimport TableCell from 'oneslash-design-system/components/tableCell';\nimport { formatCount, formatMoney } from 'oneslash-design-system/components/formatNumber';\nimport { Center, Cluster, Stack } from 'oneslash-design-system/components/layout';\n\ntype Status = 'Paid' | 'Past due' | 'Refunded';\ntype Invoice = { id: string; number: string; customer: string; day: number; date: string; cents: number; status: Status };\ntype SortBy = 'customer' | 'date' | 'amount';\ntype Focusable = HTMLButtonElement | HTMLAnchorElement | null;\n\nconst customers = ['Northwind', 'Harbor Studio', 'Lumen Labs', 'Pine and Co', 'Cedar Works', 'Bright Dental', 'Maple Design', 'Atlas Freight', 'Juniper Foods', 'Orchard Legal'];\nconst monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];\n\n// A real app reads all of them in one request: 42 is few enough to hold, sort and filter in the page.\nconst all: Invoice[] = Array.from({ length: 42 }, (_, i) => {\n const day = new Date(Date.UTC(2026, 10, 28 - i));\n return {\n id: `inv-${i}`,\n number: `INV-${1042 - i}`,\n customer: customers[(i * 7 + 3) % customers.length],\n day: i,\n date: `${monthNames[day.getUTCMonth()]} ${day.getUTCDate()}, ${day.getUTCFullYear()}`,\n cents: 2400 + ((i * 5303) % 40000),\n status: i % 11 === 4 ? 'Past due' : i % 9 === 5 ? 'Refunded' : 'Paid',\n };\n});\n\nconst statuses: Status[] = ['Paid', 'Past due', 'Refunded'];\n\nexport default function DataTablePageAllRows() {\n const [query, setQuery] = useState('');\n const [status, setStatus] = useState<Status | null>(null);\n // Opens newest first.\n const [sort, setSort] = useState<{ by: SortBy; dir: 'ascending' | 'descending' }>({ by: 'date', dir: 'descending' });\n\n const [searchAnchor, setSearchAnchor] = useState<HTMLElement | null>(null);\n const [searchOpen, setSearchOpen] = useState(false);\n const [filterAnchor, setFilterAnchor] = useState<HTMLElement | null>(null);\n const [filterOpen, setFilterOpen] = useState(false);\n const [menuRow, setMenuRow] = useState<Invoice | null>(null);\n const [menuAnchor, setMenuAnchor] = useState<HTMLElement | null>(null);\n const [menuOpen, setMenuOpen] = useState(false);\n\n const mounted = useRef(true);\n const toastIds = useRef<string[]>([]);\n const searchButton = useRef<Focusable>(null);\n\n // On unmount it closes every toast it opened.\n useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n toastIds.current.forEach((id) => dismissToast(id));\n toastIds.current = [];\n };\n }, []);\n\n // The first press on a column sorts it A to Z, and the next one reverses it. The rows are here, so it answers at once.\n function handleSort(by: SortBy) {\n setSort((current) => ({ by, dir: current.by === by && current.dir === 'ascending' ? 'descending' : 'ascending' }));\n }\n\n const words = query.trim();\n const rows = all\n .filter((inv) => (status === null || inv.status === status) && (words === '' || `${inv.number} ${inv.customer}`.toLowerCase().includes(words.toLowerCase())))\n .sort((a, b) => {\n const order = sort.by === 'customer' ? a.customer.localeCompare(b.customer) : sort.by === 'amount' ? a.cents - b.cents : b.day - a.day;\n return (sort.dir === 'ascending' ? order : -order) || a.day - b.day;\n });\n const filtering = words !== '' || status !== null;\n\n // The line under the title says the total, and what the search and the filter leave.\n const matching = [words !== '' ? `\"${words}\"` : null, status !== null ? status.toLowerCase() : null].filter(Boolean).join(', ');\n const countLine = filtering ? `${formatCount(rows.length)} of ${formatCount(all.length)} invoices match ${matching}.` : `${formatCount(all.length)} ${all.length === 1 ? 'invoice' : 'invoices'}`;\n\n // The Button clears the words and the filter. Focus goes to the search button, because the field is in the closed Popover.\n function clearFilter() {\n setQuery('');\n setStatus(null);\n searchButton.current?.focus();\n }\n\n function openMenu(inv: Invoice, anchor: HTMLElement) {\n if (menuOpen && menuRow?.id === inv.id) {\n setMenuOpen(false);\n return;\n }\n setMenuRow(inv);\n setMenuAnchor(anchor);\n setMenuOpen(true);\n }\n\n function choose(action: (inv: Invoice) => void) {\n if (!menuRow) return;\n const inv = menuRow;\n setMenuOpen(false);\n action(inv);\n }\n\n function sendReceipt(inv: Invoice) {\n toastIds.current.push(toast({ type: 'success', message: `Receipt for ${inv.number} sent to ${inv.customer}.` }));\n }\n\n // Only reads 'copied' when the number reached the clipboard.\n function copyNumber(inv: Invoice) {\n const failedCopy = () => {\n if (!mounted.current) return;\n toastIds.current.push(toast({ type: 'error', message: `Copying is blocked here. Select the number and copy it: ${inv.number}` }));\n };\n if (!navigator.clipboard) return failedCopy();\n navigator.clipboard.writeText(inv.number).then(() => {\n if (!mounted.current) return;\n toastIds.current.push(toast({ type: 'success', message: 'Invoice number copied.' }));\n }, failedCopy);\n }\n\n // The sorted column has `sort`; the others leave it unset, so exactly one header carries `aria-sort`.\n function sortHeader(by: SortBy, label: string, width?: string, align?: 'right') {\n const active = sort.by === by;\n const button = (\n <Button\n size=\"small\"\n type=\"tertiary\"\n state={active ? 'selected' : 'enabled'}\n label={label}\n decoIcon={active ? (sort.dir === 'ascending' ? 'ArrowUp' : 'ArrowDown') : undefined}\n onClickButton={() => handleSort(by)}\n />\n );\n return (\n <TableHeaderCell width={width} align={align} sort={active ? sort.dir : undefined}>\n {align === 'right' ? <Cluster justify=\"end\">{button}</Cluster> : button}\n </TableHeaderCell>\n );\n }\n\n function statusTag(s: Status) {\n // The case 'Status in a row': a dot and a color only for a state that needs action.\n return s === 'Past due' ? <Tag variant=\"dot\" size=\"small\" color=\"error\" label={s} /> : <Tag variant=\"textOnly\" size=\"small\" label={s} />;\n }\n\n return (\n <Center width=\"page\">\n {/* A real app mounts one Toaster near its root. */}\n <Toaster />\n <Stack gap=\"large\">\n <Stack gap=\"small\">\n <TitleBar title=\"Invoices\" />\n <Paragraph tone=\"secondary\" size=\"body2\" measure=\"none\">{countLine}</Paragraph>\n </Stack>\n\n {/* Search and the filter sit above the table, as the cases 'Collapsible search' and 'Filter menu' say. */}\n <Cluster gap=\"small\" justify=\"end\">\n <Tooltip title={words !== '' ? `Search: ${words}` : 'Search'}>\n <IconButton\n ref={searchButton}\n color={words !== '' ? 'secondary' : 'iconOnly'}\n state={searchOpen ? 'selected' : 'enabled'}\n size=\"small\"\n iconName=\"Search\"\n ariaLabel={words !== '' ? `Search: ${words}` : 'Search'}\n aria-haspopup=\"dialog\"\n aria-expanded={searchOpen}\n onClick={(e: { currentTarget: HTMLElement }) => {\n setSearchAnchor(e.currentTarget);\n setSearchOpen((o) => !o);\n }}\n />\n </Tooltip>\n <Tooltip title={status ? status : 'Filter by status'}>\n <IconButton\n color={status ? 'secondary' : 'iconOnly'}\n state={filterOpen ? 'selected' : 'enabled'}\n size=\"small\"\n iconName=\"ListFilter\"\n ariaLabel={status ? `Filter by status: ${status}` : 'Filter by status'}\n aria-haspopup=\"menu\"\n aria-expanded={filterOpen}\n onClick={(e: { currentTarget: HTMLElement }) => {\n setFilterAnchor(e.currentTarget);\n setFilterOpen((o) => !o);\n }}\n />\n </Tooltip>\n </Cluster>\n\n {all.length === 0 ? (\n // A new workspace has none. The case 'Empty list' says what to write.\n <Surface minHeight=\"tall\" align=\"center\">\n <EmptyBox size=\"large\" text=\"No invoices yet\" secondText=\"Your first invoice appears here after your first payment.\" />\n </Surface>\n ) : rows.length === 0 ? (\n <Surface minHeight=\"tall\" align=\"center\">\n <EmptyBox\n size=\"large\"\n icon=\"Search\"\n text={words !== '' ? `No ${status ? `${status.toLowerCase()} ` : ''}invoices match \"${words}\"` : `No ${status?.toLowerCase()} invoices`}\n secondText={words !== '' ? 'Check the spelling, or search for fewer words.' : 'Choose another status, or clear the filter.'}\n action={<Button size=\"medium\" type=\"secondary\" state=\"enabled\" label={status !== null ? 'Clear Filter' : 'Clear Search'} onClickButton={clearFilter} />}\n />\n </Surface>\n ) : (\n <TableContainer aria-label=\"Invoices\" minWidth=\"640px\">\n <TableHeader>\n <TableRow>\n <TableHeaderCell width=\"110px\">Invoice</TableHeaderCell>\n {sortHeader('customer', 'Customer')}\n {sortHeader('date', 'Date', '140px')}\n {sortHeader('amount', 'Amount', '130px', 'right')}\n <TableHeaderCell width=\"120px\">Status</TableHeaderCell>\n <TableHeaderCell width=\"90px\">Actions</TableHeaderCell>\n </TableRow>\n </TableHeader>\n {rows.map((inv) => (\n <TableRow key={inv.id}>\n <TableCell width=\"110px\">{inv.number}</TableCell>\n <TableCell>{inv.customer}</TableCell>\n <TableCell width=\"140px\">{inv.date}</TableCell>\n {/* A table shows the exact amount, right-aligned. */}\n <TableCell width=\"130px\" align=\"right\">{formatMoney(inv.cents / 100)}</TableCell>\n <TableCell width=\"120px\">{statusTag(inv.status)}</TableCell>\n <TableCell width=\"90px\">\n <Tooltip title=\"More\">\n <IconButton\n color=\"iconOnly\"\n state={menuOpen && menuRow?.id === inv.id ? 'selected' : 'enabled'}\n size=\"small\"\n iconName=\"Ellipsis\"\n ariaLabel={`More actions for ${inv.number}`}\n aria-haspopup=\"menu\"\n aria-expanded={menuOpen && menuRow?.id === inv.id}\n onClick={(e: { currentTarget: HTMLElement }) => openMenu(inv, e.currentTarget)}\n />\n </Tooltip>\n </TableCell>\n </TableRow>\n ))}\n </TableContainer>\n )}\n </Stack>\n\n <Popover open={searchOpen} anchorEl={searchAnchor} onClose={() => setSearchOpen(false)} returnFocus aria-label=\"Search\">\n <Menu width={288}>\n <TextField\n id=\"data-table-page-all-rows-search\"\n type=\"search\"\n size=\"small\"\n autoFocus\n aria-label=\"Search invoices\"\n placeholder=\"Search invoices\"\n value={query}\n onChange={(e) => setQuery(e.target.value)}\n onKeyDown={(e) => {\n // Escape clears the search and closes. Enter closes and keeps it.\n if (e.key === 'Escape') {\n e.preventDefault();\n setQuery('');\n setSearchOpen(false);\n } else if (e.key === 'Enter') {\n e.preventDefault();\n setSearchOpen(false);\n }\n }}\n />\n </Menu>\n </Popover>\n <Popover open={filterOpen} anchorEl={filterAnchor} onClose={() => setFilterOpen(false)} returnFocus>\n <Menu navigable aria-label=\"Filter by status\" width={200}>\n {statuses.map((s) => (\n <MenuItem\n key={s}\n size=\"small\"\n label={s === 'Past due' ? 'Past Due' : s}\n isSelected={s === status}\n role=\"menuitemradio\"\n onClick={() => {\n setFilterOpen(false);\n setStatus(s);\n }}\n />\n ))}\n {status && <Line />}\n {status && (\n <MenuItem\n size=\"small\"\n iconName=\"X\"\n label=\"Clear Filter\"\n onClick={() => {\n setFilterOpen(false);\n setStatus(null);\n }}\n />\n )}\n </Menu>\n </Popover>\n <Popover open={menuOpen} anchorEl={menuAnchor} onClose={() => setMenuOpen(false)} returnFocus>\n <Menu navigable aria-label={menuRow ? `Actions for ${menuRow.number}` : 'Invoice actions'} width={220}>\n <MenuItem size=\"small\" iconName=\"Copy\" label=\"Copy Invoice Number\" onClick={() => choose(copyNumber)} />\n <MenuItem size=\"small\" iconName=\"Mail\" label=\"Send Receipt\" onClick={() => choose(sendReceipt)} />\n </Menu>\n </Popover>\n </Center>\n );\n}\n",
|
|
2301
2395
|
"uses": [
|
|
2302
2396
|
"Button",
|
|
2303
2397
|
"Center",
|
|
@@ -3511,7 +3605,9 @@
|
|
|
3511
3605
|
"Follow the rule 'A number shows its unit and never shows 0 for unknown'.",
|
|
3512
3606
|
"Show a `TableContainer` named 'Invoices', with `minWidth`, and the columns Date, Description, Amount, Status and Download.",
|
|
3513
3607
|
"Write the amount exactly, with `formatMoney`, in a right-aligned column with a right-aligned header: '$24.00'.",
|
|
3514
|
-
"Show the status as the case 'Status in a row' says: 'Paid' and '
|
|
3608
|
+
"Show the status as the case 'Status in a row' says: 'Paid', 'Refunded' and a refund's 'Issued' as `Tag variant=\"textOnly\"`, and 'Past due' as a dot.",
|
|
3609
|
+
"Show a refund as its own row: what it refunds, the amount with a minus, and the day it was made. Mark a charge 'Refunded' only when all of it came back.",
|
|
3610
|
+
"Write a refund row as 'Refund for Pro plan, Aug 2026' with '-$24.00', or 'Refund for 15 days of Pro, Oct 2026' with '-$12.00' while its charge stays 'Paid'. Put it above the charge it refunds.",
|
|
3515
3611
|
"Show the newest first. Add `Pagination` named 'Invoice pages' past 12 invoices, and show none under that.",
|
|
3516
3612
|
"Give each 'Download' link a name with the date: 'Download invoice for Nov 1, 2026, opens in a new tab'. Use `Button` with `type=\"tertiary\"`, `href` and `openInNewTab`, with an external-link `actionIcon`.",
|
|
3517
3613
|
"Put an upcoming charge in the first row with an 'Upcoming' `Tag variant=\"dot\" color=\"info\"`. Give it no Download link, because no invoice exists yet.",
|
|
@@ -3521,7 +3617,7 @@
|
|
|
3521
3617
|
"Show only an amount and a status. Keep a card number, an account number and the name of the payment provider off the page."
|
|
3522
3618
|
],
|
|
3523
3619
|
"dont": [
|
|
3524
|
-
"Do not show the amount as '$24' or '24.00'. A table shows the exact amount, with its symbol and
|
|
3620
|
+
"Do not show the amount as '$24' or '24.00'. A table shows the exact amount, with its symbol and its currency's decimals.",
|
|
3525
3621
|
"Do not show a card number, even a part of it, in an invoice row.",
|
|
3526
3622
|
"Do not make the upcoming charge look like a paid invoice, or leave it out of the table when it differs from the plan price.",
|
|
3527
3623
|
"Do not name every Download link 'Download'. A screen reader lists the links apart from their rows.",
|
|
@@ -3535,7 +3631,7 @@
|
|
|
3535
3631
|
"id": "table",
|
|
3536
3632
|
"title": "A table of past invoices",
|
|
3537
3633
|
"useWhen": "A history of payments, the same amount each month or close to it.",
|
|
3538
|
-
"source": "'use client';\nimport { useState } from 'react';\nimport Heading from 'oneslash-design-system/components/heading';\nimport Button from 'oneslash-design-system/components/button';\nimport Tag from 'oneslash-design-system/components/tag';\nimport EmptyBox from 'oneslash-design-system/components/emptyBox';\nimport Pagination from 'oneslash-design-system/components/pagination';\nimport TableContainer from 'oneslash-design-system/components/tableContainer';\nimport TableHeader from 'oneslash-design-system/components/tableHeader';\nimport TableHeaderCell from 'oneslash-design-system/components/tableHeaderCell';\nimport TableRow from 'oneslash-design-system/components/tableRow';\nimport TableCell from 'oneslash-design-system/components/tableCell';\nimport { formatMoney } from 'oneslash-design-system/components/formatNumber';\nimport { Center, Stack } from 'oneslash-design-system/components/layout';\n\ntype Invoice = { id: string; date: string; description: string; amount: number; status: 'Paid' | 'Refunded' };\n\n// A real app reads these from the server, newest first.\nconst months = ['Nov 1, 2026', 'Oct 1, 2026', 'Sep 1, 2026', 'Aug 1, 2026', 'Jul 1, 2026', 'Jun 1, 2026', 'May 1, 2026', 'Apr 1, 2026', 'Mar 1, 2026', 'Feb 1, 2026', 'Jan 1, 2026', 'Dec 1, 2025', 'Nov 1, 2025', 'Oct 1, 2025'];\nconst invoices: Invoice[] = months.
|
|
3634
|
+
"source": "'use client';\nimport { useState } from 'react';\nimport Heading from 'oneslash-design-system/components/heading';\nimport Button from 'oneslash-design-system/components/button';\nimport Tag from 'oneslash-design-system/components/tag';\nimport EmptyBox from 'oneslash-design-system/components/emptyBox';\nimport Pagination from 'oneslash-design-system/components/pagination';\nimport TableContainer from 'oneslash-design-system/components/tableContainer';\nimport TableHeader from 'oneslash-design-system/components/tableHeader';\nimport TableHeaderCell from 'oneslash-design-system/components/tableHeaderCell';\nimport TableRow from 'oneslash-design-system/components/tableRow';\nimport TableCell from 'oneslash-design-system/components/tableCell';\nimport { formatMoney } from 'oneslash-design-system/components/formatNumber';\nimport { Center, Stack } from 'oneslash-design-system/components/layout';\n\n// A refund is a row of its own, with a minus. A charge reads 'Refunded' only when all of it came back.\ntype Invoice = { id: string; kind: 'charge' | 'refund'; date: string; description: string; amount: number; status: 'Paid' | 'Refunded' | 'Issued' };\n\n// A real app reads these from the server, newest first.\nconst months = ['Nov 1, 2026', 'Oct 1, 2026', 'Sep 1, 2026', 'Aug 1, 2026', 'Jul 1, 2026', 'Jun 1, 2026', 'May 1, 2026', 'Apr 1, 2026', 'Mar 1, 2026', 'Feb 1, 2026', 'Jan 1, 2026', 'Dec 1, 2025', 'Nov 1, 2025', 'Oct 1, 2025'];\n// Each refund by the charge it refunds: all of August, and 15 days of October.\nconst refunds: Record<string, Invoice> = {\n 'Aug 1, 2026': { id: 'ref-0', kind: 'refund', date: 'Aug 6, 2026', description: 'Refund for Pro plan, Aug 2026', amount: -24, status: 'Issued' },\n 'Oct 1, 2026': { id: 'ref-1', kind: 'refund', date: 'Oct 16, 2026', description: 'Refund for 15 days of Pro, Oct 2026', amount: -12, status: 'Issued' },\n};\nconst invoices: Invoice[] = months.flatMap((date, i): Invoice[] => {\n const amount = 24;\n const charge: Invoice = {\n id: `inv-${i}`,\n kind: 'charge',\n date,\n description: `Pro plan, ${date.split(' ')[0]} ${date.split(', ')[1]}`,\n amount,\n // Refunded in full, or still Paid when only part came back\n status: refunds[date] && -refunds[date].amount === amount ? 'Refunded' : 'Paid',\n };\n // The refund came later, so it sits above its charge\n return refunds[date] ? [refunds[date], charge] : [charge];\n});\n\nconst PAGE_SIZE = 12;\n\nexport default function InvoiceListTable() {\n const [page, setPage] = useState(1);\n const pageCount = Math.ceil(invoices.length / PAGE_SIZE);\n const rows = invoices.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);\n\n return (\n <Center width=\"page\">\n <Stack gap=\"large\">\n <Heading level={2} size=\"h5\">Invoices</Heading>\n {invoices.length === 0 ? (\n // A new workspace has none. The line says when the first one arrives.\n <EmptyBox size=\"small\" text=\"No invoices yet\" secondText=\"Your first invoice appears here after your first payment.\" />\n ) : (\n <>\n <TableContainer aria-label=\"Invoices\" minWidth=\"640px\">\n <TableHeader>\n <TableRow>\n <TableHeaderCell width=\"130px\">Date</TableHeaderCell>\n <TableHeaderCell>Description</TableHeaderCell>\n <TableHeaderCell width=\"100px\" align=\"right\">Amount</TableHeaderCell>\n <TableHeaderCell width=\"110px\">Status</TableHeaderCell>\n <TableHeaderCell width=\"130px\">Download</TableHeaderCell>\n </TableRow>\n </TableHeader>\n {rows.map((inv) => (\n <TableRow key={inv.id}>\n <TableCell width=\"130px\">{inv.date}</TableCell>\n <TableCell>{inv.description}</TableCell>\n {/* A table shows the exact amount, right-aligned. A refund has a minus: '-$24.00'. */}\n <TableCell width=\"100px\" align=\"right\">{formatMoney(inv.amount)}</TableCell>\n <TableCell width=\"110px\">\n <Tag variant=\"textOnly\" size=\"small\" label={inv.status} />\n </TableCell>\n <TableCell width=\"130px\">\n {/* A real app links to the file on its own server. The name says which invoice and that it opens a tab. */}\n <Button\n size=\"small\"\n type=\"tertiary\"\n state=\"enabled\"\n label=\"Download\"\n aria-label={`Download ${inv.kind === 'refund' ? 'refund' : 'invoice'} for ${inv.date}, opens in a new tab`}\n actionIcon=\"ExternalLink\"\n href={`https://acme.example/invoices/${inv.id}.pdf`}\n openInNewTab\n />\n </TableCell>\n </TableRow>\n ))}\n </TableContainer>\n {/* Shows nothing under 13 invoices. */}\n <Pagination aria-label=\"Invoice pages\" page={page} pageCount={pageCount} onPageChange={setPage} />\n </>\n )}\n </Stack>\n </Center>\n );\n}\n",
|
|
3539
3635
|
"uses": [
|
|
3540
3636
|
"Button",
|
|
3541
3637
|
"Center",
|
|
@@ -4524,7 +4620,7 @@
|
|
|
4524
4620
|
"Close the quick pick when an emoji is picked. Focus goes back to the button that opened it.",
|
|
4525
4621
|
"Move focus to the 'Add reaction' button when the chip that had it disappears, because its count reached 0.",
|
|
4526
4622
|
"Use `quick-pick` when six emoji cover most reactions, and `picker` when people use many. Both name each emoji in words.",
|
|
4527
|
-
"Open the picker from 'Add reaction' in a `<Popover returnFocus>` around `EmojiPicker`. Pass the person's emoji as `selected`, so they show pressed. A pick adds or removes the reaction and closes the Popover."
|
|
4623
|
+
"Open the picker from 'Add reaction' in a `<Popover returnFocus aria-label=\"Pick a reaction\">` around `EmojiPicker`. Pass the person's emoji as `selected`, so they show pressed. A pick adds or removes the reaction and closes the Popover."
|
|
4528
4624
|
],
|
|
4529
4625
|
"dont": [
|
|
4530
4626
|
"Do not show a chip with a count of 0.",
|
|
@@ -4579,7 +4675,7 @@
|
|
|
4579
4675
|
"id": "picker",
|
|
4580
4676
|
"title": "Emoji picker",
|
|
4581
4677
|
"useWhen": "People react with more than the usual six emoji.",
|
|
4582
|
-
"source": "'use client';\nimport { useEffect, useRef, useState } from 'react';\nimport Message from 'oneslash-design-system/components/message';\nimport UserImage from 'oneslash-design-system/components/userImage';\nimport TimeStamp from 'oneslash-design-system/components/timeStamp';\nimport Heading from 'oneslash-design-system/components/heading';\nimport Paragraph from 'oneslash-design-system/components/paragraph';\nimport Tag from 'oneslash-design-system/components/tag';\nimport IconButton from 'oneslash-design-system/components/iconButton';\nimport Tooltip from 'oneslash-design-system/components/tooltip';\nimport Popover from 'oneslash-design-system/components/popover';\nimport EmojiPicker from 'oneslash-design-system/components/emojiPicker';\nimport { Center, Cluster, Stack } from 'oneslash-design-system/components/layout';\n\n// A real app reads this from the session.\nconst me = 'Dana Lee';\n\n// Each reaction keeps the emoji's name in words, from the picker, for its chip's aria-label.\ntype Reaction = { emoji: string; name: string; by: string[] };\ntype Row = { id: string; from: string; at: Date; text: string; reactions: Reaction[] };\n\nconst firstThread: Row[] = [\n {\n id: 'm1',\n from: 'Ben Carter',\n at: new Date('2025-01-15T11:40:00Z'),\n text: 'The pricing page is live.',\n reactions: [\n { emoji: '👍', name: 'Thumbs up', by: ['Omar Reyes', me] },\n { emoji: '🙌', name: 'Raised hands', by: ['Omar Reyes'] },\n ],\n },\n { id: 'm2', from: 'Omar Reyes', at: new Date('2025-01-15T11:42:00Z'), text: 'Nice work. I will share it with the sales team.', reactions: [] },\n];\n\nconst firstName = (name: string) => name.split(' ')[0];\n\n// 'Omar and you': other people by first name, the person last.\nfunction whoReacted(by: string[]) {\n const names = [...by.filter((n) => n !== me).map(firstName), ...(by.includes(me) ? ['you'] : [])];\n if (names.length === 1) return names[0] === 'you' ? 'You' : names[0];\n return `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`;\n}\n\n// 'Thumbs up, 3 reactions'. The chip's aria-pressed says whether the person reacted.\nfunction chipName(r: Reaction) {\n const count = `${r.by.length} ${r.by.length === 1 ? 'reaction' : 'reactions'}`;\n return `${r.name}, ${count}`;\n}\n\nexport default function MessageReactionsPicker() {\n const [thread, setThread] = useState(firstThread);\n // Each row's 'Add reaction' button by row id. When the chip that had focus goes away, focus goes there.\n const addButtons = useRef<Record<string, HTMLButtonElement | HTMLAnchorElement | null>>({});\n const focusAdd = useRef<string | null>(null);\n\n useEffect(() => {\n if (!focusAdd.current) return;\n addButtons.current[focusAdd.current]?.focus();\n focusAdd.current = null;\n });\n // The row whose picker is open, and the button it opens from. Both stay set while it fades out.\n const [pickRow, setPickRow] = useState<Row | null>(null);\n const [pickAnchor, setPickAnchor] = useState<HTMLElement | null>(null);\n const [pickOpen, setPickOpen] = useState(false);\n\n // The count changes at once. A real app sends the change to the server and puts it back if that fails.\n function toggle(rowId: string, emoji: string, name: string) {\n const row = thread.find((m) => m.id === rowId);\n const chip = row?.reactions.find((r) => r.emoji === emoji);\n // The person's reaction was the last one, so the chip goes away.\n if (chip && chip.by.length === 1 && chip.by[0] === me) focusAdd.current = rowId;\n setThread((rows) =>\n rows.map((m) => {\n if (m.id !== rowId) return m;\n const has = m.reactions.find((r) => r.emoji === emoji);\n const reactions = has\n ? m.reactions.map((r) =>\n r.emoji !== emoji ? r : { ...r, by: r.by.includes(me) ? r.by.filter((n) => n !== me) : [...r.by, me] },\n )\n : [...m.reactions, { emoji, name, by: [me] }];\n // A chip with no reactions left goes away.\n return { ...m, reactions: reactions.filter((r) => r.by.length > 0) };\n }),\n );\n }\n\n function openPick(m: Row, anchor: HTMLElement) {\n if (pickOpen && pickRow?.id === m.id) {\n setPickOpen(false);\n return;\n }\n setPickRow(m);\n setPickAnchor(anchor);\n setPickOpen(true);\n }\n\n // Escape, a click outside and a pick close it. Popover's returnFocus gives focus back to 'Add reaction'.\n function closePick() {\n setPickOpen(false);\n }\n\n // The open row, read from the thread so the picker shows its reactions as they are now.\n const openRow = thread.find((m) => m.id === pickRow?.id);\n const mine = openRow ? openRow.reactions.filter((r) => r.by.includes(me)).map((r) => r.emoji) : [];\n\n return (\n <Center width=\"page\">\n <Stack gap=\"large\">\n <Heading level={1} size=\"h5\">Launch plan</Heading>\n {/* A real app gives the list that holds the rows role=\"log\". */}\n <Stack gap=\"small\">\n {thread.map((m) => (\n <Message\n key={m.id}\n aria-label={m.from}\n avatar={<UserImage userHandle={m.from} decorative />}\n name={m.from}\n meta={<TimeStamp createdAt={m.at} dateFormat=\"absolute\" data=\"time\" />}\n footer={\n <Cluster gap=\"small\">\n {m.reactions.map((r) => (\n <Tooltip key={r.emoji} title={whoReacted(r.by)}>\n <Tag\n variant=\"contained\"\n size=\"small\"\n state={r.by.includes(me) ? 'selected' : 'enabled'}\n label={`${r.emoji} ${r.by.length}`}\n aria-label={chipName(r)}\n onClick={() => toggle(m.id, r.emoji, r.name)}\n />\n </Tooltip>\n ))}\n <Tooltip title=\"Add reaction\">\n <IconButton\n color=\"iconOnly\"\n state={pickOpen && pickRow?.id === m.id ? 'selected' : 'enabled'}\n size=\"small\"\n ref={(el) => { addButtons.current[m.id] = el; }}\n iconName=\"SmilePlus\"\n ariaLabel={`Add reaction to message from ${m.from}`}\n aria-haspopup=\"dialog\"\n aria-expanded={pickOpen && pickRow?.id === m.id}\n onClick={(e: { currentTarget: HTMLElement }) => openPick(m, e.currentTarget)}\n />\n </Tooltip>\n </Cluster>\n }\n >\n <Paragraph measure=\"none\">{m.text}</Paragraph>\n </Message>\n ))}\n </Stack>\n </Stack>\n {/* The picker focuses its search. ArrowDown enters the grid; Tab and Shift+Tab move between the search and the grid. */}\n <Popover open={pickOpen} anchorEl={pickAnchor} onClose={closePick} returnFocus>\n <EmojiPicker\n id=\"message-reactions-picker\"\n aria-label=\"Add reaction\"\n // The emoji the person already used show pressed. Picking one again removes it.\n selected={mine}\n onPick={(emoji) => {\n if (!pickRow) return;\n closePick();\n toggle(pickRow.id, emoji.char, emoji.name);\n }}\n />\n </Popover>\n </Center>\n );\n}\n",
|
|
4678
|
+
"source": "'use client';\nimport { useEffect, useRef, useState } from 'react';\nimport Message from 'oneslash-design-system/components/message';\nimport UserImage from 'oneslash-design-system/components/userImage';\nimport TimeStamp from 'oneslash-design-system/components/timeStamp';\nimport Heading from 'oneslash-design-system/components/heading';\nimport Paragraph from 'oneslash-design-system/components/paragraph';\nimport Tag from 'oneslash-design-system/components/tag';\nimport IconButton from 'oneslash-design-system/components/iconButton';\nimport Tooltip from 'oneslash-design-system/components/tooltip';\nimport Popover from 'oneslash-design-system/components/popover';\nimport EmojiPicker from 'oneslash-design-system/components/emojiPicker';\nimport { Center, Cluster, Stack } from 'oneslash-design-system/components/layout';\n\n// A real app reads this from the session.\nconst me = 'Dana Lee';\n\n// Each reaction keeps the emoji's name in words, from the picker, for its chip's aria-label.\ntype Reaction = { emoji: string; name: string; by: string[] };\ntype Row = { id: string; from: string; at: Date; text: string; reactions: Reaction[] };\n\nconst firstThread: Row[] = [\n {\n id: 'm1',\n from: 'Ben Carter',\n at: new Date('2025-01-15T11:40:00Z'),\n text: 'The pricing page is live.',\n reactions: [\n { emoji: '👍', name: 'Thumbs up', by: ['Omar Reyes', me] },\n { emoji: '🙌', name: 'Raised hands', by: ['Omar Reyes'] },\n ],\n },\n { id: 'm2', from: 'Omar Reyes', at: new Date('2025-01-15T11:42:00Z'), text: 'Nice work. I will share it with the sales team.', reactions: [] },\n];\n\nconst firstName = (name: string) => name.split(' ')[0];\n\n// 'Omar and you': other people by first name, the person last.\nfunction whoReacted(by: string[]) {\n const names = [...by.filter((n) => n !== me).map(firstName), ...(by.includes(me) ? ['you'] : [])];\n if (names.length === 1) return names[0] === 'you' ? 'You' : names[0];\n return `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`;\n}\n\n// 'Thumbs up, 3 reactions'. The chip's aria-pressed says whether the person reacted.\nfunction chipName(r: Reaction) {\n const count = `${r.by.length} ${r.by.length === 1 ? 'reaction' : 'reactions'}`;\n return `${r.name}, ${count}`;\n}\n\nexport default function MessageReactionsPicker() {\n const [thread, setThread] = useState(firstThread);\n // Each row's 'Add reaction' button by row id. When the chip that had focus goes away, focus goes there.\n const addButtons = useRef<Record<string, HTMLButtonElement | HTMLAnchorElement | null>>({});\n const focusAdd = useRef<string | null>(null);\n\n useEffect(() => {\n if (!focusAdd.current) return;\n addButtons.current[focusAdd.current]?.focus();\n focusAdd.current = null;\n });\n // The row whose picker is open, and the button it opens from. Both stay set while it fades out.\n const [pickRow, setPickRow] = useState<Row | null>(null);\n const [pickAnchor, setPickAnchor] = useState<HTMLElement | null>(null);\n const [pickOpen, setPickOpen] = useState(false);\n\n // The count changes at once. A real app sends the change to the server and puts it back if that fails.\n function toggle(rowId: string, emoji: string, name: string) {\n const row = thread.find((m) => m.id === rowId);\n const chip = row?.reactions.find((r) => r.emoji === emoji);\n // The person's reaction was the last one, so the chip goes away.\n if (chip && chip.by.length === 1 && chip.by[0] === me) focusAdd.current = rowId;\n setThread((rows) =>\n rows.map((m) => {\n if (m.id !== rowId) return m;\n const has = m.reactions.find((r) => r.emoji === emoji);\n const reactions = has\n ? m.reactions.map((r) =>\n r.emoji !== emoji ? r : { ...r, by: r.by.includes(me) ? r.by.filter((n) => n !== me) : [...r.by, me] },\n )\n : [...m.reactions, { emoji, name, by: [me] }];\n // A chip with no reactions left goes away.\n return { ...m, reactions: reactions.filter((r) => r.by.length > 0) };\n }),\n );\n }\n\n function openPick(m: Row, anchor: HTMLElement) {\n if (pickOpen && pickRow?.id === m.id) {\n setPickOpen(false);\n return;\n }\n setPickRow(m);\n setPickAnchor(anchor);\n setPickOpen(true);\n }\n\n // Escape, a click outside and a pick close it. Popover's returnFocus gives focus back to 'Add reaction'.\n function closePick() {\n setPickOpen(false);\n }\n\n // The open row, read from the thread so the picker shows its reactions as they are now.\n const openRow = thread.find((m) => m.id === pickRow?.id);\n const mine = openRow ? openRow.reactions.filter((r) => r.by.includes(me)).map((r) => r.emoji) : [];\n\n return (\n <Center width=\"page\">\n <Stack gap=\"large\">\n <Heading level={1} size=\"h5\">Launch plan</Heading>\n {/* A real app gives the list that holds the rows role=\"log\". */}\n <Stack gap=\"small\">\n {thread.map((m) => (\n <Message\n key={m.id}\n aria-label={m.from}\n avatar={<UserImage userHandle={m.from} decorative />}\n name={m.from}\n meta={<TimeStamp createdAt={m.at} dateFormat=\"absolute\" data=\"time\" />}\n footer={\n <Cluster gap=\"small\">\n {m.reactions.map((r) => (\n <Tooltip key={r.emoji} title={whoReacted(r.by)}>\n <Tag\n variant=\"contained\"\n size=\"small\"\n state={r.by.includes(me) ? 'selected' : 'enabled'}\n label={`${r.emoji} ${r.by.length}`}\n aria-label={chipName(r)}\n onClick={() => toggle(m.id, r.emoji, r.name)}\n />\n </Tooltip>\n ))}\n <Tooltip title=\"Add reaction\">\n <IconButton\n color=\"iconOnly\"\n state={pickOpen && pickRow?.id === m.id ? 'selected' : 'enabled'}\n size=\"small\"\n ref={(el) => { addButtons.current[m.id] = el; }}\n iconName=\"SmilePlus\"\n ariaLabel={`Add reaction to message from ${m.from}`}\n aria-haspopup=\"dialog\"\n aria-expanded={pickOpen && pickRow?.id === m.id}\n onClick={(e: { currentTarget: HTMLElement }) => openPick(m, e.currentTarget)}\n />\n </Tooltip>\n </Cluster>\n }\n >\n <Paragraph measure=\"none\">{m.text}</Paragraph>\n </Message>\n ))}\n </Stack>\n </Stack>\n {/* The picker focuses its search. ArrowDown enters the grid; Tab and Shift+Tab move between the search and the grid. */}\n <Popover open={pickOpen} anchorEl={pickAnchor} onClose={closePick} returnFocus aria-label=\"Pick a reaction\">\n <EmojiPicker\n id=\"message-reactions-picker\"\n aria-label=\"Add reaction\"\n // The emoji the person already used show pressed. Picking one again removes it.\n selected={mine}\n onPick={(emoji) => {\n if (!pickRow) return;\n closePick();\n toggle(pickRow.id, emoji.char, emoji.name);\n }}\n />\n </Popover>\n </Center>\n );\n}\n",
|
|
4583
4679
|
"uses": [
|
|
4584
4680
|
"Center",
|
|
4585
4681
|
"Cluster",
|
|
@@ -4616,7 +4712,8 @@
|
|
|
4616
4712
|
"Put a date line between days, a `Line` with a `label` that reads 'Today', 'Yesterday', or the full date with the year: 'Monday, January 13, 2025'.",
|
|
4617
4713
|
"Pass an `aria-label` that names the sender on every row, compact ones too: 'Dana Lee', or 'Acme Agent, agent'. The time is in the row.",
|
|
4618
4714
|
"Give the list that holds the rows `role=\"log\"`, so a screen reader reads new messages as they arrive.",
|
|
4619
|
-
"Write an agent's text as
|
|
4715
|
+
"Write an agent's plain text as sentences in `Paragraph`.",
|
|
4716
|
+
"Render an agent's markdown with `Markdown`, never as raw text with its marks."
|
|
4620
4717
|
],
|
|
4621
4718
|
"dont": [
|
|
4622
4719
|
"Do not show a photo or an initial for an agent.",
|
|
@@ -4722,6 +4819,70 @@
|
|
|
4722
4819
|
}
|
|
4723
4820
|
]
|
|
4724
4821
|
},
|
|
4822
|
+
{
|
|
4823
|
+
"id": "newsletter-signup",
|
|
4824
|
+
"title": "Newsletter sign-up",
|
|
4825
|
+
"kind": "design",
|
|
4826
|
+
"level": "organism",
|
|
4827
|
+
"area": "marketing",
|
|
4828
|
+
"situation": "A reader of the public site wants to hear about the product by email, without making an account.",
|
|
4829
|
+
"do": [
|
|
4830
|
+
"Follow the rules 'A form error shows next to the problem' and 'Success shows where the person is looking'.",
|
|
4831
|
+
"Use a `Form` with a visible label 'Email address' on a `TextField type=\"email\" autoComplete=\"email\"`, and a Button 'Subscribe'.",
|
|
4832
|
+
"Make 'Subscribe' secondary. The page's one primary Button stays 'Sign Up', as the rule 'A marketing page asks for one main action, in the same words everywhere' says.",
|
|
4833
|
+
"Show a bad address on submit, under the field: 'Enter an email address, like name@example.com.' Keep the Button enabled.",
|
|
4834
|
+
"Make the pressed Button `loading` while the request runs, and keep its label. Make the field `readOnly` meanwhile, so focus stays in it.",
|
|
4835
|
+
"Replace the form with 'Check your email to confirm.' when the request works, and move focus to that line, so a screen reader reads it.",
|
|
4836
|
+
"Send an email to an address already on the list too, saying it is subscribed and how to leave, so the line is true for both.",
|
|
4837
|
+
"Show the same line for an address that is already on the list, so the form never tells who is subscribed.",
|
|
4838
|
+
"Confirm by email before sending anything, as the case 'Check your email' says.",
|
|
4839
|
+
"Say how often the email comes and how to leave, in `section`: 'One email a month with what shipped. Leave any time from the link in each email.'",
|
|
4840
|
+
"Put `section` after the post's text and before the case 'Page end' `next-link`, which still ends the page. It asks for an email, not an account, so it is not a sign-up banner.",
|
|
4841
|
+
"Put the sign-up above the footer, not in it, as the case 'Site footer' says. The footer's 'Newsletter' link goes to a page with this form."
|
|
4842
|
+
],
|
|
4843
|
+
"dont": [
|
|
4844
|
+
"Do not open the sign-up in a popup on scroll or when the reader leaves.",
|
|
4845
|
+
"Do not tick a box for marketing email before the reader does.",
|
|
4846
|
+
"Do not use a placeholder as the only label.",
|
|
4847
|
+
"Do not label the Button 'Sign Up'. That word means making an account.",
|
|
4848
|
+
"Do not say 'You are already subscribed'. It tells anyone whether an address is on the list.",
|
|
4849
|
+
"Do not disable the Button until the field is filled. Show the error on submit."
|
|
4850
|
+
],
|
|
4851
|
+
"native": "On Apple and Android an app has no newsletter form. Link to the web page that has it, or let the person turn on product news in the app's notification settings.",
|
|
4852
|
+
"options": [
|
|
4853
|
+
{
|
|
4854
|
+
"id": "inline",
|
|
4855
|
+
"title": "One field above the footer",
|
|
4856
|
+
"useWhen": "A sign-up just above the footer or at the end of a page, one field wide.",
|
|
4857
|
+
"source": "'use client';\nimport { useEffect, useRef, useState } from 'react';\nimport Form from 'oneslash-design-system/components/form';\nimport TextField from 'oneslash-design-system/components/textField';\nimport Button from 'oneslash-design-system/components/button';\nimport Heading from 'oneslash-design-system/components/heading';\nimport SiteFooter from 'oneslash-design-system/components/siteFooter';\nimport { Center, Stack } from 'oneslash-design-system/components/layout';\n\n// A small check: some text, an @, then some text.\nfunction looksLikeEmail(value: string) {\n return /^[^@\\s]+@[^@\\s]+$/.test(value);\n}\n\nexport default function NewsletterSignupInline() {\n const [email, setEmail] = useState('');\n const [error, setError] = useState('');\n const [sending, setSending] = useState(false);\n const [done, setDone] = useState(false);\n const timer = useRef<ReturnType<typeof setTimeout>>();\n const doneLine = useRef<HTMLHeadingElement>(null);\n\n // Stops the request if the example goes away before it ends.\n useEffect(() => () => clearTimeout(timer.current), []);\n\n // The form is gone, so focus moves to the line that took its place, and a screen reader reads it.\n useEffect(() => {\n if (done) doneLine.current?.focus({ preventScroll: true });\n }, [done]);\n\n // While it sends, the field is read-only, not disabled, so focus stays in it.\n function handleSubmit() {\n if (sending) return;\n // An empty field and a bad address get their own words. The Button stays enabled either way.\n const value = email.trim();\n if (!value) {\n setError('Enter your email.');\n return;\n }\n if (!looksLikeEmail(value)) {\n setError('Enter an email address, like name@example.com.');\n return;\n }\n setError('');\n setSending(true);\n // Stands in for the request to the server. It always sends an email: a link to confirm a new address,\n // or a note that an address already on the list is subscribed, with the link to leave.\n // A failed request shows an inline error Alert above the field instead, such as 'Could not subscribe. Try again.'\n timer.current = setTimeout(() => {\n setSending(false);\n // Both get an email, so the same line is true for both, and the form never tells who is subscribed.\n setDone(true);\n }, 1200);\n }\n\n return (\n <Stack gap=\"huge\">\n {/* The sign-up sits just above the footer, one field wide. The footer itself holds only links. */}\n <Center width=\"form\">\n <Stack gap=\"large\">\n <Heading level={2} size=\"subtitle1\">Get the Acme newsletter</Heading>\n {done ? (\n <Heading ref={doneLine} tabIndex={-1} level={3} size=\"subtitle1\">Check your email to confirm.</Heading>\n ) : (\n <Form aria-label=\"Get the Acme newsletter\" onSubmit={handleSubmit}>\n <TextField\n id=\"newsletter-signup-inline-email\"\n label=\"Email address\"\n type=\"email\"\n autoComplete=\"email\"\n value={email}\n readOnly={sending}\n error={Boolean(error)}\n errorText={error}\n onChange={(e) => { setEmail(e.target.value); setError(''); }}\n />\n <Stack align=\"start\">\n <Button size=\"medium\" type=\"secondary\" state=\"enabled\" label=\"Subscribe\" htmlType=\"submit\" loading={sending} />\n </Stack>\n </Form>\n )}\n </Stack>\n </Center>\n <SiteFooter\n brand={{ href: '#top', name: 'Acme' }}\n links={[\n { label: 'Pricing', href: '#pricing' },\n { label: 'Blog', href: '#blog' },\n { label: 'Privacy', href: '#privacy' },\n ]}\n legal=\"© 2026 Acme. All rights reserved.\"\n />\n </Stack>\n );\n}\n",
|
|
4858
|
+
"uses": [
|
|
4859
|
+
"Button",
|
|
4860
|
+
"Center",
|
|
4861
|
+
"Form",
|
|
4862
|
+
"Heading",
|
|
4863
|
+
"SiteFooter",
|
|
4864
|
+
"Stack",
|
|
4865
|
+
"TextField"
|
|
4866
|
+
]
|
|
4867
|
+
},
|
|
4868
|
+
{
|
|
4869
|
+
"id": "section",
|
|
4870
|
+
"title": "A section at the end of a post",
|
|
4871
|
+
"useWhen": "The end of a post, where a reader decides whether to hear more, so it says what comes and how often.",
|
|
4872
|
+
"source": "'use client';\nimport { useEffect, useRef, useState } from 'react';\nimport Surface from 'oneslash-design-system/components/surface';\nimport Form from 'oneslash-design-system/components/form';\nimport TextField from 'oneslash-design-system/components/textField';\nimport Button from 'oneslash-design-system/components/button';\nimport Heading from 'oneslash-design-system/components/heading';\nimport Paragraph from 'oneslash-design-system/components/paragraph';\nimport { Center, Stack } from 'oneslash-design-system/components/layout';\n\n// A small check: some text, an @, then some text.\nfunction looksLikeEmail(value: string) {\n return /^[^@\\s]+@[^@\\s]+$/.test(value);\n}\n\nexport default function NewsletterSignupSection() {\n const [email, setEmail] = useState('');\n const [error, setError] = useState('');\n const [sending, setSending] = useState(false);\n const [done, setDone] = useState(false);\n const timer = useRef<ReturnType<typeof setTimeout>>();\n const doneLine = useRef<HTMLHeadingElement>(null);\n\n // Stops the request if the example goes away before it ends.\n useEffect(() => () => clearTimeout(timer.current), []);\n\n // The form is gone, so focus moves to the line that took its place, and a screen reader reads it.\n useEffect(() => {\n if (done) doneLine.current?.focus({ preventScroll: true });\n }, [done]);\n\n // While it sends, the field is read-only, not disabled, so focus stays in it.\n function handleSubmit() {\n if (sending) return;\n // An empty field and a bad address get their own words. The Button stays enabled either way.\n const value = email.trim();\n if (!value) {\n setError('Enter your email.');\n return;\n }\n if (!looksLikeEmail(value)) {\n setError('Enter an email address, like name@example.com.');\n return;\n }\n setError('');\n setSending(true);\n // Stands in for the request to the server. It always sends an email: a link to confirm a new address,\n // or a note that an address already on the list is subscribed, with the link to leave.\n // A failed request shows an inline error Alert above the field instead, such as 'Could not subscribe. Try again.'\n timer.current = setTimeout(() => {\n setSending(false);\n // Both get an email, so the same line is true for both, and the form never tells who is subscribed.\n setDone(true);\n }, 1200);\n }\n\n return (\n // The end of a post: the section says what comes and how often, then asks for one address.\n <Center width=\"form\">\n <Surface padding=\"small\">\n <Stack gap=\"large\">\n <Stack gap=\"small\">\n <Heading level={2} size=\"h6\">Get the Acme newsletter</Heading>\n <Paragraph tone=\"secondary\" size=\"body2\" measure=\"none\">One email a month with what shipped. Leave any time from the link in each email.</Paragraph>\n </Stack>\n {done ? (\n <Heading ref={doneLine} tabIndex={-1} level={3} size=\"subtitle1\">Check your email to confirm.</Heading>\n ) : (\n <Form aria-label=\"Get the Acme newsletter\" onSubmit={handleSubmit}>\n <TextField\n id=\"newsletter-signup-section-email\"\n label=\"Email address\"\n type=\"email\"\n autoComplete=\"email\"\n value={email}\n readOnly={sending}\n error={Boolean(error)}\n errorText={error}\n onChange={(e) => { setEmail(e.target.value); setError(''); }}\n />\n <Stack align=\"start\">\n <Button size=\"medium\" type=\"secondary\" state=\"enabled\" label=\"Subscribe\" htmlType=\"submit\" loading={sending} />\n </Stack>\n </Form>\n )}\n </Stack>\n </Surface>\n </Center>\n );\n}\n",
|
|
4873
|
+
"uses": [
|
|
4874
|
+
"Button",
|
|
4875
|
+
"Center",
|
|
4876
|
+
"Form",
|
|
4877
|
+
"Heading",
|
|
4878
|
+
"Paragraph",
|
|
4879
|
+
"Stack",
|
|
4880
|
+
"Surface",
|
|
4881
|
+
"TextField"
|
|
4882
|
+
]
|
|
4883
|
+
}
|
|
4884
|
+
]
|
|
4885
|
+
},
|
|
4725
4886
|
{
|
|
4726
4887
|
"id": "not-found-page",
|
|
4727
4888
|
"title": "Page not found",
|
|
@@ -4831,17 +4992,19 @@
|
|
|
4831
4992
|
"level": "rule",
|
|
4832
4993
|
"area": "dashboard",
|
|
4833
4994
|
"situation": "A page shows counts, money, sizes, shares or changes.",
|
|
4834
|
-
"answer": "Use the helpers in `formatNumber` (`formatCount`, `formatMoney`, `formatPercent`, `formatBytes`, `formatDuration`), `StatTile` and `Progress`. A count is whole and grouped: '1,240'. In a tile, a count or an amount from 10,000 up shows its short form: '12.4K', '$12.4K'. A table shows the exact number, right-aligned. On a chart's axis, a number from 10,000 up shows its short form too: '12.4K'. The chart's readout and its table show the exact number. Money has its symbol and
|
|
4995
|
+
"answer": "Use the helpers in `formatNumber` (`formatCount`, `formatMoney`, `formatPercent`, `formatBytes`, `formatDuration`), `StatTile` and `Progress`. A count is whole and grouped: '1,240'. In a tile, a count or an amount from 10,000 up shows its short form: '12.4K', '$12.4K'. A table shows the exact number, right-aligned. On a chart's axis, a number from 10,000 up shows its short form too: '12.4K'. The chart's readout and its table show the exact number. Money has its symbol and its currency's decimals: '$1,240.00', '¥1,240', 'KWD 1,240.000'. A cost under the smallest unit reads '< $0.01'. A share is a whole percent, and a small one reads '< 1%'. A size is base 1024: '52 MB', '1.2 GB'. A time reads '340 ms', '1.2 s', '2 h 24 min'. The unit is in the label or after the number in words: 'Responses', '7 of 8 seats', '340 responses, no limit'. A bare number is never shown, and a unit is never only in a tooltip. A change says its direction, its size and what it compares with: 'Up 12% from last week'. It reads 'New this week' when there was nothing before. A change in a percent is in points: 'Up 3 pts from last week'. A refund in a list of charges has a minus: '-$12.00'. In a sentence, say the word: 'Refunded $12.00'. A change has no color, because more is not good or bad by itself. Unknown is never 0. `formatNumber` shows '–' for a value it cannot read. `StatTile` shows 'No data yet'. While a number loads, a `Skeleton` holds its place. On a failure, show the case 'Load failure'. A limit is a `Progress`, which says 'Limit reached' in words.",
|
|
4835
4996
|
"why": "One page that rounds a cost to four decimals and another that rounds it to two make the same bill look like two different amounts. A 0 shown while a number loads reads as a real answer, so the person believes something that is not true.",
|
|
4836
4997
|
"do": [
|
|
4837
4998
|
"Show a count whole and grouped: '1,240'. In a tile, show a count or an amount from 10,000 up in its short form: '12.4K', '$12.4K'.",
|
|
4838
4999
|
"Show the exact number in a table, right-aligned.",
|
|
4839
5000
|
"Show a number from 10,000 up on a chart's axis in its short form too: '12.4K'. Show the exact number in the chart's readout and its table.",
|
|
4840
|
-
"Show money with its symbol and
|
|
5001
|
+
"Show money with its symbol and its currency's decimals: '$1,240.00', '¥1,240', 'KWD 1,240.000'. Show a cost under the smallest unit as '< $0.01'.",
|
|
4841
5002
|
"Show a time as '340 ms', '1.2 s' or '2 h 24 min'. Show a share as a whole percent, and a small one as '< 1%'. Show a size in base 1024: '52 MB', '1.2 GB'.",
|
|
4842
5003
|
"Put the unit in the label or after the number in words: 'Responses', '7 of 8 seats', '340 responses, no limit'.",
|
|
4843
5004
|
"Match the noun to the count: '1 invoice', '290 invoices'.",
|
|
4844
5005
|
"Say a change's direction, size and comparison: 'Up 12% from last week'. Say 'New this week' when there was nothing before.",
|
|
5006
|
+
"Say a change in a percent in points: 'Up 3 pts from last week'. A screen reader hears 'percentage points'.",
|
|
5007
|
+
"Show a refund in a list of charges with a minus: '-$12.00'. In a sentence, say the word: 'Refunded $12.00'.",
|
|
4845
5008
|
"Show a `Skeleton` while a number loads, 'No data yet' when there is none, and the case 'Load failure' when it could not load.",
|
|
4846
5009
|
"Use the helpers in `formatNumber` (`formatCount`, `formatMoney`, `formatPercent`, `formatBytes`, `formatDuration`), `StatTile` and `Progress`. Do not format a number by hand."
|
|
4847
5010
|
],
|
|
@@ -4849,6 +5012,8 @@
|
|
|
4849
5012
|
"Do not show 0 for a number that is loading, missing or failed.",
|
|
4850
5013
|
"Do not show a bare number, or a unit only in a tooltip.",
|
|
4851
5014
|
"Do not round a cost to four decimals in one place and two in another.",
|
|
5015
|
+
"Do not give every currency two decimals. Yen has none: '¥1,240', not '¥1,240.00'.",
|
|
5016
|
+
"Do not say a change in a percent as a percent ('Up 25%' for 12% against 9.6%).",
|
|
4852
5017
|
"Do not color a change green or red. More is not good or bad by itself.",
|
|
4853
5018
|
"Do not show the compact form ('12.4K') in a table, or give a screen reader only the compact form.",
|
|
4854
5019
|
"Do not show only the short form in a chart. Its readout and table are exact.",
|
|
@@ -4981,6 +5146,8 @@
|
|
|
4981
5146
|
"Keep the labels the same as the headings, in the same case.",
|
|
4982
5147
|
"Name the nav 'On this page', which is the default, or pass an `aria-label` that fits the page.",
|
|
4983
5148
|
"Let a click scroll the heading to just under the header and keep its item current until the scroll ends. With reduced motion it jumps.",
|
|
5149
|
+
"Pass `history=\"replace\"` when Back should leave the page, such as a page that closes by going back. Keep the default when a person should be able to go back to where they were reading.",
|
|
5150
|
+
"Pass `keepInView` when images or other content above a section can load late and push it down.",
|
|
4984
5151
|
"Keep the aside to the list. A phone does not show it, so the page must read in order without it. The sections are not places: on a phone the person scrolls to them."
|
|
4985
5152
|
],
|
|
4986
5153
|
"dont": [
|
|
@@ -5533,7 +5700,7 @@
|
|
|
5533
5700
|
"do": [
|
|
5534
5701
|
"Use `AvatarStack` for four or more people. Past `max` its last circle counts the rest, such as '+3'.",
|
|
5535
5702
|
"Make the stack one button with `onClick`, and name it for what it opens: 'Show the 6 people in this thread'.",
|
|
5536
|
-
"Open a `<Popover returnFocus>` from the stack with a `List` of every name and role, such as 'Ben Carter, Admin'. Escape or a click outside closes it, and Escape puts focus back on the stack.",
|
|
5703
|
+
"Open a `<Popover returnFocus aria-label=\"People in this thread\">` from the stack with a `List` of every name and role, such as 'Ben Carter, Admin'. Escape or a click outside closes it, and Escape puts focus back on the stack.",
|
|
5537
5704
|
"Show one to three people as faces and their names: 'Dana Lee, Ben Carter and Omar Reyes'. Make each face `UserImage decorative`, because the names say who is there.",
|
|
5538
5705
|
"Keep the same order everywhere, the person who started the item first.",
|
|
5539
5706
|
"Use the person's name as `userHandle`, so a person with no picture shows their initial."
|
|
@@ -5550,7 +5717,7 @@
|
|
|
5550
5717
|
"id": "stack",
|
|
5551
5718
|
"title": "Overlapping faces that open a list",
|
|
5552
5719
|
"useWhen": "Four or more people are on a thread or a task, shown in its header.",
|
|
5553
|
-
"source": "'use client';\nimport { useState } from 'react';\nimport Heading from 'oneslash-design-system/components/heading';\nimport Paragraph from 'oneslash-design-system/components/paragraph';\nimport AvatarStack from 'oneslash-design-system/components/avatarStack';\nimport Popover from 'oneslash-design-system/components/popover';\nimport List from 'oneslash-design-system/components/list';\nimport { Cluster, Stack } from 'oneslash-design-system/components/layout';\n\n// The person who started the thread comes first, here and everywhere these people are listed.\nconst people = [\n { name: 'Ben Carter', role: 'Admin' },\n { name: 'Dana Lee', role: 'Member' },\n { name: 'Omar Reyes', role: 'Member' },\n { name: 'Mia Park', role: 'Member' },\n { name: 'Leo Grant', role: 'Guest' },\n { name: 'Ana Silva', role: 'Guest' },\n];\n\nexport default function PeopleRowStack() {\n // The open list is anchored on the stack's button, and focus goes back to it on close.\n const [anchor, setAnchor] = useState<HTMLElement | null>(null);\n return (\n <Stack gap=\"large\">\n <Cluster justify=\"between\">\n <Stack gap=\"small\">\n <Heading level={1} size=\"h5\">Launch checklist</Heading>\n <Paragraph tone=\"secondary\" size=\"body2\" measure=\"none\">Started by Ben Carter on Nov 12, 2026</Paragraph>\n </Stack>\n <AvatarStack\n people={people}\n aria-label={`Show the ${people.length} people in this thread`}\n aria-haspopup=\"dialog\"\n aria-expanded={anchor !== null}\n onClick={(event) => setAnchor(anchor ? null : event.currentTarget)}\n />\n </Cluster>\n <Popover id=\"people-row-people\" open={anchor !== null} anchorEl={anchor} onClose={() => setAnchor(null)} returnFocus>\n <List items={people.map((p) => `${p.name}, ${p.role}`)} />\n </Popover>\n </Stack>\n );\n}\n",
|
|
5720
|
+
"source": "'use client';\nimport { useState } from 'react';\nimport Heading from 'oneslash-design-system/components/heading';\nimport Paragraph from 'oneslash-design-system/components/paragraph';\nimport AvatarStack from 'oneslash-design-system/components/avatarStack';\nimport Popover from 'oneslash-design-system/components/popover';\nimport List from 'oneslash-design-system/components/list';\nimport { Cluster, Stack } from 'oneslash-design-system/components/layout';\n\n// The person who started the thread comes first, here and everywhere these people are listed.\nconst people = [\n { name: 'Ben Carter', role: 'Admin' },\n { name: 'Dana Lee', role: 'Member' },\n { name: 'Omar Reyes', role: 'Member' },\n { name: 'Mia Park', role: 'Member' },\n { name: 'Leo Grant', role: 'Guest' },\n { name: 'Ana Silva', role: 'Guest' },\n];\n\nexport default function PeopleRowStack() {\n // The open list is anchored on the stack's button, and focus goes back to it on close.\n const [anchor, setAnchor] = useState<HTMLElement | null>(null);\n return (\n <Stack gap=\"large\">\n <Cluster justify=\"between\">\n <Stack gap=\"small\">\n <Heading level={1} size=\"h5\">Launch checklist</Heading>\n <Paragraph tone=\"secondary\" size=\"body2\" measure=\"none\">Started by Ben Carter on Nov 12, 2026</Paragraph>\n </Stack>\n <AvatarStack\n people={people}\n aria-label={`Show the ${people.length} people in this thread`}\n aria-haspopup=\"dialog\"\n aria-expanded={anchor !== null}\n onClick={(event) => setAnchor(anchor ? null : event.currentTarget)}\n />\n </Cluster>\n <Popover id=\"people-row-people\" open={anchor !== null} anchorEl={anchor} onClose={() => setAnchor(null)} returnFocus aria-label=\"People in this thread\">\n <List items={people.map((p) => `${p.name}, ${p.role}`)} />\n </Popover>\n </Stack>\n );\n}\n",
|
|
5554
5721
|
"uses": [
|
|
5555
5722
|
"AvatarStack",
|
|
5556
5723
|
"Cluster",
|
|
@@ -5684,6 +5851,52 @@
|
|
|
5684
5851
|
}
|
|
5685
5852
|
]
|
|
5686
5853
|
},
|
|
5854
|
+
{
|
|
5855
|
+
"id": "plan-comparison",
|
|
5856
|
+
"title": "Plan comparison",
|
|
5857
|
+
"kind": "design",
|
|
5858
|
+
"level": "organism",
|
|
5859
|
+
"area": "marketing",
|
|
5860
|
+
"situation": "A visitor to the public site wants to see every limit of every plan side by side before signing up.",
|
|
5861
|
+
"do": [
|
|
5862
|
+
"Follow the rule 'A number shows its unit and never shows 0 for unknown'.",
|
|
5863
|
+
"Show the same plans as the case 'Plan picker', word for word: the names, the prices and what each includes.",
|
|
5864
|
+
"Open the section with `SectionIntro` 'Compare plans', under the plan cards of the case 'Pricing section'.",
|
|
5865
|
+
"Put the table in `TableContainer aria-label=\"Compare plans\" minWidth=\"40rem\"`. It is a named region that scrolls sideways on a phone, as in the case 'Data table page', so the page never does.",
|
|
5866
|
+
"Put the plan names in the header row, after 'Feature', with one `TableHeaderCell` for each plan.",
|
|
5867
|
+
"Put the features in the first column, each in `TableCell rowHeader`, so a screen reader says the feature with each cell: Price, Members, AI agent responses, Storage, Export to PDF and Priority support.",
|
|
5868
|
+
"Write each cell in the plan's own words, such as 'Unlimited members'. Say what a plan has as 'Included' and what is missing as 'Not included'.",
|
|
5869
|
+
"Leave Buttons out of the table. The plan cards above it hold the one action for each plan, as the rule 'A marketing page asks for one main action, in the same words everywhere' says."
|
|
5870
|
+
],
|
|
5871
|
+
"dont": [
|
|
5872
|
+
"Do not show a check mark or a cross with no words.",
|
|
5873
|
+
"Do not build the table from a grid of boxes. A screen reader cannot read it as a table.",
|
|
5874
|
+
"Do not hide the header row on a phone. Let the table scroll sideways in its region.",
|
|
5875
|
+
"Do not put a Button in every column.",
|
|
5876
|
+
"Do not change a price or a limit here without changing it in the cases 'Plan picker' and 'Pricing section' too.",
|
|
5877
|
+
"Do not dim the other columns with tabs. Every plan stays in view."
|
|
5878
|
+
],
|
|
5879
|
+
"native": "On Apple an app has no pricing page. The plans are in the app as a `List` with the system purchase sheet, as the case 'Plan picker' says. On iPad or Mac, a `Table` with the plans as columns works too.",
|
|
5880
|
+
"options": [
|
|
5881
|
+
{
|
|
5882
|
+
"id": "table",
|
|
5883
|
+
"title": "Table under the plan cards",
|
|
5884
|
+
"useWhen": "A pricing page shows every limit of every plan side by side, under the plan cards.",
|
|
5885
|
+
"source": "'use client';\nimport PageShell from 'oneslash-design-system/components/pageShell';\nimport SectionIntro from 'oneslash-design-system/components/sectionIntro';\nimport TableContainer from 'oneslash-design-system/components/tableContainer';\nimport TableHeader from 'oneslash-design-system/components/tableHeader';\nimport TableHeaderCell from 'oneslash-design-system/components/tableHeaderCell';\nimport TableRow from 'oneslash-design-system/components/tableRow';\nimport TableCell from 'oneslash-design-system/components/tableCell';\nimport { formatMoney } from 'oneslash-design-system/components/formatNumber';\nimport { PageSection } from 'oneslash-design-system/components/layout';\n\ntype PlanId = 'free' | 'pro' | 'business';\n\n// The same plans as the cases 'Plan picker' and 'Pricing section': names, prices and what each includes. A real site reads them from one place.\nconst plans: { id: PlanId; name: string; price: string; includes: string[] }[] = [\n { id: 'free', name: 'Free', price: `${formatMoney(0)} per month`, includes: ['3 members', '50 AI agent responses a month', '1 GB of storage'] },\n { id: 'pro', name: 'Pro', price: `${formatMoney(8)} per member per month`, includes: ['Unlimited members', '1,000 AI agent responses a month', '50 GB of storage', 'Export to PDF'] },\n { id: 'business', name: 'Business', price: `${formatMoney(16)} per member per month`, includes: ['Unlimited members', '10,000 AI agent responses a month', '500 GB of storage', 'Export to PDF', 'Priority support'] },\n];\n\n// One row per limit. A cell is the plan's own words for it, 'Included' when the plan has the feature, or 'Not included'.\nconst rows: { feature: string; cells: Record<PlanId, string> }[] = [\n { feature: 'Price', cells: { free: `${formatMoney(0)} per month`, pro: `${formatMoney(8)} per member per month`, business: `${formatMoney(16)} per member per month` } },\n { feature: 'Members', cells: { free: '3 members', pro: 'Unlimited members', business: 'Unlimited members' } },\n { feature: 'AI agent responses', cells: { free: '50 AI agent responses a month', pro: '1,000 AI agent responses a month', business: '10,000 AI agent responses a month' } },\n { feature: 'Storage', cells: { free: '1 GB of storage', pro: '50 GB of storage', business: '500 GB of storage' } },\n { feature: 'Export to PDF', cells: { free: 'Not included', pro: 'Included', business: 'Included' } },\n { feature: 'Priority support', cells: { free: 'Not included', pro: 'Not included', business: 'Included' } },\n];\n\nexport default function PlanComparisonTable() {\n return (\n <PageShell>\n <PageSection gap=\"xxlarge\">\n <SectionIntro name=\"Compare plans\" />\n {/* A named region that scrolls sideways on a phone, so the page never does. The header row stays at every width. */}\n {/* No Buttons here: the plan cards above the table hold the one action for each plan. */}\n <TableContainer aria-label=\"Compare plans\" minWidth=\"40rem\">\n <TableHeader>\n <TableRow>\n <TableHeaderCell>Feature</TableHeaderCell>\n {plans.map((p) => (\n <TableHeaderCell key={p.id}>{p.name}</TableHeaderCell>\n ))}\n </TableRow>\n </TableHeader>\n {rows.map((row) => (\n <TableRow key={row.feature}>\n {/* The feature names its row, so a screen reader says it with each cell. */}\n <TableCell rowHeader>{row.feature}</TableCell>\n {plans.map((p) => (\n <TableCell key={p.id}>{row.cells[p.id]}</TableCell>\n ))}\n </TableRow>\n ))}\n </TableContainer>\n </PageSection>\n </PageShell>\n );\n}\n",
|
|
5886
|
+
"uses": [
|
|
5887
|
+
"PageSection",
|
|
5888
|
+
"PageShell",
|
|
5889
|
+
"SectionIntro",
|
|
5890
|
+
"TableCell",
|
|
5891
|
+
"TableContainer",
|
|
5892
|
+
"TableHeader",
|
|
5893
|
+
"TableHeaderCell",
|
|
5894
|
+
"TableRow",
|
|
5895
|
+
"formatMoney"
|
|
5896
|
+
]
|
|
5897
|
+
}
|
|
5898
|
+
]
|
|
5899
|
+
},
|
|
5687
5900
|
{
|
|
5688
5901
|
"id": "plan-picker",
|
|
5689
5902
|
"title": "Plan picker",
|
|
@@ -5707,7 +5920,8 @@
|
|
|
5707
5920
|
"Do not run the limits together in one line with dots between them. Use a `List`, one limit per item.",
|
|
5708
5921
|
"Do not add a monthly and yearly switch when no plan bills yearly.",
|
|
5709
5922
|
"Do not change a Button label to show it is busy, such as to 'Checking...'.",
|
|
5710
|
-
"Do not charge or change the plan from this page. The confirm does that."
|
|
5923
|
+
"Do not charge or change the plan from this page. The confirm does that.",
|
|
5924
|
+
"Do not change a price or a limit here without changing it in the cases 'Pricing section' and 'Plan comparison' too."
|
|
5711
5925
|
],
|
|
5712
5926
|
"native": "On Apple use a `List` of plans with the system purchase sheet, and mark the current plan with a checkmark and the words 'Current plan'. Never build a card by hand.",
|
|
5713
5927
|
"options": [
|
|
@@ -5862,7 +6076,7 @@
|
|
|
5862
6076
|
"Do not name a Button 'Get Started', 'Choose' or 'Select'. Name the plan it signs up for.",
|
|
5863
6077
|
"Do not open the sign-up page in a new tab.",
|
|
5864
6078
|
"Do not give two plans a primary Button.",
|
|
5865
|
-
"Do not change a price or a limit here without changing it in the
|
|
6079
|
+
"Do not change a price or a limit here without changing it in the cases 'Plan picker' and 'Plan comparison' too. A visitor sees one set of plans.",
|
|
5866
6080
|
"Do not make a card clickable as a whole. Its Button is the one control."
|
|
5867
6081
|
],
|
|
5868
6082
|
"native": "On Apple an app has no pricing section. The plans are in the app as a `List` with the system purchase sheet, as the case 'Plan picker' says.",
|
|
@@ -6835,7 +7049,8 @@
|
|
|
6835
7049
|
"Give each column a short `title`, such as 'Product', 'Company' and 'Legal'. A phone shows two columns across and a wide window up to four.",
|
|
6836
7050
|
"Put the legal line last, in `legal`: the year and the name, and the license if there is one, such as '© 2026 Acme. Released under the MIT License.'",
|
|
6837
7051
|
"Mark a link to another site with `external`. It opens in a new tab and the icon and the hidden words '(opens in a new tab)' say so.",
|
|
6838
|
-
"Keep the footer to links and the legal line. It holds every page the header leaves out, in plain words."
|
|
7052
|
+
"Keep the footer to links and the legal line. It holds every page the header leaves out, in plain words.",
|
|
7053
|
+
"Put a newsletter sign-up above the footer, as the case 'Newsletter sign-up' says. The footer holds only its link."
|
|
6839
7054
|
],
|
|
6840
7055
|
"dont": [
|
|
6841
7056
|
"Do not put a sales pitch, a heading or a Button in the footer. Use a call to action band above it.",
|
|
@@ -6863,7 +7078,7 @@
|
|
|
6863
7078
|
"id": "columns",
|
|
6864
7079
|
"title": "Links in groups",
|
|
6865
7080
|
"useWhen": "The site has many links that fall into groups, such as product, company and legal.",
|
|
6866
|
-
"source": "'use client';\nimport SiteFooter from 'oneslash-design-system/components/siteFooter';\nimport Heading from 'oneslash-design-system/components/heading';\nimport Paragraph from 'oneslash-design-system/components/paragraph';\nimport { Center, Stack } from 'oneslash-design-system/components/layout';\n\nconst columns = [\n {\n title: 'Product',\n links: [\n { label: 'Features', href: '#features' },\n { label: 'Pricing', href: '#pricing' },\n { label: 'Changelog', href: '#changelog' },\n { label: 'Docs', href: '#docs' },\n ],\n },\n {\n title: 'Company',\n links: [\n { label: 'About', href: '#about' },\n { label: 'Blog', href: '#blog' },\n { label: 'Contact', href: '#contact' },\n ],\n },\n {\n title: 'Follow',\n links: [\n { label: 'GitHub', href: 'https://github.com/acme/acme', external: true },\n { label: 'Newsletter', href: '
|
|
7081
|
+
"source": "'use client';\nimport SiteFooter from 'oneslash-design-system/components/siteFooter';\nimport Heading from 'oneslash-design-system/components/heading';\nimport Paragraph from 'oneslash-design-system/components/paragraph';\nimport { Center, Stack } from 'oneslash-design-system/components/layout';\n\nconst columns = [\n {\n title: 'Product',\n links: [\n { label: 'Features', href: '#features' },\n { label: 'Pricing', href: '#pricing' },\n { label: 'Changelog', href: '#changelog' },\n { label: 'Docs', href: '#docs' },\n ],\n },\n {\n title: 'Company',\n links: [\n { label: 'About', href: '#about' },\n { label: 'Blog', href: '#blog' },\n { label: 'Contact', href: '#contact' },\n ],\n },\n {\n title: 'Follow',\n links: [\n { label: 'GitHub', href: 'https://github.com/acme/acme', external: true },\n // The page with the sign-up form of the case 'Newsletter sign-up'. The footer holds the link, not the form.\n { label: 'Newsletter', href: '#newsletter' },\n ],\n },\n {\n title: 'Legal',\n links: [\n { label: 'Terms', href: '#terms' },\n { label: 'Privacy', href: '#privacy' },\n ],\n },\n];\n\nexport default function SiteFooterColumns() {\n return (\n <>\n {/* A real page puts its content in PageShell, then SiteFooter. Center keeps the footer in view here. */}\n <Center width=\"page\">\n <Stack gap=\"large\">\n <Heading level={1} size=\"h5\">About Acme</Heading>\n <Paragraph tone=\"secondary\" measure=\"none\">Acme helps small teams share files and decide together.</Paragraph>\n </Stack>\n </Center>\n {/* Groups of links, two across on a phone and four across from md. The legal line is last. */}\n <SiteFooter\n brand={{ href: '#top', name: 'Acme' }}\n columns={columns}\n legal=\"© 2026 Acme. All rights reserved.\"\n />\n </>\n );\n}\n",
|
|
6867
7082
|
"uses": [
|
|
6868
7083
|
"Center",
|
|
6869
7084
|
"Heading",
|
|
@@ -7044,10 +7259,12 @@
|
|
|
7044
7259
|
"do": [
|
|
7045
7260
|
"Follow the rule 'A number shows its unit and never shows 0 for unknown'. Use `StatTile`, which does.",
|
|
7046
7261
|
"Put the tiles in `<Grid compact columns={4}>`: two across on a phone, up to four from md up.",
|
|
7262
|
+
"Give the row `from=\"lg\"` inside an `AppShell`. From md the sidebar takes the room four tiles need.",
|
|
7047
7263
|
"Use four tiles at most. A fifth number goes in a table.",
|
|
7048
7264
|
"Make each tile count one thing, with its unit in the label or the `unit` prop: 'New comments', 'Responses'.",
|
|
7049
7265
|
"Count every tile over the same range, and say the range in the heading above the row: 'This week'.",
|
|
7050
7266
|
"Pass `previous` and `period` to get the change line, such as 'Up 12% from last week'. Leave `previous` out when there is nothing to compare with.",
|
|
7267
|
+
"Give a percent tile `previous` as a fraction too. Its change reads in points.",
|
|
7051
7268
|
"Pass `loading` while the numbers load, so a `Skeleton` holds each place. Pass `value={null}` when there is no data: the tile says 'No data yet'.",
|
|
7052
7269
|
"Pass `format` for money, a percent, a size or a time, such as `format=\"money\"`. Do not format a number by hand.",
|
|
7053
7270
|
"Give the one number that matters most `size=\"large\"` and a row of its own, with the others under it."
|
|
@@ -7065,7 +7282,7 @@
|
|
|
7065
7282
|
"id": "tiles",
|
|
7066
7283
|
"title": "Tiles of equal weight",
|
|
7067
7284
|
"useWhen": "Two to four numbers matter about the same, over one range.",
|
|
7068
|
-
"source": "'use client';\nimport { useEffect, useRef, useState } from 'react';\nimport Heading from 'oneslash-design-system/components/heading';\nimport StatTile from 'oneslash-design-system/components/statTile';\nimport Button from 'oneslash-design-system/components/button';\nimport { Center, Cluster, Grid, Stack } from 'oneslash-design-system/components/layout';\n\nexport default function StatRowTiles() {\n const [loading, setLoading] = useState(false);\n const timer = useRef<ReturnType<typeof setTimeout>>();\n\n // Stops the request if the example goes away before it ends.\n useEffect(() => () => clearTimeout(timer.current), []);\n\n function reload() {\n if (loading) return;\n setLoading(true);\n // Stands in for the request to the server.\n timer.current = setTimeout(() => setLoading(false), 1200);\n }\n\n return (\n <Center width=\"page\">\n <Stack gap=\"large\">\n <Cluster justify=\"between\">\n <Heading level={2} size=\"h6\">This week</Heading>\n <Button size=\"small\" type=\"tertiary\" state=\"enabled\" label=\"Reload\" decoIcon=\"RefreshCw\" onClickButton={reload} />\n </Cluster>\n {/* Four tiles at most. Two across on a phone, four from md up. Each counts one thing over the same range. */}\n <Grid compact columns={4}>\n <StatTile label=\"New comments\" value={1240} previous={1106} loading={loading} />\n <StatTile label=\"
|
|
7285
|
+
"source": "'use client';\nimport { useEffect, useRef, useState } from 'react';\nimport Heading from 'oneslash-design-system/components/heading';\nimport StatTile from 'oneslash-design-system/components/statTile';\nimport Button from 'oneslash-design-system/components/button';\nimport { Center, Cluster, Grid, Stack } from 'oneslash-design-system/components/layout';\n\nexport default function StatRowTiles() {\n const [loading, setLoading] = useState(false);\n const timer = useRef<ReturnType<typeof setTimeout>>();\n\n // Stops the request if the example goes away before it ends.\n useEffect(() => () => clearTimeout(timer.current), []);\n\n function reload() {\n if (loading) return;\n setLoading(true);\n // Stands in for the request to the server.\n timer.current = setTimeout(() => setLoading(false), 1200);\n }\n\n return (\n <Center width=\"page\">\n <Stack gap=\"large\">\n <Cluster justify=\"between\">\n <Heading level={2} size=\"h6\">This week</Heading>\n <Button size=\"small\" type=\"tertiary\" state=\"enabled\" label=\"Reload\" decoIcon=\"RefreshCw\" onClickButton={reload} />\n </Cluster>\n {/* Four tiles at most. Two across on a phone, four from md up. Each counts one thing over the same range. */}\n <Grid compact columns={4}>\n <StatTile label=\"New comments\" value={1240} previous={1106} loading={loading} />\n {/* A percent is a fraction, and so is its previous value. The change reads in points: 'Up 3 pts'. */}\n <StatTile label=\"Share marked done\" value={0.25} format=\"percent\" previous={0.22} loading={loading} />\n <StatTile label=\"People engaged\" value={18} previous={18} loading={loading} />\n <StatTile label=\"Average reply time\" value={8_640_000} format=\"duration\" previous={9_200_000} loading={loading} />\n </Grid>\n </Stack>\n </Center>\n );\n}\n",
|
|
7069
7286
|
"uses": [
|
|
7070
7287
|
"Button",
|
|
7071
7288
|
"Center",
|
|
@@ -7321,7 +7538,7 @@
|
|
|
7321
7538
|
"id": "people-change-status",
|
|
7322
7539
|
"title": "People change the status",
|
|
7323
7540
|
"useWhen": "People move the task through its states.",
|
|
7324
|
-
"source": "'use client';\nimport { useEffect, useRef, useState } from 'react';\nimport AppShell from 'oneslash-design-system/components/appShell';\nimport SidePane, { type SidePaneHandle } from 'oneslash-design-system/components/sidePane';\nimport Navigation from 'oneslash-design-system/components/navigation';\nimport TitleBar from 'oneslash-design-system/components/titleBar';\nimport Tag from 'oneslash-design-system/components/tag';\nimport AvatarStack from 'oneslash-design-system/components/avatarStack';\nimport Button from 'oneslash-design-system/components/button';\nimport IconButton from 'oneslash-design-system/components/iconButton';\nimport Tooltip from 'oneslash-design-system/components/tooltip';\nimport Popover from 'oneslash-design-system/components/popover';\nimport Menu from 'oneslash-design-system/components/menu';\nimport MenuItem from 'oneslash-design-system/components/menuItem';\nimport Line from 'oneslash-design-system/components/line';\nimport List from 'oneslash-design-system/components/list';\nimport Modal from 'oneslash-design-system/components/modal';\nimport Timeline from 'oneslash-design-system/components/timeline';\nimport Paragraph from 'oneslash-design-system/components/paragraph';\nimport Toaster, { toast, dismissToast } from 'oneslash-design-system/components/toaster';\nimport { Stack } from 'oneslash-design-system/components/layout';\n\ntype PaneId = 'plan' | 'history';\ntype Focusable = HTMLButtonElement | HTMLAnchorElement | null;\n\nconst task = 'Launch checklist';\n\n// A Button and a menu item say the state in Title Case. The Tag says it in sentence case.\nconst statuses = [\n { id: 'to-do', label: 'To Do', tag: 'To do' },\n { id: 'in-progress', label: 'In Progress', tag: 'In progress' },\n { id: 'in-review', label: 'In Review', tag: 'In review' },\n { id: 'done', label: 'Done', tag: 'Done' },\n];\n\n// The person who started the task comes first, here and in every list of these people.\nconst people = [\n { name: 'Ben Carter', role: 'Admin' },\n { name: 'Dana Lee', role: 'Member' },\n { name: 'Omar Reyes', role: 'Member' },\n { name: 'Mia Park', role: 'Member' },\n { name: 'Leo Grant', role: 'Guest' },\n { name: 'Ana Silva', role: 'Guest' },\n];\n\nconst history = [\n { id: 'h3', title: 'Dana Lee approved the plan', when: 'Nov 16, 2026, 2:52 PM', dateTime: '2026-11-16T14:52', actor: { name: 'Dana Lee' } },\n { id: 'h2', title: 'Acme Agent wrote the plan', when: 'Nov 16, 2026, 2:40 PM', dateTime: '2026-11-16T14:40', actor: { name: 'Acme Agent', agent: true } },\n { id: 'h1', title: 'Ben Carter created the task', when: 'Nov 15, 2026, 4:02 PM', dateTime: '2026-11-15T16:02', actor: { name: 'Ben Carter' } },\n];\n\n// The places. A real app lets each link go to its page.\nconst sidebar = (\n <Navigation aria-label=\"Main\">\n <MenuItem\n size=\"small\"\n label=\"Tasks\"\n iconName=\"ListChecks\"\n href=\"/tasks\"\n isSelected\n aria-current=\"page\"\n onClick={(event: { preventDefault: () => void }) => event.preventDefault()}\n />\n </Navigation>\n);\n\nexport default function TaskHeaderPeopleChangeStatus() {\n const [navOpen, setNavOpen] = useState(false);\n const [status, setStatus] = useState('in-progress');\n const [statusAnchor, setStatusAnchor] = useState<HTMLElement | null>(null);\n const [peopleAnchor, setPeopleAnchor] = useState<HTMLElement | null>(null);\n const [moreAnchor, setMoreAnchor] = useState<HTMLElement | null>(null);\n const [moreOpen, setMoreOpen] = useState(false);\n // One pane at a time. Opening another replaces it.\n const [pane, setPane] = useState<PaneId | null>(null);\n const [confirming, setConfirming] = useState(false);\n const [deleting, setDeleting] = useState(false);\n const paneRef = useRef<SidePaneHandle>(null);\n const moreButton = useRef<Focusable>(null);\n const timer = useRef<ReturnType<typeof setTimeout>>();\n const toastIds = useRef<string[]>([]);\n // Where focus goes after the next render, once the element it goes to is on screen.\n const focusNext = useRef<() => void>();\n\n // On unmount it stops the request and closes every toast it opened.\n useEffect(() => () => {\n clearTimeout(timer.current);\n toastIds.current.forEach((id) => dismissToast(id));\n toastIds.current = [];\n }, []);\n\n useEffect(() => {\n const move = focusNext.current;\n focusNext.current = undefined;\n move?.();\n });\n\n const current = statuses.find((s) => s.id === status) ?? statuses[0];\n\n // The new state shows in the Tag and on the Button at once. The Popover gives focus back to the Button.\n function chooseStatus(id: string) {\n setStatusAnchor(null);\n // A real app sends the new state to the server here.\n setStatus(id);\n }\n\n // Pressed again while its pane is open, the button brings the pane forward instead of opening a second one.\n function togglePane(id: PaneId) {\n if (pane === id) paneRef.current?.focus();\n else setPane(id);\n }\n\n function openMore(el: HTMLElement) {\n setMoreAnchor(el);\n setMoreOpen((o) => !o);\n }\n\n // Every item closes the menu. The Popover gives focus back to More.\n function choose(action: () => void) {\n setMoreOpen(false);\n action();\n }\n\n // The Modal opens while the menu fades, so it cannot take focus back from the menu item: 'Cancel' sends it to More.\n function keepTask() {\n if (deleting) return;\n setConfirming(false);\n focusNext.current = () => moreButton.current?.focus({ preventScroll: true });\n }\n\n function confirmDelete() {\n if (deleting) return;\n setDeleting(true);\n // Stands in for the request to the server. A real app then goes back to the task list.\n timer.current = setTimeout(() => {\n setDeleting(false);\n setConfirming(false);\n toastIds.current.push(toast({ type: 'success', message: `${task} deleted.` }));\n }, 1200);\n }\n\n const statusButton = (\n <Button\n size=\"small\"\n type=\"secondary\"\n state=\"enabled\"\n label={`Status: ${current.label}`}\n aria-haspopup=\"menu\"\n aria-expanded={statusAnchor !== null}\n onClickButton={(e: { currentTarget: HTMLElement }) => setStatusAnchor(statusAnchor ? null : e.currentTarget)}\n />\n );\n\n const paneButton = (id: PaneId) => (\n <Tooltip title={id === 'plan' ? 'Plan' : 'History'}>\n <IconButton\n color=\"iconOnly\"\n state={pane === id ? 'selected' : 'enabled'}\n size=\"medium\"\n iconName={id === 'plan' ? 'FileText' : 'History'}\n ariaLabel={id === 'plan' ? `Show the plan for ${task}` : `Show the history of ${task}`}\n aria-expanded={pane === id}\n onClick={() => togglePane(id)}\n />\n </Tooltip>\n );\n\n const more = (\n <Tooltip title=\"More\">\n <IconButton\n ref={moreButton}\n color=\"iconOnly\"\n state={moreOpen ? 'selected' : 'enabled'}\n size=\"medium\"\n iconName=\"Ellipsis\"\n ariaLabel={`More actions for ${task}`}\n aria-haspopup=\"menu\"\n aria-expanded={moreOpen}\n onClick={(e: { currentTarget: HTMLElement }) => openMore(e.currentTarget)}\n />\n </Tooltip>\n );\n\n return (\n <AppShell\n title=\"Tasks\"\n navOpen={navOpen}\n onNavOpenChange={setNavOpen}\n sidebar={sidebar}\n pane={\n pane && (\n <SidePane key={pane} ref={paneRef} title={pane === 'plan' ? 'Plan' : 'History'} onClose={() => setPane(null)}>\n {pane === 'plan' ? (\n <Stack gap=\"medium\">\n <Paragraph measure=\"none\">Ship the new home page on Nov 20, 2026. Omar Reyes writes the copy and Mia Park checks the screens.</Paragraph>\n <Paragraph tone=\"secondary\" size=\"body2\" measure=\"none\">Written by Acme Agent, Nov 16, 2026, 2:40 PM</Paragraph>\n </Stack>\n ) : (\n <Timeline id=\"task-header-history\" aria-label=\"History\" items={history} />\n )}\n </SidePane>\n )\n }\n >\n {/* A real app mounts one Toaster near its root. */}\n <Toaster />\n <Stack gap=\"large\">\n <TitleBar\n title={task}\n meta={\n <>\n <Tag variant=\"dot\" size=\"small\" label={current.tag} />\n <AvatarStack\n people={people}\n aria-label={`Show the ${people.length} people on ${task}`}\n aria-haspopup=\"dialog\"\n aria-expanded={peopleAnchor !== null}\n onClick={(event) => setPeopleAnchor(peopleAnchor ? null : event.currentTarget)}\n />\n Due Nov 20, 2026\n </>\n }\n // The status Button is too wide to sit beside the title on a phone, so below md the actions take their own line.\n actions={\n <>\n {statusButton}\n {paneButton('plan')}\n {paneButton('history')}\n {more}\n </>\n }\n actionsBelow\n />\n <Paragraph tone=\"secondary\" measure=\"none\">Acme Agent is updating the home page. Omar Reyes is writing the copy.</Paragraph>\n </Stack>\n <Popover id=\"task-header-status\" open={statusAnchor !== null} anchorEl={statusAnchor} onClose={() => setStatusAnchor(null)} returnFocus>\n <Menu navigable aria-label=\"Task status\" width={200}>\n {statuses.map((s) => (\n <MenuItem key={s.id} size=\"small\" label={s.label} isSelected={s.id === status} onClick={() => chooseStatus(s.id)} />\n ))}\n </Menu>\n </Popover>\n <Popover id=\"task-header-people\" open={peopleAnchor !== null} anchorEl={peopleAnchor} onClose={() => setPeopleAnchor(null)} returnFocus>\n <List items={people.map((p) => `${p.name}, ${p.role}`)} />\n </Popover>\n <Popover id=\"task-header-more\" open={moreOpen} anchorEl={moreAnchor} onClose={() => setMoreOpen(false)} returnFocus>\n <Menu navigable aria-label={`Actions for ${task}`} width={200}>\n {/* A real app opens the Rename Modal of the case 'Rename', and archives the task with a toast. */}\n <MenuItem size=\"small\" iconName=\"Pencil\" label=\"Rename\" onClick={() => choose(() => {})} />\n <MenuItem size=\"small\" iconName=\"Archive\" label=\"Archive\" onClick={() => choose(() => {})} />\n <Line />\n {/* Delete is last, and danger. */}\n <MenuItem size=\"small\" color=\"danger\" iconName=\"Trash2\" label=\"Delete Task\" onClick={() => choose(() => setConfirming(true))} />\n </Menu>\n </Popover>\n {/* The task is a page, not a row in a list, so the confirm is a small Modal, as the case 'Delete confirm' says. */}\n <Modal\n isOpen={confirming}\n size=\"small\"\n title=\"Delete Task\"\n onClose={keepTask}\n actions={\n <>\n <Button size=\"small\" type=\"tertiary\" state={deleting ? 'disabled' : 'enabled'} label=\"Cancel\" onClickButton={keepTask} />\n <Button size=\"small\" type=\"primary\" color=\"danger\" state=\"enabled\" label=\"Delete\" loading={deleting} onClickButton={confirmDelete} />\n </>\n }\n >\n <Paragraph measure=\"none\">This deletes '{task}', its plan and its history.</Paragraph>\n </Modal>\n </AppShell>\n );\n}\n",
|
|
7541
|
+
"source": "'use client';\nimport { useEffect, useRef, useState } from 'react';\nimport AppShell from 'oneslash-design-system/components/appShell';\nimport SidePane, { type SidePaneHandle } from 'oneslash-design-system/components/sidePane';\nimport Navigation from 'oneslash-design-system/components/navigation';\nimport TitleBar from 'oneslash-design-system/components/titleBar';\nimport Tag from 'oneslash-design-system/components/tag';\nimport AvatarStack from 'oneslash-design-system/components/avatarStack';\nimport Button from 'oneslash-design-system/components/button';\nimport IconButton from 'oneslash-design-system/components/iconButton';\nimport Tooltip from 'oneslash-design-system/components/tooltip';\nimport Popover from 'oneslash-design-system/components/popover';\nimport Menu from 'oneslash-design-system/components/menu';\nimport MenuItem from 'oneslash-design-system/components/menuItem';\nimport Line from 'oneslash-design-system/components/line';\nimport List from 'oneslash-design-system/components/list';\nimport Modal from 'oneslash-design-system/components/modal';\nimport Timeline from 'oneslash-design-system/components/timeline';\nimport Paragraph from 'oneslash-design-system/components/paragraph';\nimport Toaster, { toast, dismissToast } from 'oneslash-design-system/components/toaster';\nimport { Stack } from 'oneslash-design-system/components/layout';\n\ntype PaneId = 'plan' | 'history';\ntype Focusable = HTMLButtonElement | HTMLAnchorElement | null;\n\nconst task = 'Launch checklist';\n\n// A Button and a menu item say the state in Title Case. The Tag says it in sentence case.\nconst statuses = [\n { id: 'to-do', label: 'To Do', tag: 'To do' },\n { id: 'in-progress', label: 'In Progress', tag: 'In progress' },\n { id: 'in-review', label: 'In Review', tag: 'In review' },\n { id: 'done', label: 'Done', tag: 'Done' },\n];\n\n// The person who started the task comes first, here and in every list of these people.\nconst people = [\n { name: 'Ben Carter', role: 'Admin' },\n { name: 'Dana Lee', role: 'Member' },\n { name: 'Omar Reyes', role: 'Member' },\n { name: 'Mia Park', role: 'Member' },\n { name: 'Leo Grant', role: 'Guest' },\n { name: 'Ana Silva', role: 'Guest' },\n];\n\nconst history = [\n { id: 'h3', title: 'Dana Lee approved the plan', when: 'Nov 16, 2026, 2:52 PM', dateTime: '2026-11-16T14:52', actor: { name: 'Dana Lee' } },\n { id: 'h2', title: 'Acme Agent wrote the plan', when: 'Nov 16, 2026, 2:40 PM', dateTime: '2026-11-16T14:40', actor: { name: 'Acme Agent', agent: true } },\n { id: 'h1', title: 'Ben Carter created the task', when: 'Nov 15, 2026, 4:02 PM', dateTime: '2026-11-15T16:02', actor: { name: 'Ben Carter' } },\n];\n\n// The places. A real app lets each link go to its page.\nconst sidebar = (\n <Navigation aria-label=\"Main\">\n <MenuItem\n size=\"small\"\n label=\"Tasks\"\n iconName=\"ListChecks\"\n href=\"/tasks\"\n isSelected\n aria-current=\"page\"\n onClick={(event: { preventDefault: () => void }) => event.preventDefault()}\n />\n </Navigation>\n);\n\nexport default function TaskHeaderPeopleChangeStatus() {\n const [navOpen, setNavOpen] = useState(false);\n const [status, setStatus] = useState('in-progress');\n const [statusAnchor, setStatusAnchor] = useState<HTMLElement | null>(null);\n const [peopleAnchor, setPeopleAnchor] = useState<HTMLElement | null>(null);\n const [moreAnchor, setMoreAnchor] = useState<HTMLElement | null>(null);\n const [moreOpen, setMoreOpen] = useState(false);\n // One pane at a time. Opening another replaces it.\n const [pane, setPane] = useState<PaneId | null>(null);\n const [confirming, setConfirming] = useState(false);\n const [deleting, setDeleting] = useState(false);\n const paneRef = useRef<SidePaneHandle>(null);\n const moreButton = useRef<Focusable>(null);\n const timer = useRef<ReturnType<typeof setTimeout>>();\n const toastIds = useRef<string[]>([]);\n // Where focus goes after the next render, once the element it goes to is on screen.\n const focusNext = useRef<() => void>();\n\n // On unmount it stops the request and closes every toast it opened.\n useEffect(() => () => {\n clearTimeout(timer.current);\n toastIds.current.forEach((id) => dismissToast(id));\n toastIds.current = [];\n }, []);\n\n useEffect(() => {\n const move = focusNext.current;\n focusNext.current = undefined;\n move?.();\n });\n\n const current = statuses.find((s) => s.id === status) ?? statuses[0];\n\n // The new state shows in the Tag and on the Button at once. The Popover gives focus back to the Button.\n function chooseStatus(id: string) {\n setStatusAnchor(null);\n // A real app sends the new state to the server here.\n setStatus(id);\n }\n\n // Pressed again while its pane is open, the button brings the pane forward instead of opening a second one.\n function togglePane(id: PaneId) {\n if (pane === id) paneRef.current?.focus();\n else setPane(id);\n }\n\n function openMore(el: HTMLElement) {\n setMoreAnchor(el);\n setMoreOpen((o) => !o);\n }\n\n // Every item closes the menu. The Popover gives focus back to More.\n function choose(action: () => void) {\n setMoreOpen(false);\n action();\n }\n\n // The Modal opens while the menu fades, so it cannot take focus back from the menu item: 'Cancel' sends it to More.\n function keepTask() {\n if (deleting) return;\n setConfirming(false);\n focusNext.current = () => moreButton.current?.focus({ preventScroll: true });\n }\n\n function confirmDelete() {\n if (deleting) return;\n setDeleting(true);\n // Stands in for the request to the server. A real app then goes back to the task list.\n timer.current = setTimeout(() => {\n setDeleting(false);\n setConfirming(false);\n toastIds.current.push(toast({ type: 'success', message: `${task} deleted.` }));\n }, 1200);\n }\n\n const statusButton = (\n <Button\n size=\"small\"\n type=\"secondary\"\n state=\"enabled\"\n label={`Status: ${current.label}`}\n aria-haspopup=\"menu\"\n aria-expanded={statusAnchor !== null}\n onClickButton={(e: { currentTarget: HTMLElement }) => setStatusAnchor(statusAnchor ? null : e.currentTarget)}\n />\n );\n\n const paneButton = (id: PaneId) => (\n <Tooltip title={id === 'plan' ? 'Plan' : 'History'}>\n <IconButton\n color=\"iconOnly\"\n state={pane === id ? 'selected' : 'enabled'}\n size=\"medium\"\n iconName={id === 'plan' ? 'FileText' : 'History'}\n ariaLabel={id === 'plan' ? `Show the plan for ${task}` : `Show the history of ${task}`}\n aria-expanded={pane === id}\n onClick={() => togglePane(id)}\n />\n </Tooltip>\n );\n\n const more = (\n <Tooltip title=\"More\">\n <IconButton\n ref={moreButton}\n color=\"iconOnly\"\n state={moreOpen ? 'selected' : 'enabled'}\n size=\"medium\"\n iconName=\"Ellipsis\"\n ariaLabel={`More actions for ${task}`}\n aria-haspopup=\"menu\"\n aria-expanded={moreOpen}\n onClick={(e: { currentTarget: HTMLElement }) => openMore(e.currentTarget)}\n />\n </Tooltip>\n );\n\n return (\n <AppShell\n title=\"Tasks\"\n navOpen={navOpen}\n onNavOpenChange={setNavOpen}\n sidebar={sidebar}\n pane={\n pane && (\n <SidePane key={pane} ref={paneRef} title={pane === 'plan' ? 'Plan' : 'History'} onClose={() => setPane(null)}>\n {pane === 'plan' ? (\n <Stack gap=\"medium\">\n <Paragraph measure=\"none\">Ship the new home page on Nov 20, 2026. Omar Reyes writes the copy and Mia Park checks the screens.</Paragraph>\n <Paragraph tone=\"secondary\" size=\"body2\" measure=\"none\">Written by Acme Agent, Nov 16, 2026, 2:40 PM</Paragraph>\n </Stack>\n ) : (\n <Timeline id=\"task-header-history\" aria-label=\"History\" items={history} />\n )}\n </SidePane>\n )\n }\n >\n {/* A real app mounts one Toaster near its root. */}\n <Toaster />\n <Stack gap=\"large\">\n <TitleBar\n title={task}\n meta={\n <>\n <Tag variant=\"dot\" size=\"small\" label={current.tag} />\n <AvatarStack\n people={people}\n aria-label={`Show the ${people.length} people on ${task}`}\n aria-haspopup=\"dialog\"\n aria-expanded={peopleAnchor !== null}\n onClick={(event) => setPeopleAnchor(peopleAnchor ? null : event.currentTarget)}\n />\n Due Nov 20, 2026\n </>\n }\n // The status Button is too wide to sit beside the title on a phone, so below md the actions take their own line.\n actions={\n <>\n {statusButton}\n {paneButton('plan')}\n {paneButton('history')}\n {more}\n </>\n }\n actionsBelow\n />\n <Paragraph tone=\"secondary\" measure=\"none\">Acme Agent is updating the home page. Omar Reyes is writing the copy.</Paragraph>\n </Stack>\n <Popover id=\"task-header-status\" open={statusAnchor !== null} anchorEl={statusAnchor} onClose={() => setStatusAnchor(null)} returnFocus>\n <Menu navigable aria-label=\"Task status\" width={200}>\n {statuses.map((s) => (\n <MenuItem key={s.id} size=\"small\" label={s.label} isSelected={s.id === status} onClick={() => chooseStatus(s.id)} />\n ))}\n </Menu>\n </Popover>\n <Popover id=\"task-header-people\" open={peopleAnchor !== null} anchorEl={peopleAnchor} onClose={() => setPeopleAnchor(null)} returnFocus aria-label={`People on ${task}`}>\n <List items={people.map((p) => `${p.name}, ${p.role}`)} />\n </Popover>\n <Popover id=\"task-header-more\" open={moreOpen} anchorEl={moreAnchor} onClose={() => setMoreOpen(false)} returnFocus>\n <Menu navigable aria-label={`Actions for ${task}`} width={200}>\n {/* A real app opens the Rename Modal of the case 'Rename', and archives the task with a toast. */}\n <MenuItem size=\"small\" iconName=\"Pencil\" label=\"Rename\" onClick={() => choose(() => {})} />\n <MenuItem size=\"small\" iconName=\"Archive\" label=\"Archive\" onClick={() => choose(() => {})} />\n <Line />\n {/* Delete is last, and danger. */}\n <MenuItem size=\"small\" color=\"danger\" iconName=\"Trash2\" label=\"Delete Task\" onClick={() => choose(() => setConfirming(true))} />\n </Menu>\n </Popover>\n {/* The task is a page, not a row in a list, so the confirm is a small Modal, as the case 'Delete confirm' says. */}\n <Modal\n isOpen={confirming}\n size=\"small\"\n title=\"Delete Task\"\n onClose={keepTask}\n actions={\n <>\n <Button size=\"small\" type=\"tertiary\" state={deleting ? 'disabled' : 'enabled'} label=\"Cancel\" onClickButton={keepTask} />\n <Button size=\"small\" type=\"primary\" color=\"danger\" state=\"enabled\" label=\"Delete\" loading={deleting} onClickButton={confirmDelete} />\n </>\n }\n >\n <Paragraph measure=\"none\">This deletes '{task}', its plan and its history.</Paragraph>\n </Modal>\n </AppShell>\n );\n}\n",
|
|
7325
7542
|
"uses": [
|
|
7326
7543
|
"AppShell",
|
|
7327
7544
|
"AvatarStack",
|
|
@@ -7350,7 +7567,7 @@
|
|
|
7350
7567
|
"id": "agent-sets-status",
|
|
7351
7568
|
"title": "The agent sets the status",
|
|
7352
7569
|
"useWhen": "The agent or a check sets the state, and people only read it.",
|
|
7353
|
-
"source": "'use client';\nimport { useEffect, useRef, useState } from 'react';\nimport AppShell from 'oneslash-design-system/components/appShell';\nimport SidePane, { type SidePaneHandle } from 'oneslash-design-system/components/sidePane';\nimport Navigation from 'oneslash-design-system/components/navigation';\nimport TitleBar from 'oneslash-design-system/components/titleBar';\nimport Tag from 'oneslash-design-system/components/tag';\nimport AvatarStack from 'oneslash-design-system/components/avatarStack';\nimport Button from 'oneslash-design-system/components/button';\nimport IconButton from 'oneslash-design-system/components/iconButton';\nimport Tooltip from 'oneslash-design-system/components/tooltip';\nimport Popover from 'oneslash-design-system/components/popover';\nimport Menu from 'oneslash-design-system/components/menu';\nimport MenuItem from 'oneslash-design-system/components/menuItem';\nimport Line from 'oneslash-design-system/components/line';\nimport List from 'oneslash-design-system/components/list';\nimport Modal from 'oneslash-design-system/components/modal';\nimport Timeline from 'oneslash-design-system/components/timeline';\nimport Paragraph from 'oneslash-design-system/components/paragraph';\nimport Toaster, { toast, dismissToast } from 'oneslash-design-system/components/toaster';\nimport { Stack } from 'oneslash-design-system/components/layout';\n\ntype PaneId = 'plan' | 'history';\ntype Width = 'wide' | 'phone';\ntype Focusable = HTMLButtonElement | HTMLAnchorElement | null;\n\nconst task = 'Launch checklist';\n\n// The person who started the task comes first, here and in every list of these people.\nconst people = [\n { name: 'Ben Carter', role: 'Admin' },\n { name: 'Dana Lee', role: 'Member' },\n { name: 'Omar Reyes', role: 'Member' },\n { name: 'Mia Park', role: 'Member' },\n { name: 'Leo Grant', role: 'Guest' },\n { name: 'Ana Silva', role: 'Guest' },\n];\n\nconst history = [\n { id: 'h3', title: 'Dana Lee approved the plan', when: 'Nov 16, 2026, 2:52 PM', dateTime: '2026-11-16T14:52', actor: { name: 'Dana Lee' } },\n { id: 'h2', title: 'Acme Agent wrote the plan', when: 'Nov 16, 2026, 2:40 PM', dateTime: '2026-11-16T14:40', actor: { name: 'Acme Agent', agent: true } },\n { id: 'h1', title: 'Ben Carter created the task', when: 'Nov 15, 2026, 4:02 PM', dateTime: '2026-11-15T16:02', actor: { name: 'Ben Carter' } },\n];\n\n// The places. A real app lets each link go to its page.\nconst sidebar = (\n <Navigation aria-label=\"Main\">\n <MenuItem\n size=\"small\"\n label=\"Tasks\"\n iconName=\"ListChecks\"\n href=\"/tasks\"\n isSelected\n aria-current=\"page\"\n onClick={(event: { preventDefault: () => void }) => event.preventDefault()}\n />\n </Navigation>\n);\n\nexport default function TaskHeaderAgentSetsStatus() {\n const [navOpen, setNavOpen] = useState(false);\n const [peopleAnchor, setPeopleAnchor] = useState<HTMLElement | null>(null);\n // Which More button opened the menu: on a phone the menu also holds History. It stays set while the menu fades out.\n const [moreFrom, setMoreFrom] = useState<Width>('wide');\n const [moreAnchor, setMoreAnchor] = useState<HTMLElement | null>(null);\n const [moreOpen, setMoreOpen] = useState(false);\n // One pane at a time. Opening another replaces it.\n const [pane, setPane] = useState<PaneId | null>(null);\n const [confirming, setConfirming] = useState(false);\n const [deleting, setDeleting] = useState(false);\n const paneRef = useRef<SidePaneHandle>(null);\n const moreButtons = useRef<Record<Width, Focusable>>({ wide: null, phone: null });\n const timer = useRef<ReturnType<typeof setTimeout>>();\n const toastIds = useRef<string[]>([]);\n // Where focus goes after the next render, once the element it goes to is on screen.\n const focusNext = useRef<() => void>();\n\n // On unmount it stops the request and closes every toast it opened.\n useEffect(() => () => {\n clearTimeout(timer.current);\n toastIds.current.forEach((id) => dismissToast(id));\n toastIds.current = [];\n }, []);\n\n useEffect(() => {\n const move = focusNext.current;\n focusNext.current = undefined;\n move?.();\n });\n\n // Pressed again while its pane is open, the button brings the pane forward instead of opening a second one.\n function togglePane(id: PaneId) {\n if (pane === id) paneRef.current?.focus();\n else setPane(id);\n }\n\n function openMore(from: Width, el: HTMLElement) {\n if (moreOpen && moreFrom === from) {\n setMoreOpen(false);\n return;\n }\n setMoreFrom(from);\n setMoreAnchor(el);\n setMoreOpen(true);\n }\n\n // Every item closes the menu. The Popover gives focus back to More.\n function choose(action: () => void) {\n setMoreOpen(false);\n action();\n }\n\n // The Modal opens while the menu fades, so it cannot take focus back from the menu item: 'Cancel' sends it to More.\n function keepTask() {\n if (deleting) return;\n setConfirming(false);\n focusNext.current = () => moreButtons.current[moreFrom]?.focus({ preventScroll: true });\n }\n\n function confirmDelete() {\n if (deleting) return;\n setDeleting(true);\n // Stands in for the request to the server. A real app then goes back to the task list.\n timer.current = setTimeout(() => {\n setDeleting(false);\n setConfirming(false);\n toastIds.current.push(toast({ type: 'success', message: `${task} deleted.` }));\n }, 1200);\n }\n\n const paneButton = (id: PaneId) => (\n <Tooltip title={id === 'plan' ? 'Plan' : 'History'}>\n <IconButton\n color=\"iconOnly\"\n state={pane === id ? 'selected' : 'enabled'}\n size=\"medium\"\n iconName={id === 'plan' ? 'FileText' : 'History'}\n ariaLabel={id === 'plan' ? `Show the plan for ${task}` : `Show the history of ${task}`}\n aria-expanded={pane === id}\n onClick={() => togglePane(id)}\n />\n </Tooltip>\n );\n\n const more = (from: Width) => (\n <Tooltip title=\"More\">\n <IconButton\n ref={(el) => { moreButtons.current[from] = el; }}\n color=\"iconOnly\"\n state={moreOpen && moreFrom === from ? 'selected' : 'enabled'}\n size=\"medium\"\n iconName=\"Ellipsis\"\n ariaLabel={`More actions for ${task}`}\n aria-haspopup=\"menu\"\n aria-expanded={moreOpen && moreFrom === from}\n onClick={(e: { currentTarget: HTMLElement }) => openMore(from, e.currentTarget)}\n />\n </Tooltip>\n );\n\n return (\n <AppShell\n title=\"Tasks\"\n navOpen={navOpen}\n onNavOpenChange={setNavOpen}\n sidebar={sidebar}\n pane={\n pane && (\n <SidePane key={pane} ref={paneRef} title={pane === 'plan' ? 'Plan' : 'History'} onClose={() => setPane(null)}>\n {pane === 'plan' ? (\n <Stack gap=\"medium\">\n <Paragraph measure=\"none\">Ship the new home page on Nov 20, 2026. Omar Reyes writes the copy and Mia Park checks the screens.</Paragraph>\n <Paragraph tone=\"secondary\" size=\"body2\" measure=\"none\">Written by Acme Agent, Nov 16, 2026, 2:40 PM</Paragraph>\n </Stack>\n ) : (\n <Timeline id=\"task-header-agent-history\" aria-label=\"History\" items={history} />\n )}\n </SidePane>\n )\n }\n >\n {/* A real app mounts one Toaster near its root. */}\n <Toaster />\n <Stack gap=\"large\">\n <TitleBar\n title={task}\n meta={\n <>\n {/* Acme Agent and the checks set the state. People read it here and do not change it. */}\n <Tag variant=\"dot\" size=\"small\" label=\"In progress\" />\n <AvatarStack\n people={people}\n aria-label={`Show the ${people.length} people on ${task}`}\n aria-haspopup=\"dialog\"\n aria-expanded={peopleAnchor !== null}\n onClick={(event) => setPeopleAnchor(peopleAnchor ? null : event.currentTarget)}\n />\n Due Nov 20, 2026\n </>\n }\n actions={\n <>\n {paneButton('plan')}\n {paneButton('history')}\n {more('wide')}\n </>\n }\n phoneActions={\n <>\n {paneButton('plan')}\n {more('phone')}\n </>\n }\n />\n <Paragraph tone=\"secondary\" measure=\"none\">Acme Agent sets the status as the work moves. It is updating the home page, and Omar Reyes is writing the copy.</Paragraph>\n </Stack>\n <Popover id=\"task-header-agent-people\" open={peopleAnchor !== null} anchorEl={peopleAnchor} onClose={() => setPeopleAnchor(null)} returnFocus>\n <List items={people.map((p) => `${p.name}, ${p.role}`)} />\n </Popover>\n <Popover id=\"task-header-agent-more\" open={moreOpen} anchorEl={moreAnchor} onClose={() => setMoreOpen(false)} returnFocus>\n <Menu navigable aria-label={`Actions for ${task}`} width={200}>\n {moreFrom === 'phone' && (\n <>\n <MenuItem size=\"small\" iconName=\"History\" label=\"History\" onClick={() => choose(() => togglePane('history'))} />\n <Line />\n </>\n )}\n {/* A real app opens the Rename Modal of the case 'Rename', and archives the task with a toast. */}\n <MenuItem size=\"small\" iconName=\"Pencil\" label=\"Rename\" onClick={() => choose(() => {})} />\n <MenuItem size=\"small\" iconName=\"Archive\" label=\"Archive\" onClick={() => choose(() => {})} />\n <Line />\n {/* Delete is last, and danger. */}\n <MenuItem size=\"small\" color=\"danger\" iconName=\"Trash2\" label=\"Delete Task\" onClick={() => choose(() => setConfirming(true))} />\n </Menu>\n </Popover>\n {/* The task is a page, not a row in a list, so the confirm is a small Modal, as the case 'Delete confirm' says. */}\n <Modal\n isOpen={confirming}\n size=\"small\"\n title=\"Delete Task\"\n onClose={keepTask}\n actions={\n <>\n <Button size=\"small\" type=\"tertiary\" state={deleting ? 'disabled' : 'enabled'} label=\"Cancel\" onClickButton={keepTask} />\n <Button size=\"small\" type=\"primary\" color=\"danger\" state=\"enabled\" label=\"Delete\" loading={deleting} onClickButton={confirmDelete} />\n </>\n }\n >\n <Paragraph measure=\"none\">This deletes '{task}', its plan and its history.</Paragraph>\n </Modal>\n </AppShell>\n );\n}\n",
|
|
7570
|
+
"source": "'use client';\nimport { useEffect, useRef, useState } from 'react';\nimport AppShell from 'oneslash-design-system/components/appShell';\nimport SidePane, { type SidePaneHandle } from 'oneslash-design-system/components/sidePane';\nimport Navigation from 'oneslash-design-system/components/navigation';\nimport TitleBar from 'oneslash-design-system/components/titleBar';\nimport Tag from 'oneslash-design-system/components/tag';\nimport AvatarStack from 'oneslash-design-system/components/avatarStack';\nimport Button from 'oneslash-design-system/components/button';\nimport IconButton from 'oneslash-design-system/components/iconButton';\nimport Tooltip from 'oneslash-design-system/components/tooltip';\nimport Popover from 'oneslash-design-system/components/popover';\nimport Menu from 'oneslash-design-system/components/menu';\nimport MenuItem from 'oneslash-design-system/components/menuItem';\nimport Line from 'oneslash-design-system/components/line';\nimport List from 'oneslash-design-system/components/list';\nimport Modal from 'oneslash-design-system/components/modal';\nimport Timeline from 'oneslash-design-system/components/timeline';\nimport Paragraph from 'oneslash-design-system/components/paragraph';\nimport Toaster, { toast, dismissToast } from 'oneslash-design-system/components/toaster';\nimport { Stack } from 'oneslash-design-system/components/layout';\n\ntype PaneId = 'plan' | 'history';\ntype Width = 'wide' | 'phone';\ntype Focusable = HTMLButtonElement | HTMLAnchorElement | null;\n\nconst task = 'Launch checklist';\n\n// The person who started the task comes first, here and in every list of these people.\nconst people = [\n { name: 'Ben Carter', role: 'Admin' },\n { name: 'Dana Lee', role: 'Member' },\n { name: 'Omar Reyes', role: 'Member' },\n { name: 'Mia Park', role: 'Member' },\n { name: 'Leo Grant', role: 'Guest' },\n { name: 'Ana Silva', role: 'Guest' },\n];\n\nconst history = [\n { id: 'h3', title: 'Dana Lee approved the plan', when: 'Nov 16, 2026, 2:52 PM', dateTime: '2026-11-16T14:52', actor: { name: 'Dana Lee' } },\n { id: 'h2', title: 'Acme Agent wrote the plan', when: 'Nov 16, 2026, 2:40 PM', dateTime: '2026-11-16T14:40', actor: { name: 'Acme Agent', agent: true } },\n { id: 'h1', title: 'Ben Carter created the task', when: 'Nov 15, 2026, 4:02 PM', dateTime: '2026-11-15T16:02', actor: { name: 'Ben Carter' } },\n];\n\n// The places. A real app lets each link go to its page.\nconst sidebar = (\n <Navigation aria-label=\"Main\">\n <MenuItem\n size=\"small\"\n label=\"Tasks\"\n iconName=\"ListChecks\"\n href=\"/tasks\"\n isSelected\n aria-current=\"page\"\n onClick={(event: { preventDefault: () => void }) => event.preventDefault()}\n />\n </Navigation>\n);\n\nexport default function TaskHeaderAgentSetsStatus() {\n const [navOpen, setNavOpen] = useState(false);\n const [peopleAnchor, setPeopleAnchor] = useState<HTMLElement | null>(null);\n // Which More button opened the menu: on a phone the menu also holds History. It stays set while the menu fades out.\n const [moreFrom, setMoreFrom] = useState<Width>('wide');\n const [moreAnchor, setMoreAnchor] = useState<HTMLElement | null>(null);\n const [moreOpen, setMoreOpen] = useState(false);\n // One pane at a time. Opening another replaces it.\n const [pane, setPane] = useState<PaneId | null>(null);\n const [confirming, setConfirming] = useState(false);\n const [deleting, setDeleting] = useState(false);\n const paneRef = useRef<SidePaneHandle>(null);\n const moreButtons = useRef<Record<Width, Focusable>>({ wide: null, phone: null });\n const timer = useRef<ReturnType<typeof setTimeout>>();\n const toastIds = useRef<string[]>([]);\n // Where focus goes after the next render, once the element it goes to is on screen.\n const focusNext = useRef<() => void>();\n\n // On unmount it stops the request and closes every toast it opened.\n useEffect(() => () => {\n clearTimeout(timer.current);\n toastIds.current.forEach((id) => dismissToast(id));\n toastIds.current = [];\n }, []);\n\n useEffect(() => {\n const move = focusNext.current;\n focusNext.current = undefined;\n move?.();\n });\n\n // Pressed again while its pane is open, the button brings the pane forward instead of opening a second one.\n function togglePane(id: PaneId) {\n if (pane === id) paneRef.current?.focus();\n else setPane(id);\n }\n\n function openMore(from: Width, el: HTMLElement) {\n if (moreOpen && moreFrom === from) {\n setMoreOpen(false);\n return;\n }\n setMoreFrom(from);\n setMoreAnchor(el);\n setMoreOpen(true);\n }\n\n // Every item closes the menu. The Popover gives focus back to More.\n function choose(action: () => void) {\n setMoreOpen(false);\n action();\n }\n\n // The Modal opens while the menu fades, so it cannot take focus back from the menu item: 'Cancel' sends it to More.\n function keepTask() {\n if (deleting) return;\n setConfirming(false);\n focusNext.current = () => moreButtons.current[moreFrom]?.focus({ preventScroll: true });\n }\n\n function confirmDelete() {\n if (deleting) return;\n setDeleting(true);\n // Stands in for the request to the server. A real app then goes back to the task list.\n timer.current = setTimeout(() => {\n setDeleting(false);\n setConfirming(false);\n toastIds.current.push(toast({ type: 'success', message: `${task} deleted.` }));\n }, 1200);\n }\n\n const paneButton = (id: PaneId) => (\n <Tooltip title={id === 'plan' ? 'Plan' : 'History'}>\n <IconButton\n color=\"iconOnly\"\n state={pane === id ? 'selected' : 'enabled'}\n size=\"medium\"\n iconName={id === 'plan' ? 'FileText' : 'History'}\n ariaLabel={id === 'plan' ? `Show the plan for ${task}` : `Show the history of ${task}`}\n aria-expanded={pane === id}\n onClick={() => togglePane(id)}\n />\n </Tooltip>\n );\n\n const more = (from: Width) => (\n <Tooltip title=\"More\">\n <IconButton\n ref={(el) => { moreButtons.current[from] = el; }}\n color=\"iconOnly\"\n state={moreOpen && moreFrom === from ? 'selected' : 'enabled'}\n size=\"medium\"\n iconName=\"Ellipsis\"\n ariaLabel={`More actions for ${task}`}\n aria-haspopup=\"menu\"\n aria-expanded={moreOpen && moreFrom === from}\n onClick={(e: { currentTarget: HTMLElement }) => openMore(from, e.currentTarget)}\n />\n </Tooltip>\n );\n\n return (\n <AppShell\n title=\"Tasks\"\n navOpen={navOpen}\n onNavOpenChange={setNavOpen}\n sidebar={sidebar}\n pane={\n pane && (\n <SidePane key={pane} ref={paneRef} title={pane === 'plan' ? 'Plan' : 'History'} onClose={() => setPane(null)}>\n {pane === 'plan' ? (\n <Stack gap=\"medium\">\n <Paragraph measure=\"none\">Ship the new home page on Nov 20, 2026. Omar Reyes writes the copy and Mia Park checks the screens.</Paragraph>\n <Paragraph tone=\"secondary\" size=\"body2\" measure=\"none\">Written by Acme Agent, Nov 16, 2026, 2:40 PM</Paragraph>\n </Stack>\n ) : (\n <Timeline id=\"task-header-agent-history\" aria-label=\"History\" items={history} />\n )}\n </SidePane>\n )\n }\n >\n {/* A real app mounts one Toaster near its root. */}\n <Toaster />\n <Stack gap=\"large\">\n <TitleBar\n title={task}\n meta={\n <>\n {/* Acme Agent and the checks set the state. People read it here and do not change it. */}\n <Tag variant=\"dot\" size=\"small\" label=\"In progress\" />\n <AvatarStack\n people={people}\n aria-label={`Show the ${people.length} people on ${task}`}\n aria-haspopup=\"dialog\"\n aria-expanded={peopleAnchor !== null}\n onClick={(event) => setPeopleAnchor(peopleAnchor ? null : event.currentTarget)}\n />\n Due Nov 20, 2026\n </>\n }\n actions={\n <>\n {paneButton('plan')}\n {paneButton('history')}\n {more('wide')}\n </>\n }\n phoneActions={\n <>\n {paneButton('plan')}\n {more('phone')}\n </>\n }\n />\n <Paragraph tone=\"secondary\" measure=\"none\">Acme Agent sets the status as the work moves. It is updating the home page, and Omar Reyes is writing the copy.</Paragraph>\n </Stack>\n <Popover id=\"task-header-agent-people\" open={peopleAnchor !== null} anchorEl={peopleAnchor} onClose={() => setPeopleAnchor(null)} returnFocus aria-label={`People on ${task}`}>\n <List items={people.map((p) => `${p.name}, ${p.role}`)} />\n </Popover>\n <Popover id=\"task-header-agent-more\" open={moreOpen} anchorEl={moreAnchor} onClose={() => setMoreOpen(false)} returnFocus>\n <Menu navigable aria-label={`Actions for ${task}`} width={200}>\n {moreFrom === 'phone' && (\n <>\n <MenuItem size=\"small\" iconName=\"History\" label=\"History\" onClick={() => choose(() => togglePane('history'))} />\n <Line />\n </>\n )}\n {/* A real app opens the Rename Modal of the case 'Rename', and archives the task with a toast. */}\n <MenuItem size=\"small\" iconName=\"Pencil\" label=\"Rename\" onClick={() => choose(() => {})} />\n <MenuItem size=\"small\" iconName=\"Archive\" label=\"Archive\" onClick={() => choose(() => {})} />\n <Line />\n {/* Delete is last, and danger. */}\n <MenuItem size=\"small\" color=\"danger\" iconName=\"Trash2\" label=\"Delete Task\" onClick={() => choose(() => setConfirming(true))} />\n </Menu>\n </Popover>\n {/* The task is a page, not a row in a list, so the confirm is a small Modal, as the case 'Delete confirm' says. */}\n <Modal\n isOpen={confirming}\n size=\"small\"\n title=\"Delete Task\"\n onClose={keepTask}\n actions={\n <>\n <Button size=\"small\" type=\"tertiary\" state={deleting ? 'disabled' : 'enabled'} label=\"Cancel\" onClickButton={keepTask} />\n <Button size=\"small\" type=\"primary\" color=\"danger\" state=\"enabled\" label=\"Delete\" loading={deleting} onClickButton={confirmDelete} />\n </>\n }\n >\n <Paragraph measure=\"none\">This deletes '{task}', its plan and its history.</Paragraph>\n </Modal>\n </AppShell>\n );\n}\n",
|
|
7354
7571
|
"uses": [
|
|
7355
7572
|
"AppShell",
|
|
7356
7573
|
"AvatarStack",
|