@milesroxas/design-hub 0.13.0 → 0.15.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.
Files changed (101) hide show
  1. package/README.md +38 -33
  2. package/core/catalog.test.ts +28 -1
  3. package/core/catalog.ts +21 -4
  4. package/core/prototype.test.ts +12 -1
  5. package/core/prototype.ts +21 -2
  6. package/core/review/model.ts +71 -6
  7. package/core/review/service.test.ts +536 -1
  8. package/core/review/service.ts +452 -25
  9. package/core/review/store.ts +45 -4
  10. package/dist/core/catalog.d.ts +8 -1
  11. package/dist/core/catalog.js +12 -3
  12. package/dist/core/prototype.d.ts +20 -2
  13. package/dist/core/prototype.js +17 -2
  14. package/dist/core/review/model.d.ts +42 -3
  15. package/dist/core/review/model.js +52 -3
  16. package/dist/core/review/service.d.ts +81 -7
  17. package/dist/core/review/service.js +407 -23
  18. package/dist/core/review/store.d.ts +29 -2
  19. package/dist/core/review/store.js +4 -0
  20. package/dist/scripts/client.d.ts +1 -1
  21. package/dist/scripts/client.js +1 -1
  22. package/dist/scripts/lib/catalog.d.ts +1 -1
  23. package/dist/scripts/lib/catalog.js +3 -3
  24. package/dist/scripts/lib/dns.d.ts +16 -2
  25. package/dist/scripts/lib/dns.js +66 -3
  26. package/dist/scripts/lib/fake-host.d.ts +16 -1
  27. package/dist/scripts/lib/fake-host.js +36 -1
  28. package/dist/scripts/lib/host.d.ts +2 -0
  29. package/dist/scripts/lib/resend.d.ts +36 -0
  30. package/dist/scripts/lib/resend.js +66 -0
  31. package/dist/scripts/lib/studio-deps.d.ts +7 -0
  32. package/dist/scripts/lib/studio-deps.js +6 -1
  33. package/dist/scripts/lib/studios.d.ts +2 -2
  34. package/dist/scripts/lib/studios.js +5 -5
  35. package/dist/scripts/lib/vercel-host.js +6 -0
  36. package/dist/scripts/new.d.ts +8 -3
  37. package/dist/scripts/new.js +15 -4
  38. package/dist/scripts/people.d.ts +16 -4
  39. package/dist/scripts/people.js +67 -17
  40. package/dist/scripts/preflight.js +1 -1
  41. package/dist/scripts/share.js +3 -3
  42. package/dist/scripts/studio.d.ts +19 -3
  43. package/dist/scripts/studio.js +327 -6
  44. package/dist/server/api.d.ts +25 -2
  45. package/dist/server/api.js +77 -17
  46. package/dist/server/dev-studio.d.ts +36 -0
  47. package/dist/server/dev-studio.js +181 -0
  48. package/dist/server/dev.d.ts +16 -1
  49. package/dist/server/dev.js +23 -3
  50. package/dist/server/gate.d.ts +26 -3
  51. package/dist/server/gate.js +323 -52
  52. package/dist/server/mailer.d.ts +60 -0
  53. package/dist/server/mailer.js +104 -0
  54. package/dist/server/mailers/fake.d.ts +8 -0
  55. package/dist/server/mailers/fake.js +16 -0
  56. package/dist/server/mailers/resend.d.ts +21 -0
  57. package/dist/server/mailers/resend.js +49 -0
  58. package/dist/server/session.js +4 -1
  59. package/dist/vercel/proxy.js +10 -3
  60. package/dist/vite/plugin.js +6 -1
  61. package/kit/ViewTools.tsx +9 -0
  62. package/kit/prefs.ts +3 -4
  63. package/kit/ui/Menu.tsx +29 -18
  64. package/kit/ui/layer.ts +41 -0
  65. package/package.json +1 -1
  66. package/shell/Command.tsx +142 -0
  67. package/shell/Index.tsx +902 -400
  68. package/shell/Milestone.tsx +302 -0
  69. package/shell/Sidebar.tsx +236 -0
  70. package/shell/index.css +224 -0
  71. package/shell/milestones.test.ts +157 -0
  72. package/shell/milestones.ts +144 -0
  73. package/shell/registry.ts +4 -3
  74. package/shell/review/Bar.tsx +1 -0
  75. package/shell/review/Card.tsx +17 -7
  76. package/shell/review/People.tsx +908 -134
  77. package/shell/review/Review.tsx +2 -2
  78. package/shell/review/anchor.ts +6 -1
  79. package/shell/review/client.ts +41 -7
  80. package/shell/review/menu-place.test.ts +41 -0
  81. package/shell/review/place.test.ts +26 -1
  82. package/shell/review/place.ts +17 -0
  83. package/shell/review/review.css +97 -11
  84. package/shell/review/view.test.ts +115 -1
  85. package/shell/review/view.ts +92 -2
  86. package/shell/shell.css +8 -175
  87. package/shell/sidebar.css +86 -0
  88. package/shell/studio/ClientHub.tsx +21 -10
  89. package/shell/studio/StudioHub.tsx +121 -45
  90. package/shell/studio/hub.css +118 -27
  91. package/shell/studio/page.tsx +28 -17
  92. package/shell/system.css +12 -0
  93. package/skills/miles-deploy/SKILL.md +25 -4
  94. package/skills/miles-new-feature/SKILL.md +2 -1
  95. package/skills/miles-prototype/SKILL.md +1 -1
  96. package/templates/app/README.md +1 -1
  97. package/templates/brand/README.md +1 -1
  98. package/templates/site/README.md +1 -1
  99. package/templates/space/README.md +1 -1
  100. package/templates/studio/.env.example +6 -0
  101. package/templates/studio/package.json +1 -1
@@ -0,0 +1,104 @@
1
+ // The one port mail goes through (email.md, E12): a studio site sends when it
2
+ // has a mail key and a sender, and never otherwise. Resend is its first
3
+ // adapter (server/mailers/resend.ts). A send never throws and answers sent,
4
+ // refused or down; whoever sends records the answer for Studio (recordMail),
5
+ // and a person is never shown it (E7).
6
+ import { escapeHtml } from '../core/html.js';
7
+ import { CODE } from '../core/review/model.js';
8
+ import { resendMailer } from './mailers/resend.js';
9
+ /** The name in a sender (`Suits & Sandals <signin@mail.example.com>`), or its address when it has none. */
10
+ export function senderName(from) {
11
+ const named = from.match(/^\s*"?([^"<]*?)"?\s*<([^>]+)>\s*$/);
12
+ return (named?.[1] || named?.[2] || from).trim();
13
+ }
14
+ /** The studio's mailer: null unless both RESEND_API_KEY and MAIL_FROM are set, so a studio that wants only links sets up nothing. */
15
+ export function chooseMailer(env, fetcher) {
16
+ const key = env.RESEND_API_KEY?.trim();
17
+ const from = env.MAIL_FROM?.trim();
18
+ if (!key || !from)
19
+ return null;
20
+ return { name: senderName(from), ...resendMailer({ key, from, ...(fetcher ? { fetcher } : {}) }) };
21
+ }
22
+ /** A code as it is read aloud: two groups of four. */
23
+ const spacedCode = (code) => `${code.slice(0, 4)} ${code.slice(4)}`;
24
+ /**
25
+ * The code mail (email.md, section 3): the studio's name, the code in two
26
+ * groups of four, how long it lasts, and one line to ignore it. No link, no
27
+ * tracking, no image. The subject starts with the code, so it reads from a
28
+ * notification. `key` is the person and the code's hash, so each new code is
29
+ * a new mail and a second send of one code is not.
30
+ */
31
+ export function codeMail(studio, to, code, key) {
32
+ const spaced = spacedCode(code);
33
+ const subject = `${spaced} is your sign-in code for ${studio}`;
34
+ const lasts = `It works once and lasts ${CODE.minutes} minutes.`;
35
+ const ignore = 'If you did not ask for it, ignore this email.';
36
+ const text = `Your sign-in code for ${studio}:\n\n${spaced}\n\n${lasts}\n\n${ignore}\n`;
37
+ const font = 'font-family:-apple-system,BlinkMacSystemFont,&quot;Segoe UI&quot;,Helvetica,Arial,sans-serif';
38
+ const html = `<!doctype html>
39
+ <html lang="en">
40
+ <head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${escapeHtml(subject)}</title></head>
41
+ <body style="margin:0;padding:32px 16px;background:#ffffff;color:#171717;${font};font-size:14px;line-height:20px">
42
+ <div style="max-width:360px;margin:0 auto">
43
+ <p style="margin:0 0 16px">Your sign-in code for ${escapeHtml(studio)}:</p>
44
+ <p style="margin:0 0 16px;font-size:28px;line-height:36px;font-weight:600;letter-spacing:.08em;font-variant-numeric:tabular-nums">${spaced}</p>
45
+ <p style="margin:0 0 8px;color:#585858">${lasts}</p>
46
+ <p style="margin:0;color:#585858">${ignore}</p>
47
+ </div>
48
+ </body>
49
+ </html>
50
+ `;
51
+ return { to, subject, text, html, key: `code-${key}` };
52
+ }
53
+ /**
54
+ * The invite (email.md, E10): who gave them access, their one-time link as
55
+ * one button and as plain text, that it works once on one device, and the
56
+ * address to sign in at with this email from then on: their client's own
57
+ * host, or the studio's for a Studio person, never another's. Its words are
58
+ * the link page's ("Sign in as", "Next time, sign in with your email"). No
59
+ * tracking, no image. `key` is the person's id: one add, one mail.
60
+ */
61
+ export function inviteMail(studio, person, link, address) {
62
+ const subject = `Your sign-in link for ${studio}`;
63
+ const title = `Sign in as ${person.name}`;
64
+ const lead = `${studio} gave you access. This link works once, on one device.`;
65
+ const home = `https://${address}`;
66
+ const text = `${title}\n\n${lead}\n\n${link}\n\nNext time, sign in with your email at ${home}\n`;
67
+ const font = 'font-family:-apple-system,BlinkMacSystemFont,&quot;Segoe UI&quot;,Helvetica,Arial,sans-serif';
68
+ const muted = 'color:#585858';
69
+ const html = `<!doctype html>
70
+ <html lang="en">
71
+ <head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${escapeHtml(subject)}</title></head>
72
+ <body style="margin:0;padding:32px 16px;background:#ffffff;color:#171717;${font};font-size:14px;line-height:20px">
73
+ <div style="max-width:360px;margin:0 auto">
74
+ <p style="margin:0 0 12px;${muted}">${escapeHtml(studio)}</p>
75
+ <p style="margin:0 0 8px;font-size:20px;line-height:28px;font-weight:600;overflow-wrap:anywhere">${escapeHtml(title)}</p>
76
+ <p style="margin:0 0 20px">${escapeHtml(lead)}</p>
77
+ <p style="margin:0 0 20px"><a href="${escapeHtml(link)}" style="display:inline-block;padding:12px 20px;line-height:20px;border-radius:8px;background:#171717;color:#ffffff;font-weight:600;text-decoration:none">Sign in</a></p>
78
+ <p style="margin:0 0 20px">Next time, sign in with your email at <a href="${escapeHtml(home)}" style="color:#171717">${escapeHtml(address)}</a>.</p>
79
+ <p style="margin:0 0 4px;font-size:12px;line-height:16px;${muted}">If the button does not open, paste this link into your browser:</p>
80
+ <p style="margin:0;font-size:12px;line-height:16px;${muted};word-break:break-all">${escapeHtml(link)}</p>
81
+ </div>
82
+ </body>
83
+ </html>
84
+ `;
85
+ return { to: person.email, subject, text, html, key: `invite-${person.id}` };
86
+ }
87
+ /**
88
+ * Sends one mail and records the answer for Studio (recordMail, email.md,
89
+ * "When mail breaks"): the one way the studio's mail goes out, a code's or an
90
+ * invite's. Never rejects: a mailer that throws is down, and a record that
91
+ * fails is logged, so the answer stands whatever the store does.
92
+ */
93
+ export async function sendAndRecord(mailer, review, mail) {
94
+ const answer = await mailer.send(mail).catch(() => 'down');
95
+ await review.recordMail(answer).catch((error) => console.error('[mail] not recorded:', error));
96
+ return answer;
97
+ }
98
+ /**
99
+ * Mails a new person their invite, with their link on `home`, the host they
100
+ * sign in on, and records the answer as a code's is (sendAndRecord). Waits
101
+ * for the send, since whoever adds is Studio (E7 is about the person signing
102
+ * in). Never throws: the person and their link stand whatever happens.
103
+ */
104
+ export const sendInvite = (mailer, review, person, token, home) => sendAndRecord(mailer, review, inviteMail(mailer.name, person, `https://${home}/invite/${token}`, home));
@@ -0,0 +1,8 @@
1
+ import type { Mail, Mailer, Sent } from '../mailer.ts';
2
+ export type FakeMailer = Mailer & {
3
+ /** Every mail sent, in order. */
4
+ sent: Mail[];
5
+ /** What the next sends answer; `hang` never answers. */
6
+ answer: Sent | 'hang' | 'throw';
7
+ };
8
+ export declare function fakeMailer(name?: string): FakeMailer;
@@ -0,0 +1,16 @@
1
+ export function fakeMailer(name = 'Test Studio') {
2
+ const mailer = {
3
+ name,
4
+ sent: [],
5
+ answer: 'sent',
6
+ send(mail) {
7
+ mailer.sent.push(mail);
8
+ if (mailer.answer === 'hang')
9
+ return new Promise(() => { });
10
+ if (mailer.answer === 'throw')
11
+ return Promise.reject(new Error('fake mailer failed'));
12
+ return Promise.resolve(mailer.answer);
13
+ },
14
+ };
15
+ return mailer;
16
+ }
@@ -0,0 +1,21 @@
1
+ import type { Sent } from '../../core/review/service.ts';
2
+ type Mail = {
3
+ to: string;
4
+ subject: string;
5
+ text: string;
6
+ html: string;
7
+ key: string;
8
+ };
9
+ export type ResendOptions = {
10
+ /** The send-only key (RESEND_API_KEY). */
11
+ key: string;
12
+ /** The sender, `Name <address>` (MAIL_FROM). */
13
+ from: string;
14
+ fetcher?: typeof fetch;
15
+ /** How long a send may take before it is down; tests shorten it. */
16
+ timeoutMs?: number;
17
+ };
18
+ export declare function resendMailer({ key, from, fetcher, timeoutMs }: ResendOptions): {
19
+ send(mail: Mail): Promise<Sent>;
20
+ };
21
+ export {};
@@ -0,0 +1,49 @@
1
+ const ENDPOINT = 'https://api.resend.com/emails';
2
+ const TIMEOUT_MS = 5_000;
3
+ /** A 200 whose body names the mail Resend made. */
4
+ async function made(response) {
5
+ const body = (await response.json().catch(() => null));
6
+ return typeof body?.id === 'string' && body.id !== '';
7
+ }
8
+ export function resendMailer({ key, from, fetcher = fetch, timeoutMs = TIMEOUT_MS }) {
9
+ async function post(mail, signal) {
10
+ const response = await fetcher(ENDPOINT, {
11
+ method: 'POST',
12
+ headers: {
13
+ authorization: `Bearer ${key}`,
14
+ 'content-type': 'application/json',
15
+ // Held 24 hours by Resend: the same mail sent twice is one mail.
16
+ 'idempotency-key': mail.key,
17
+ },
18
+ body: JSON.stringify({ from, to: [mail.to], subject: mail.subject, text: mail.text, html: mail.html }),
19
+ signal,
20
+ });
21
+ if (response.status === 200 && (await made(response)))
22
+ return 'sent';
23
+ console.error('[mail] Resend refused a send:', response.status);
24
+ return 'refused';
25
+ }
26
+ return {
27
+ async send(mail) {
28
+ const abort = new AbortController();
29
+ let timer;
30
+ // A fetch that ignores its signal still ends here: the timer answers down.
31
+ const late = new Promise((resolve) => {
32
+ timer = setTimeout(() => {
33
+ abort.abort();
34
+ resolve('down');
35
+ }, timeoutMs);
36
+ });
37
+ try {
38
+ return await Promise.race([post(mail, abort.signal), late]);
39
+ }
40
+ catch {
41
+ console.error('[mail] Resend did not answer.');
42
+ return 'down';
43
+ }
44
+ finally {
45
+ clearTimeout(timer);
46
+ }
47
+ },
48
+ };
49
+ }
@@ -109,6 +109,9 @@ export const clearedCookie = (name) => `${name}=; Path=/; Max-Age=0; HttpOnly; S
109
109
  // A request with neither header is not from a browser that could be tricked
110
110
  // into it (every current browser sends Origin on a POST), so it passes: it
111
111
  // holds whatever it sends, and a forged request needs a victim's browser.
112
+ // http only on this machine: localhost and its subdomains (acme.localhost),
113
+ // which every current browser resolves to loopback.
114
+ const isLocalhost = (hostname) => hostname === 'localhost' || hostname.endsWith('.localhost');
112
115
  export function sameOrigin(request) {
113
116
  const site = request.headers.get('sec-fetch-site');
114
117
  if (site && site !== 'same-origin')
@@ -121,7 +124,7 @@ export function sameOrigin(request) {
121
124
  const host = request.headers.get('x-forwarded-host') ?? request.headers.get('host') ?? new URL(request.url).host;
122
125
  try {
123
126
  const o = new URL(origin);
124
- return (o.protocol === 'https:' || o.hostname === 'localhost') && o.host === host;
127
+ return (o.protocol === 'https:' || isLocalhost(o.hostname)) && o.host === host;
125
128
  }
126
129
  catch {
127
130
  return false;
@@ -2,14 +2,21 @@
2
2
  // as proxy.entrypoint): the gate (server/gate.ts), with its decisions carried
3
3
  // out the way Vercel's middleware does, `next()` to pass on and `rewrite()`
4
4
  // to go on to a function. Everything the gate decides is in the gate; this
5
- // file only says it in Vercel's words.
6
- import { next, rewrite } from '@vercel/functions';
5
+ // file only says it in Vercel's words: work after the response goes to
6
+ // `waitUntil`, and the network address the cap counts is `x-real-ip`, which
7
+ // Vercel's edge sets from the connection and overwrites whatever the caller
8
+ // sent (read by `ipAddress`), so no caller chooses it.
9
+ import { ipAddress, next, rewrite, waitUntil } from '@vercel/functions';
7
10
  import { createGate, GATE_FONT, gatePreview } from '../server/gate.js';
8
11
  export { GATE_FONT, gatePreview };
9
12
  /** A gate's decision as Vercel's middleware answers it. */
10
13
  export function onVercel(decision) {
11
14
  if (decision instanceof Response)
12
15
  return decision;
16
+ if ('answer' in decision) {
17
+ waitUntil(decision.after);
18
+ return decision.answer;
19
+ }
13
20
  if (decision.pass === 'rewrite')
14
21
  return rewrite(decision.to, { headers: decision.headers });
15
22
  return decision.headers ? next({ headers: decision.headers }) : next();
@@ -18,6 +25,6 @@ export function onVercel(decision) {
18
25
  export function createStudioProxy(options = {}) {
19
26
  const gate = createGate(options);
20
27
  return async function proxy(request) {
21
- return onVercel(await gate(request));
28
+ return onVercel(await gate(request, { address: ipAddress(request) ?? null }));
22
29
  };
23
30
  }
@@ -12,6 +12,7 @@ import react from '@vitejs/plugin-react';
12
12
  import { build, searchForWorkspaceRoot } from 'vite';
13
13
  import { isProjectSlug, STUDIO_DIR, STUDIO_PAGE } from '../core/prototype.js';
14
14
  import { devReview } from '../server/dev.js';
15
+ import { devStudio } from '../server/dev-studio.js';
15
16
  import { devPort, readEnv } from '../server/env.js';
16
17
  import { GATE_FONT, gatePreview } from '../server/gate.js';
17
18
  import { PACKAGE, PACKAGE_KIT, SHELL } from '../server/paths.js';
@@ -23,7 +24,9 @@ const require = createRequire(import.meta.url);
23
24
  // The gate pages load before sign-in, so they cannot reach the hashed
24
25
  // bundle. Their font goes out at the one fixed path the gate lets through.
25
26
  // `design-hub dev` has no gate, so there /_gate/ previews the sign-in page,
26
- // ?page=link a link's page and ?page=used a used or expired link's.
27
+ // ?page=link a link's page and ?page=used a used or expired link's; email
28
+ // sign-in's pages too: ?page=email, code, code-wrong, code-expired,
29
+ // code-tries, code-long and slow (gatePreview in server/gate.ts).
27
30
  const gateFontFile = () => join(dirname(require.resolve('@fontsource-variable/geist')), 'files', 'geist-latin-wght-normal.woff2');
28
31
  function gateFont() {
29
32
  return {
@@ -64,6 +67,8 @@ export function designHub({ root }) {
64
67
  kitResolver(join(root, 'kit'), PACKAGE_KIT),
65
68
  lapse(root),
66
69
  markdownDocs(),
70
+ // Before devReview: a request from a studio page is the dev studio's, every other the project's.
71
+ devStudio(),
67
72
  devReview(),
68
73
  gateFont(),
69
74
  ];
package/kit/ViewTools.tsx CHANGED
@@ -3,10 +3,12 @@ import { createContext, useContext, useEffect, useLayoutEffect, useState } from
3
3
  import { ensureDialRoot } from './dials';
4
4
  import {
5
5
  type Appearance,
6
+ pinAppearance,
6
7
  prefersReducedMotion,
7
8
  setAppearance,
8
9
  setForceReduce,
9
10
  setSpeed,
11
+ urlAppearance,
10
12
  useAppearance,
11
13
  } from './prefs';
12
14
 
@@ -79,6 +81,13 @@ function useTheme(
79
81
  useEffect(() => {
80
82
  if (on) setValue('theme', appearance);
81
83
  }, [on, appearance, setValue]);
84
+ // A panel without the theme is a prototype with one look: the page opens in the system theme, so hold it
85
+ // in light (or what ?theme= asks) while the prototype is open, as a Board holds its export look. Before paint, so a dark machine never flashes dark.
86
+ useLayoutEffect(() => {
87
+ if (on) return;
88
+ pinAppearance(urlAppearance() ?? 'light');
89
+ return () => pinAppearance(null);
90
+ }, [on]);
82
91
  }
83
92
 
84
93
  function useMotion(on: boolean, reduce: boolean | undefined, speed: string | undefined) {
package/kit/prefs.ts CHANGED
@@ -29,12 +29,12 @@ let forceReduce = false;
29
29
  let speed = 1;
30
30
  let lapse: LapseHandle | null = null;
31
31
 
32
+ // Every page opens in the system theme, so a reviewer sees what their OS asks for. ?theme= overrides it,
33
+ // and a choice in View or a product setting lasts until the page reloads.
32
34
  function readAppearance(): Appearance {
33
35
  const fromUrl = params.get('theme');
34
36
  if (fromUrl === 'light' || fromUrl === 'dark' || fromUrl === 'system') return fromUrl;
35
- const saved = readStored('proto:appearance');
36
- if (saved === 'light' || saved === 'dark' || saved === 'system') return saved;
37
- return 'light';
37
+ return 'system';
38
38
  }
39
39
 
40
40
  // Storage throws in a private window or with site data blocked: the page then runs on its defaults.
@@ -99,7 +99,6 @@ export const urlAppearance = (): 'light' | 'dark' | null => {
99
99
  export function setAppearance(next: Appearance) {
100
100
  if (next === appearance) return;
101
101
  appearance = next;
102
- store('proto:appearance', next);
103
102
  applyTheme();
104
103
  emit();
105
104
  }
package/kit/ui/Menu.tsx CHANGED
@@ -10,7 +10,7 @@ import {
10
10
  } from 'react';
11
11
  import { createPortal } from 'react-dom';
12
12
  import { Icon, type IconName } from '../Icon';
13
- import { afterTransition } from './layer';
13
+ import { afterTransition, placeMenu } from './layer';
14
14
  import './ui.css';
15
15
 
16
16
  export type MenuItem = {
@@ -40,6 +40,8 @@ export type MenuConfig = {
40
40
  selected?: string;
41
41
  checkable?: boolean;
42
42
  role?: 'menu' | 'listbox';
43
+ /** A selector for the card or panel the trigger sits in: the menu opens on the side that stays inside it. */
44
+ within?: string;
43
45
  /** Added to the popup, which portals to <body>: the way a layer with its own material and stacking dresses its menus. */
44
46
  className?: string;
45
47
  onSelect?: (value: string | undefined, item: MenuItem) => void;
@@ -162,7 +164,13 @@ function MenuPopup({
162
164
  const menu = popupRef.current;
163
165
  const trigger = triggerRef.current;
164
166
  if (!menu || !trigger) return;
165
- place(menu, trigger, typeof config.width === 'function' ? config.width(trigger) : config.width, align);
167
+ place(
168
+ menu,
169
+ trigger,
170
+ typeof config.width === 'function' ? config.width(trigger) : config.width,
171
+ align,
172
+ config.within,
173
+ );
166
174
  const frame = requestAnimationFrame(() => setShown(true));
167
175
  const focus = setTimeout(() => {
168
176
  const picked = selected != null ? menu.querySelector<HTMLElement>('.menu-item.is-selected') : null;
@@ -265,23 +273,26 @@ const STEP: Record<string, (i: number, last: number) => number> = {
265
273
  End: (_, last) => last,
266
274
  };
267
275
 
268
- /**
269
- * Opens below the trigger when it fits, above when it does not, aligned to
270
- * the trigger's end or start and kept 8px inside the viewport. The origin
271
- * sits on the trigger, so the menu grows out of it.
272
- */
273
- function place(menu: HTMLElement, trigger: HTMLElement, width: number | undefined, align: 'start' | 'end') {
274
- const r = trigger.getBoundingClientRect();
276
+ /** Puts the menu where `placeMenu` says, for its trigger and the container it should stay inside. */
277
+ function place(
278
+ menu: HTMLElement,
279
+ trigger: HTMLElement,
280
+ width: number | undefined,
281
+ align: 'start' | 'end',
282
+ within: string | undefined,
283
+ ) {
275
284
  if (width) menu.style.width = `${width}px`;
276
- const mw = width || menu.offsetWidth;
277
- const mh = menu.offsetHeight;
278
- const below = r.bottom + 4 + mh <= innerHeight - 8 || r.top - mh - 4 < 8;
279
- const top = below ? r.bottom + 4 : r.top - mh - 4;
280
- const left = Math.max(8, Math.min(align === 'end' ? r.right - mw : r.left, innerWidth - mw - 8));
281
- menu.dataset.side = below ? 'below' : 'above';
282
- menu.style.top = `${top + scrollY}px`;
283
- menu.style.left = `${left + scrollX}px`;
284
- menu.style.transformOrigin = `${below ? 'top' : 'bottom'} ${align === 'end' ? 'right' : 'left'}`;
285
+ const at = placeMenu(
286
+ trigger.getBoundingClientRect(),
287
+ { width: width || menu.offsetWidth, height: menu.offsetHeight },
288
+ { width: innerWidth, height: innerHeight },
289
+ align,
290
+ within ? trigger.closest(within)?.getBoundingClientRect() : null,
291
+ );
292
+ menu.dataset.side = at.side;
293
+ menu.style.top = `${at.top + scrollY}px`;
294
+ menu.style.left = `${at.left + scrollX}px`;
295
+ menu.style.transformOrigin = at.origin;
285
296
  }
286
297
 
287
298
  function MenuKeys({ keys }: { keys: NonNullable<MenuItem['keys']> }) {
package/kit/ui/layer.ts CHANGED
@@ -49,3 +49,44 @@ export function installPressFeedback() {
49
49
  document.addEventListener('pointercancel', lift);
50
50
  document.addEventListener('pointerleave', lift, true);
51
51
  }
52
+
53
+ type Box = { top: number; bottom: number; left: number; right: number };
54
+
55
+ /**
56
+ * Where a menu goes for its trigger. Below when it fits, above when it does
57
+ * not, on the trigger's end or start edge and 8px inside the viewport. With
58
+ * `within` (the card or panel the trigger sits in), the side that stays
59
+ * inside it wins, and when neither does, the side that leaves it least. The
60
+ * origin is the trigger's own edge, in the menu's pixels, so the menu grows
61
+ * out of its button even when the viewport pushed it sideways.
62
+ */
63
+ export function placeMenu(
64
+ trigger: Box,
65
+ menu: { width: number; height: number },
66
+ viewport: { width: number; height: number },
67
+ align: 'start' | 'end',
68
+ within?: Box | null,
69
+ ) {
70
+ const GAP = 4;
71
+ const EDGE = 8;
72
+ const below = trigger.bottom + GAP + menu.height;
73
+ const above = trigger.top - GAP - menu.height;
74
+ const fitsBelow = below <= viewport.height - EDGE;
75
+ const fitsAbove = above >= EDGE;
76
+ let down = fitsBelow || !fitsAbove;
77
+ if (within && fitsBelow && fitsAbove) {
78
+ const overBelow = Math.max(0, below - within.bottom);
79
+ const overAbove = Math.max(0, within.top - above);
80
+ down = overBelow <= overAbove;
81
+ }
82
+ const anchor = align === 'end' ? trigger.right : trigger.left;
83
+ const wanted = align === 'end' ? trigger.right - menu.width : trigger.left;
84
+ const left = Math.max(EDGE, Math.min(wanted, viewport.width - menu.width - EDGE));
85
+ const x = Math.max(0, Math.min(anchor - left, menu.width));
86
+ return {
87
+ side: down ? ('below' as const) : ('above' as const),
88
+ top: down ? trigger.bottom + GAP : above,
89
+ left,
90
+ origin: `${x}px ${down ? 'top' : 'bottom'}`,
91
+ };
92
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@milesroxas/design-hub",
3
- "version": "0.13.0",
3
+ "version": "0.15.0",
4
4
  "description": "The Design Hub product: the hub that lists and serves prototypes, the review panel and its API, the sign-in gate, the kit, and the design-hub CLI. A project installs it and keeps only its prototypes, kit materials and docs.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -0,0 +1,142 @@
1
+ // The command menu: one box that finds any milestone, prototype, tool or
2
+ // action. Opened many times a day, so it opens and closes with no motion.
3
+ // Enter opens a prototype and shows a milestone's home.
4
+ import { Icon, type IconName } from '@kit/Icon';
5
+ import { type KeyboardEvent, useEffect, useRef, useState } from 'react';
6
+
7
+ export type CommandItem = {
8
+ id: string;
9
+ group: 'Recent' | 'Milestones' | 'Prototypes' | 'Tools' | 'Actions';
10
+ label: string;
11
+ /** Read by the search beside the label, never shown. */
12
+ text?: string;
13
+ hint?: string;
14
+ icon: IconName;
15
+ run: () => void;
16
+ };
17
+
18
+ const LIMIT = 8;
19
+ const GROUPS: CommandItem['group'][] = ['Milestones', 'Prototypes', 'Tools', 'Actions'];
20
+
21
+ /** What a query leaves: every group's matches, at most eight of each. With no query, what was opened last and the actions. */
22
+ function resultsOf(items: CommandItem[], q: string): CommandItem[] {
23
+ if (!q) return items.filter((i) => i.group === 'Recent' || i.group === 'Actions');
24
+ const hit = (i: CommandItem) => `${i.label} ${i.text ?? ''} ${i.hint ?? ''}`.toLowerCase().includes(q);
25
+ return GROUPS.flatMap((g) => items.filter((i) => i.group === g && hit(i)).slice(0, LIMIT));
26
+ }
27
+
28
+ /** Which way a key moves the active option: the arrows, or Control with N and P. */
29
+ const moveOf = (e: KeyboardEvent) => {
30
+ if (e.key === 'ArrowDown' || (e.ctrlKey && e.key === 'n')) return 1;
31
+ if (e.key === 'ArrowUp' || (e.ctrlKey && e.key === 'p')) return -1;
32
+ return 0;
33
+ };
34
+ const closes = (e: KeyboardEvent) =>
35
+ e.key === 'Escape' || ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k');
36
+
37
+ export function CommandMenu({ items, onClose }: { items: CommandItem[]; onClose: () => void }) {
38
+ const [query, setQuery] = useState('');
39
+ const [active, setActive] = useState(0);
40
+ const back = useRef<Element | null>(document.activeElement);
41
+ const list = useRef<HTMLDivElement>(null);
42
+ const field = useRef<HTMLInputElement>(null);
43
+ useEffect(() => field.current?.focus(), []);
44
+ const shown = resultsOf(items, query.trim().toLowerCase());
45
+ const at = Math.min(active, Math.max(0, shown.length - 1));
46
+
47
+ // Focus goes back to where it was once the page behind is no longer inert.
48
+ const close = () => {
49
+ const el = back.current as HTMLElement | null;
50
+ onClose();
51
+ requestAnimationFrame(() => el?.focus?.());
52
+ };
53
+ const run = (item?: CommandItem) => {
54
+ if (!item) return;
55
+ close();
56
+ item.run();
57
+ };
58
+
59
+ // biome-ignore lint/correctness/useExhaustiveDependencies: scroll the active option into view when it changes
60
+ useEffect(() => {
61
+ list.current?.querySelector('[aria-selected="true"]')?.scrollIntoView({ block: 'nearest' });
62
+ }, [at]);
63
+
64
+ const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
65
+ const move = moveOf(e);
66
+ if (!move && e.key !== 'Enter' && e.key !== 'Tab' && !closes(e)) return;
67
+ e.preventDefault();
68
+ e.stopPropagation();
69
+ if (move) setActive((at + move + shown.length) % Math.max(1, shown.length));
70
+ else if (e.key === 'Enter') run(shown[at]);
71
+ else if (closes(e)) close();
72
+ };
73
+
74
+ return (
75
+ <div
76
+ className="ix-cmd-overlay sys"
77
+ onPointerDown={(e) => {
78
+ if (e.target === e.currentTarget) close();
79
+ }}
80
+ >
81
+ <div className="ix-cmd" role="dialog" aria-modal="true" aria-label="Command menu" onKeyDown={onKeyDown}>
82
+ <div className="ix-cmd-field">
83
+ <Icon name="search-md" size={16} />
84
+ <input
85
+ ref={field}
86
+ role="combobox"
87
+ aria-expanded="true"
88
+ aria-controls="ix-cmd-list"
89
+ aria-activedescendant={shown[at] ? `ix-cmd-${shown[at].id}` : undefined}
90
+ aria-label="Search milestones, prototypes and actions"
91
+ placeholder="Search milestones, prototypes and actions"
92
+ autoComplete="off"
93
+ spellCheck={false}
94
+ value={query}
95
+ onChange={(e) => {
96
+ setQuery(e.target.value);
97
+ setActive(0);
98
+ }}
99
+ />
100
+ <span className="ix-kbd" aria-hidden="true">
101
+ esc
102
+ </span>
103
+ </div>
104
+ <div ref={list} id="ix-cmd-list" className="ix-cmd-list" role="listbox" aria-label="Results">
105
+ {shown.length === 0 ? <p className="ix-cmd-none">Nothing matches “{query}”.</p> : null}
106
+ {shown.map((item, i) => (
107
+ <div key={item.id} role="presentation">
108
+ {item.group !== shown[i - 1]?.group ? (
109
+ <div className="ix-cmd-group" role="presentation">
110
+ {item.group}
111
+ </div>
112
+ ) : null}
113
+ {/* biome-ignore lint/a11y/useKeyWithClickEvents: the input owns the keys; options take the pointer */}
114
+ <div
115
+ id={`ix-cmd-${item.id}`}
116
+ role="option"
117
+ aria-selected={i === at}
118
+ tabIndex={-1}
119
+ className="ix-cmd-item"
120
+ onPointerMove={() => i !== at && setActive(i)}
121
+ onClick={() => run(item)}
122
+ >
123
+ <Icon name={item.icon} size={16} />
124
+ <span className="ix-cmd-label">{item.label}</span>
125
+ {item.hint ? <span className="ix-cmd-hint">{item.hint}</span> : null}
126
+ </div>
127
+ </div>
128
+ ))}
129
+ </div>
130
+ <div className="ix-cmd-foot" aria-hidden="true">
131
+ <span>
132
+ <kbd>↑</kbd>
133
+ <kbd>↓</kbd> Move
134
+ </span>
135
+ <span>
136
+ <kbd>↵</kbd> Open
137
+ </span>
138
+ </div>
139
+ </div>
140
+ </div>
141
+ );
142
+ }