@brucesantos/design-space 0.8.0 → 0.9.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.
@@ -1,4 +1,4 @@
1
- import { ComponentPreview, ComponentPreviewFixture, Fixture, HandoffScope, Persona, ProductDefinition, RouteDefinition, Rule, Scenario } from '../types/index.js';
1
+ import { ComponentPreview, Control, ControlGroup, ComponentPreviewFixture, Fixture, HandoffScope, Persona, ProductDefinition, RouteDefinition, Rule, Scenario } from '../types/index.js';
2
2
  import { ValidationIssue } from './validate.js';
3
3
  /**
4
4
  * Uma tela: uma rota declarada e as variações dela.
@@ -20,6 +20,32 @@ export type ScreenNode = {
20
20
  href: string;
21
21
  /** Cenários da rota, na ordem de `scenarios`. */
22
22
  variations: Scenario[];
23
+ /** `route.group`, sem espaços nas pontas; `undefined` quando a tela não tem fluxo. */
24
+ group: string | undefined;
25
+ /** `route.controls`, ou lista vazia. */
26
+ controls: ControlGroup[];
27
+ };
28
+ /**
29
+ * Um fluxo: as telas que declaram o mesmo `route.group`, na ordem de `routes`.
30
+ * O fluxo sem nome reúne as telas sem `group` e vem sempre primeiro.
31
+ */
32
+ export type FlowNode = {
33
+ name: string | undefined;
34
+ screens: ScreenNode[];
35
+ };
36
+ /** Um valor de controle pedido pela URL que o motor não pôde usar. */
37
+ export type InvalidControl = {
38
+ id: string;
39
+ value: string;
40
+ /** `unknown-control`: a tela não tem esse controle. `invalid-value`: o valor não é uma das opções. */
41
+ reason: "unknown-control" | "invalid-value";
42
+ /** Valor usado no lugar, quando o controle existe. */
43
+ fallback?: string;
44
+ };
45
+ export type ControlResolution = {
46
+ /** Valor de cada controle da tela, na ordem declarada. */
47
+ values: Record<string, string>;
48
+ invalid: InvalidControl[];
23
49
  };
24
50
  export type ScenarioQueryOptions = {
25
51
  /** Recorte de handoff. Sem ele, todo cenário registrado é visível. */
@@ -52,6 +78,21 @@ export type Registry = {
52
78
  screenOf: (scenario: Scenario | undefined) => ScreenNode | undefined;
53
79
  /** Telas permitidas pelo recorte, com variações também filtradas. */
54
80
  screensFor: (options?: ScenarioQueryOptions) => ScreenNode[];
81
+ /** Telas permitidas pelo recorte, agrupadas por fluxo (`route.group`). */
82
+ flows: (options?: ScenarioQueryOptions) => FlowNode[];
83
+ /** O fluxo de uma tela, com as telas dele permitidas pelo recorte. */
84
+ flowOf: (screen: ScreenNode | undefined, options?: ScenarioQueryOptions) => FlowNode | undefined;
85
+ /** Controles da tela, na ordem dos grupos. */
86
+ controlsOf: (screen: ScreenNode | undefined) => Control[];
87
+ /**
88
+ * Valores dos controles da tela: o padrão de cada controle, depois o que o
89
+ * cenário fixa, depois o que a URL pede. Pedido inválido cai no valor de baixo
90
+ * e volta em `invalid`.
91
+ */
92
+ resolveControls: (screen: ScreenNode | undefined, input?: {
93
+ scenario?: Scenario;
94
+ requested?: Record<string, string>;
95
+ }) => ControlResolution;
55
96
  /** Regras de um cenário, resolvidas e na ordem declarada. */
56
97
  rulesOf: (scenario: Scenario | undefined) => Rule[];
57
98
  /** Permissões efetivas: as do cenário, ou as da persona quando ausentes. */
@@ -65,18 +106,19 @@ export type Registry = {
65
106
  * caixa: "aprovacao" acha "Aprovação".
66
107
  */
67
108
  search: (query: string, options?: ScenarioQueryOptions) => Scenario[];
68
- /** Busca de telas: nome, descrição, rota e as variações de cada uma. */
109
+ /** Busca de telas: nome, descrição, rota, fluxo e as variações de cada uma. */
69
110
  searchScreens: (query: string, options?: ScenarioQueryOptions) => ScreenNode[];
70
111
  /** Busca de componentes: nome, descrição, grupo, id e `source`. */
71
112
  searchComponents: (query: string, handoff?: HandoffScope) => ComponentPreview[];
72
113
  /** Componentes permitidos pelo recorte; sem handoff devolve o catálogo. */
73
114
  componentsFor: (handoff?: HandoffScope) => ComponentPreview[];
74
115
  /**
75
- * Componentes usados por uma tela: a união de `components` das variações, na
76
- * ordem em que aparecem. Id sem componente registrado fica de fora.
116
+ * Componentes usados por uma tela: `route.components` e depois a união de
117
+ * `components` das variações, na ordem em que aparecem. Id sem componente
118
+ * registrado fica de fora.
77
119
  */
78
- componentsOfScreen: (screen: ScreenNode | undefined) => ComponentPreview[];
79
- /** Telas com ao menos um cenário que lista o componente em `components`. */
120
+ componentsOfScreen: (screen: ScreenNode | undefined, scenario?: Scenario) => ComponentPreview[];
121
+ /** Telas que listam o componente em `route.components` ou em um cenário. */
80
122
  usagesOf: (componentId: string | undefined, options?: ScenarioQueryOptions) => ScreenNode[];
81
123
  };
82
124
  export declare function createRegistry(product: ProductDefinition): Registry;
@@ -85,3 +127,24 @@ export declare function createRegistry(product: ProductDefinition): Registry;
85
127
  * A navegação usa exatamente a mesma regra do registry.
86
128
  */
87
129
  export declare function normalizeSearch(value: string): string;
130
+ /**
131
+ * Telas agrupadas por fluxo, na ordem em que cada fluxo aparece. As telas sem
132
+ * fluxo formam o primeiro grupo, sem nome.
133
+ */
134
+ export declare function groupScreens(screens: ScreenNode[]): FlowNode[];
135
+ /** Valor padrão de um controle: `default` quando é uma opção, senão a primeira. */
136
+ export declare function controlDefault(control: Control): string;
137
+ /**
138
+ * Resolve os valores de um conjunto de grupos de controles. Precedência, do mais
139
+ * fraco ao mais forte: padrão do controle, valor do cenário, pedido da URL. Um
140
+ * valor que não é opção do controle nunca é usado.
141
+ */
142
+ export declare function resolveScreenControls(groups: ControlGroup[], input?: {
143
+ scenario?: Scenario;
144
+ requested?: Record<string, string>;
145
+ }): ControlResolution;
146
+ /**
147
+ * `true` quando os valores atuais ainda são a combinação que o cenário fixa. É o
148
+ * que decide se o atalho aparece destacado depois de um controle mudar.
149
+ */
150
+ export declare function scenarioMatchesControls(scenario: Scenario | undefined, values: Record<string, string> | undefined): boolean;
@@ -1,10 +1,13 @@
1
1
  import { ComponentFixtureResolution, Registry, ScreenNode } from '../registry/index.js';
2
2
  import { DeployContext } from '../deploy/index.js';
3
- import { ComponentPreview, ControlsState, PanelTab, Scenario } from '../types/index.js';
3
+ import { DesignSpaceLocation } from '../controls/state.js';
4
+ import { ComponentPreview, Control, ControlsState, PanelTab, Scenario } from '../types/index.js';
4
5
  export type PanelProps = {
5
6
  registry: Registry;
6
7
  controls: ControlsState;
7
8
  deploy: DeployContext;
9
+ /** Endereço aberto: é o link da tela aberta no "Copiar para o PR". */
10
+ location: DesignSpaceLocation;
8
11
  screen: ScreenNode | undefined;
9
12
  /** Cenário ativo quando ele é variação da tela aberta. */
10
13
  variation: Scenario | undefined;
@@ -21,6 +24,11 @@ export type PanelProps = {
21
24
  onResizeEnd: () => void;
22
25
  };
23
26
  export declare function Panel(props: PanelProps): import("react").JSX.Element;
27
+ /**
28
+ * Até quatro opções curtas cabem como botões segmentados na largura do painel;
29
+ * acima disso, um select.
30
+ */
31
+ export declare function isSegmentedControl(control: Control): boolean;
24
32
  /** Cmd/Ctrl+F: o filtro do painel no lugar da busca do navegador. */
25
33
  export declare function isFilterShortcut(event: Pick<KeyboardEvent, "key" | "metaKey" | "ctrlKey" | "altKey" | "shiftKey">): boolean;
26
34
  /**
@@ -62,6 +62,12 @@ export type Labels = {
62
62
  fixturesOption: string;
63
63
  none: string;
64
64
  fixtureFallback: (requested: string, fallback: string) => string;
65
+ /** Título do bloco de persona, rede, tema, idioma e fonte de dados. */
66
+ context: string;
67
+ /** Título do bloco dos cenários da tela, depois dos controles. */
68
+ shortcuts: string;
69
+ toggleGroup: (group: string) => string;
70
+ openComponent: (component: string) => string;
65
71
  };
66
72
  info: {
67
73
  screen: string;
@@ -84,6 +90,8 @@ export type Labels = {
84
90
  rules: string;
85
91
  components: string;
86
92
  ticket: string;
93
+ flow: string;
94
+ controls: string;
87
95
  copyForPr: string;
88
96
  copiedForPr: string;
89
97
  copyPrompt: string;
@@ -94,6 +102,8 @@ export type Labels = {
94
102
  error: string;
95
103
  warning: string;
96
104
  close: string;
105
+ invalidControl: (id: string, value: string, fallback: string) => string;
106
+ unknownControl: (id: string, value: string) => string;
97
107
  };
98
108
  /** Texto do markdown gerado por "Copiar para o PR". */
99
109
  pr: {
@@ -106,6 +116,10 @@ export type Labels = {
106
116
  immutableLink: string;
107
117
  noExpected: string;
108
118
  empty: string;
119
+ open: string;
120
+ controls: string;
121
+ shortcuts: string;
122
+ defaultOption: string;
109
123
  };
110
124
  shell: {
111
125
  restoreChrome: string;
@@ -1,5 +1,5 @@
1
1
  import { DeployContext } from '../deploy/index.js';
2
- import { ScreenNode } from '../registry/index.js';
2
+ import { Registry, ScreenNode } from '../registry/index.js';
3
3
  import { ComponentPreview, ControlsState, Scenario } from '../types/index.js';
4
4
  import { Labels } from './labels.js';
5
5
  export type PrMarkdownInput = {
@@ -13,3 +13,31 @@ export type PrMarkdownInput = {
13
13
  overrides?: Partial<ControlsState>;
14
14
  };
15
15
  export declare function buildPrMarkdown({ screen, variations, components, deploy, labels, overrides, }: PrMarkdownInput): string;
16
+ export type FlowPrMarkdownInput = {
17
+ /** O fluxo da tela aberta, com as telas visíveis no recorte ativo. */
18
+ flow: {
19
+ name: string;
20
+ screens: ScreenNode[];
21
+ };
22
+ registry: Registry;
23
+ /** A tela aberta: o link dela leva os controles atuais. */
24
+ open?: {
25
+ screen: ScreenNode;
26
+ location: {
27
+ path: string;
28
+ search: string;
29
+ };
30
+ variation?: Scenario;
31
+ };
32
+ deploy: DeployContext;
33
+ labels: Labels;
34
+ /** Controles que os links precisam carregar, como o recorte de handoff. */
35
+ overrides?: Partial<ControlsState>;
36
+ };
37
+ /**
38
+ * Markdown de um fluxo inteiro: um PR de feature costuma trazer as telas do
39
+ * fluxo juntas, e a pessoa desenvolvedora precisa ver a sequência, não uma tela
40
+ * solta. Para cada tela: nome, rota, link, controles disponíveis, atalhos,
41
+ * comportamento esperado e a tabela de componentes.
42
+ */
43
+ export declare function buildFlowPrMarkdown({ flow, registry, open, deploy, labels, overrides, }: FlowPrMarkdownInput): string;
package/dist/testing.js CHANGED
@@ -1,4 +1,4 @@
1
- import { F as s, v as t, u as i, q as a, s as n } from "./index-FIzKHaWE.js";
1
+ import { F as s, v as t, y as i, x as a, s as n } from "./index-DxIx4GAk.js";
2
2
  function c(o = "http://localhost:5173") {
3
3
  const r = typeof process < "u" ? process.env : {};
4
4
  return (r.PREVIEW_URL || r.BASE_URL || o).replace(/\/$/, "");
@@ -94,6 +94,39 @@ export type Scenario = {
94
94
  * "Copiar para o PR".
95
95
  */
96
96
  components?: string[];
97
+ /**
98
+ * Valores de controle que este cenário fixa: um atalho para uma combinação.
99
+ * Abrir o cenário aplica estes valores sobre os padrões da tela. Chave é o id
100
+ * de um `Control` da tela do cenário; valor, o `value` de uma das opções.
101
+ */
102
+ controls?: Record<string, string>;
103
+ };
104
+ /** Uma opção de um controle. */
105
+ export type ControlOption = {
106
+ value: string;
107
+ label: string;
108
+ };
109
+ /** Um controle: uma dimensão de variação de um componente da tela. */
110
+ export type Control = {
111
+ /** Id estável, único dentro da tela; vira parâmetro de URL `c.<id>`. */
112
+ id: string;
113
+ label: string;
114
+ options: ControlOption[];
115
+ /** Valor inicial; padrão = primeira opção. */
116
+ default?: string;
117
+ description?: string;
118
+ };
119
+ /** Grupo de controles de um componente da tela, como no painel Variações. */
120
+ export type ControlGroup = {
121
+ /** Id estável, único dentro da tela. */
122
+ id: string;
123
+ /** "Tabela de pedidos · table". */
124
+ title: string;
125
+ /** Id de um ComponentPreview do catálogo, quando o grupo é de um componente dele. */
126
+ component?: string;
127
+ controls: Control[];
128
+ /** Uma linha de contexto, exibida sob o título. */
129
+ note?: string;
97
130
  };
98
131
  /**
99
132
  * Rota declarativa do produto. O motor casa `path` contra a URL e renderiza
@@ -112,6 +145,20 @@ export type RouteDefinition = {
112
145
  name?: string;
113
146
  /** Uma linha sobre a tela, exibida em Informações e usada na busca. */
114
147
  description?: string;
148
+ /**
149
+ * Fluxo a que a tela pertence: agrupa as telas na aba Telas, como `group`
150
+ * agrupa componentes. Tela sem fluxo fica num grupo sem título, no topo.
151
+ */
152
+ group?: string;
153
+ /** Controles por componente, exibidos no painel Variações. */
154
+ controls?: ControlGroup[];
155
+ /**
156
+ * Comportamento esperado da tela, para Informações e "Copiar para o PR"
157
+ * quando não há cenário ativo.
158
+ */
159
+ expected?: string[];
160
+ /** Ids do catálogo usados pela tela (mesmo papel de `Scenario.components`). */
161
+ components?: string[];
115
162
  };
116
163
  export type ScreenProps = {
117
164
  /** Parâmetros dinâmicos casados da rota. */
@@ -314,6 +361,16 @@ export type ScenarioContext = {
314
361
  navigate: (to: string) => void;
315
362
  /** Abre outro cenário por id. */
316
363
  openScenario: (scenarioId: string) => void;
364
+ /**
365
+ * Valor atual de cada controle da tela (id → value), com os padrões
366
+ * aplicados. Vazio quando a tela não declara controles.
367
+ */
368
+ controls: Record<string, string>;
369
+ /**
370
+ * Muda um controle a partir da UI do produto (ex.: fechar um modal volta o
371
+ * controle de sobreposição para "nenhuma"). Atualiza a URL.
372
+ */
373
+ setControl: (id: string, value: string) => void;
317
374
  };
318
375
  export type ViewportSetting = {
319
376
  /** `mobile`, `tablet`, `desktop`, `fit` ou `custom` (só por URL). */
@@ -369,6 +426,11 @@ export type ControlsState = {
369
426
  zoom?: number;
370
427
  /** Viewport girado: largura e altura trocadas quando o preset tem altura. */
371
428
  rotated?: boolean;
429
+ /**
430
+ * Valores dos controles da tela aberta (id → value), já com os padrões e o
431
+ * cenário aplicados. Na URL, só o que difere vai como `c.<id>=<value>`.
432
+ */
433
+ screenControls?: Record<string, string>;
372
434
  };
373
435
  /** Abas do painel direito do chrome. */
374
436
  export type PanelTab = "variations" | "info";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@brucesantos/design-space",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "Motor neutro do Bananas Design Space: telas como rotas com variações, catálogo de componentes, chrome em preto e branco com a UI do produto num iframe, deep links e controles de persona/viewport/rede. Não contém UI de cliente.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -1,345 +0,0 @@
1
- const $ = [
2
- "success",
3
- "loading",
4
- "empty",
5
- "error",
6
- "slow"
7
- ], y = /^[a-z0-9]+([.\-][a-z0-9]+)*$/;
8
- function f(e) {
9
- return typeof e == "string" && e.trim().length > 0;
10
- }
11
- function I(e, o) {
12
- const t = [], r = f(e?.id) ? `scenario:${e.id}` : `scenario[${o ?? "?"}]`, a = (c) => t.push({ level: "error", where: r, message: c }), s = (c) => t.push({ level: "warning", where: r, message: c });
13
- return f(e?.id) ? y.test(e.id) || a(
14
- "`id` deve ser minúsculo, em kebab-case, com pontos opcionais: `requests.approve-blocked` ou `approve-blocked`."
15
- ) : a("`id` é obrigatório."), f(e?.title) || a("`title` é obrigatório e deve usar o vocabulário do negócio."), f(e?.route) ? e.route.startsWith("/") || a("`route` deve começar com `/`.") : a("`route` é obrigatório."), e?.persona !== void 0 && !f(e.persona) && a("`persona`, quando informada, deve ser o id de uma persona registrada."), f(e?.fixture) || a("`fixture` é obrigatório. O padrão do ambiente é dado sintético (D-05)."), e?.components !== void 0 && !Array.isArray(e.components) && a("`components`, quando informado, deve ser uma lista de ids de componente."), e?.network && !$.includes(e.network) && a(`\`network\` deve ser um de: ${$.join(", ")}.`), e?.expected?.length || s(
16
- "Sem `expected`, o cenário não vira caso verificável no handoff — é tela bonita sem critério (risco: prototype theater)."
17
- ), t;
18
- }
19
- function W(e) {
20
- const o = [], t = (u, n, i) => o.push({ level: u, where: n, message: i }), r = new Set(e.personas?.map((u) => u.id) ?? []), a = new Set(e.fixtures?.map((u) => u.id) ?? []), s = new Set(e.rules?.map((u) => u.id) ?? []), c = /* @__PURE__ */ new Set();
21
- f(e.id) || t("error", "product", "`id` é obrigatório."), f(e.name) || t("error", "product", "`name` é obrigatório."), !e.routes?.length && e.scenarios?.length && t("error", "product", "`routes` está vazio: nenhum cenário conseguirá renderizar."), "modules" in e && t(
22
- "warning",
23
- "product",
24
- "`modules` foi removido na 0.8.0 e é ignorado: cada rota é uma tela, e os cenários da rota são as variações dela."
25
- );
26
- const h = /* @__PURE__ */ new Set();
27
- for (const [u, n] of (e.routes ?? []).entries()) {
28
- const i = `route:${n?.path ?? u}`;
29
- if (!f(n?.path)) {
30
- t("error", i, "`path` é obrigatório.");
31
- continue;
32
- }
33
- n.path.startsWith("/") || t("error", i, "`path` deve começar com `/`."), h.has(n.path) && t("error", i, `\`path\` duplicado: ${n.path}. Cada rota é uma tela.`), h.add(n.path), typeof n.screen != "function" && typeof n.screen != "object" && t("error", i, "`screen` é obrigatório."), n.name !== void 0 && !f(n.name) && t("warning", i, "`name` vazio: a tela aparece com o título do primeiro cenário.");
34
- }
35
- const x = /* @__PURE__ */ new Set();
36
- for (const [u, n] of (e.components ?? []).entries()) {
37
- const i = `component:${n?.id ?? u}`;
38
- f(n?.id) ? y.test(n.id) ? x.has(n.id) ? t("error", i, `\`id\` duplicado: ${n.id}.`) : x.add(n.id) : t("error", i, "`id` deve ser minúsculo em kebab-case ou usar pontos para agrupamento.") : t("error", i, "`id` é obrigatório."), f(n?.name) || t("error", i, "`name` é obrigatório."), typeof n?.preview != "function" && typeof n?.preview != "object" && t("error", i, "`preview` é obrigatório."), n?.source !== void 0 && typeof n.source != "string" && t("error", i, "`source`, quando informado, é texto livre.");
39
- const m = /* @__PURE__ */ new Set();
40
- for (const [F, l] of (n?.fixtures ?? []).entries()) {
41
- const g = `${i}/fixture:${l?.id ?? F}`;
42
- f(l?.id) ? y.test(l.id) ? m.has(l.id) ? t("error", g, `Id de fixture do componente duplicado: \`${l.id}\`.`) : m.add(l.id) : t(
43
- "error",
44
- g,
45
- `Id de fixture do componente inválido: \`${l.id}\`. Use minúsculas em kebab-case.`
46
- ) : t("error", g, "`id` da fixture do componente é obrigatório."), f(l?.label) || t("error", g, "`label` da fixture do componente é obrigatório."), (!l || !("data" in l)) && t("error", g, "`data` da fixture do componente é obrigatório.");
47
- }
48
- n?.defaultFixture && !m.has(n.defaultFixture) && t(
49
- "error",
50
- i,
51
- `\`defaultFixture\` aponta para fixture inexistente: \`${n.defaultFixture}\`.`
52
- );
53
- }
54
- for (const [u, n] of (e.scenarios ?? []).entries()) {
55
- o.push(...I(n, u));
56
- const i = `scenario:${n?.id ?? u}`;
57
- n?.id && (c.has(n.id) && t("error", i, `\`id\` duplicado: ${n.id}.`), c.add(n.id)), n?.persona && !r.has(n.persona) && t("error", i, `Persona não registrada: \`${n.persona}\`.`), n?.fixture && !a.has(n.fixture) && t("error", i, `Fixture não registrada: \`${n.fixture}\`.`);
58
- for (const m of n?.rules ?? [])
59
- s.has(m) || t("error", i, `Regra não registrada: \`${m}\`.`);
60
- for (const m of Array.isArray(n?.components) ? n.components : [])
61
- x.has(m) || t(
62
- "warning",
63
- i,
64
- `Componente não registrado: \`${m}\`. Ele não aparece em "Componentes usados".`
65
- );
66
- n?.route && !z(n.route, e) && t(
67
- "error",
68
- i,
69
- `Rota \`${n.route}\` não casa com nenhuma rota declarada. O deep link abriria a tela de rota inexistente.`
70
- );
71
- }
72
- const v = e.dataSources?.default;
73
- return v && v !== "fixtures" && (new Set(e.dataSources?.adapters?.map((n) => n.id) ?? []).has(v) || t("error", "product", `\`dataSources.default\` aponta para adapter inexistente: \`${v}\`.`), t(
74
- "warning",
75
- "product",
76
- "A fonte padrão não é `fixtures`. O padrão do ambiente é dado sintético e determinístico (D-05); API real entra como adapter opcional, com justificativa."
77
- )), o;
78
- }
79
- function z(e, o) {
80
- const t = e.split("?")[0] ?? e;
81
- return (o.routes ?? []).some((r) => M(r.path, t));
82
- }
83
- function M(e, o) {
84
- const t = e.split("/").filter(Boolean), r = o.split("/").filter(Boolean);
85
- for (const [a, s] of t.entries()) {
86
- if (s === "*") return !0;
87
- const c = r[a];
88
- if (c === void 0) return !1;
89
- if (!s.startsWith(":") && s !== c)
90
- return !1;
91
- }
92
- return t.length === r.length;
93
- }
94
- function q(e) {
95
- return e.some((o) => o.level === "error");
96
- }
97
- function N(e) {
98
- return e.length === 0 ? "Nenhum problema encontrado." : e.map((o) => `${o.level === "error" ? "✖" : "▲"} ${o.where}
99
- ${o.message}`).join(`
100
- `);
101
- }
102
- function P(e, o) {
103
- const t = e.split("/").filter(Boolean), r = T(o).split("/").filter(Boolean), a = {};
104
- for (const [s, c] of t.entries()) {
105
- if (c === "*")
106
- return a["*"] = r.slice(s).join("/"), a;
107
- const h = r[s];
108
- if (h === void 0) return null;
109
- if (c.startsWith(":")) {
110
- a[c.slice(1)] = h;
111
- continue;
112
- }
113
- if (c !== h) return null;
114
- }
115
- return t.length !== r.length ? null : a;
116
- }
117
- function _(e, o) {
118
- const t = [...e].sort((r, a) => A(a.path) - A(r.path));
119
- for (const r of t) {
120
- const a = P(r.path, o);
121
- if (a) return { definition: r, params: a };
122
- }
123
- }
124
- function A(e) {
125
- const o = e.split("/").filter(Boolean);
126
- let t = o.length;
127
- for (const r of o)
128
- r === "*" ? t -= 2 : r.startsWith(":") ? t += 1 : t += 4;
129
- return t;
130
- }
131
- function T(e) {
132
- const o = e.split("?")[0] ?? e;
133
- try {
134
- return decodeURI(o);
135
- } catch {
136
- return o;
137
- }
138
- }
139
- const p = {
140
- enabled: "handoff",
141
- scenario: "allowScenario",
142
- route: "allowRoute",
143
- component: "allowComponent"
144
- };
145
- function D(e) {
146
- if (e.get(p.enabled) === "1")
147
- return R({
148
- scenarios: e.getAll(p.scenario),
149
- routes: e.getAll(p.route),
150
- components: e.getAll(p.component)
151
- });
152
- }
153
- function C(e, o) {
154
- for (const r of Object.values(p)) e.delete(r);
155
- if (!o) return;
156
- e.set(p.enabled, "1");
157
- const t = R(o);
158
- for (const r of t.scenarios ?? []) e.append(p.scenario, r);
159
- for (const r of t.routes ?? []) e.append(p.route, r);
160
- for (const r of t.components ?? []) e.append(p.component, r);
161
- }
162
- function R(e) {
163
- const o = b(e.scenarios), t = b(e.routes), r = b(e.components);
164
- return {
165
- ...o.length ? { scenarios: o } : {},
166
- ...t.length ? { routes: t } : {},
167
- ...r.length ? { components: r } : {}
168
- };
169
- }
170
- function E(e, o) {
171
- return !e || !!(o && e.scenarios?.includes(o));
172
- }
173
- function H(e, o) {
174
- return !e || !!(o && e.components?.includes(o));
175
- }
176
- function K(e, o, t = []) {
177
- return !e || o === "/" ? !0 : [
178
- ...e.routes ?? [],
179
- ...t.filter((a) => E(e, a.id)).map((a) => a.route)
180
- ].some((a) => P(a, o) !== null);
181
- }
182
- function b(e) {
183
- return [...new Set((e ?? []).map((o) => o.trim()).filter(Boolean))].sort();
184
- }
185
- const d = {
186
- scenario: "scenario",
187
- component: "component",
188
- persona: "persona",
189
- fixture: "fixture",
190
- network: "network",
191
- viewport: "viewport",
192
- customWidth: "w",
193
- themeMode: "theme",
194
- locale: "locale",
195
- dataSource: "source",
196
- chromeTheme: "appearance",
197
- chrome: "chrome",
198
- inspector: "panel",
199
- panelTab: "tab",
200
- zoom: "zoom",
201
- rotated: "rotate"
202
- };
203
- function j(e) {
204
- return typeof e == "boolean" ? e ? "1" : "0" : String(e);
205
- }
206
- function U(e, o = {}) {
207
- for (const [t, r] of Object.entries(o)) {
208
- if (r == null) continue;
209
- if (t === "handoff") {
210
- C(e, r);
211
- continue;
212
- }
213
- const a = d[t];
214
- a && e.set(a, j(r));
215
- }
216
- }
217
- const w = "ds-frame", B = "data-ds-frame", k = [
218
- d.chromeTheme,
219
- d.chrome,
220
- d.inspector,
221
- d.panelTab,
222
- d.zoom,
223
- d.rotated
224
- ];
225
- function Q(e, o) {
226
- const t = new URLSearchParams(o);
227
- for (const r of k) t.delete(r);
228
- return t.delete(w), t.set(w, "1"), `${e || "/"}?${t.toString()}`;
229
- }
230
- function V(e) {
231
- const o = new URL(e, "http://design-space.invalid");
232
- o.searchParams.delete(w);
233
- const t = o.searchParams.toString();
234
- return { path: o.pathname || "/", search: t ? `?${t}` : "" };
235
- }
236
- function Y(e) {
237
- const o = new URL(e, "http://design-space.invalid");
238
- return `${o.pathname}|${o.searchParams.get(d.component) ?? ""}`;
239
- }
240
- function G(e, o) {
241
- const t = new URLSearchParams(e), r = new URLSearchParams(o);
242
- t.delete(w);
243
- for (const s of k) {
244
- t.delete(s);
245
- const c = r.get(s);
246
- c !== null && t.set(s, c);
247
- }
248
- const a = t.toString();
249
- return a ? `?${a}` : "";
250
- }
251
- function L(e) {
252
- if (!e || typeof e != "object") return !1;
253
- const o = e;
254
- if (o.ds !== 1 || typeof o.type != "string") return !1;
255
- switch (o.type) {
256
- case "ready":
257
- case "location":
258
- return typeof o.url == "string";
259
- case "navigate":
260
- return typeof o.url == "string";
261
- case "shortcut":
262
- return ["C", "K", "F"].includes(o.key);
263
- default:
264
- return !1;
265
- }
266
- }
267
- function J(e, o) {
268
- if (e.origin === o.origin && !(!o.source || e.source !== o.source))
269
- return L(e.data) ? e.data : void 0;
270
- }
271
- function X(e, o, t) {
272
- try {
273
- e?.postMessage(o, t);
274
- } catch {
275
- }
276
- }
277
- function Z(e = typeof window > "u" ? void 0 : window) {
278
- if (!e) return !1;
279
- if (new URLSearchParams(e.location.search).get(w) === "1") return !0;
280
- try {
281
- return !!e.frameElement?.hasAttribute(B);
282
- } catch {
283
- return !1;
284
- }
285
- }
286
- function S(e = {}) {
287
- const o = e.branchUrl || void 0, t = e.deploymentUrl || void 0, r = e.commit || void 0, a = e.env || "development", s = o && `https://${o}` || t && `https://${t}` || (typeof window < "u" ? window.location.origin : "http://localhost:5173");
288
- return {
289
- env: a,
290
- origin: s.replace(/\/$/, ""),
291
- branchUrl: o,
292
- deploymentUrl: t,
293
- branch: e.branch || void 0,
294
- commit: r,
295
- shortCommit: r?.slice(0, 7),
296
- isDeployed: a === "preview" || a === "production"
297
- };
298
- }
299
- function O(e, o = {}) {
300
- const t = o.origin ?? S().origin, r = new URL(e.route, t);
301
- return r.searchParams.set(d.scenario, e.id), e.persona && r.searchParams.set(d.persona, e.persona), r.searchParams.set(d.fixture, e.fixture), e.network && e.network !== "success" && r.searchParams.set(d.network, e.network), U(r.searchParams, o.overrides), r.toString();
302
- }
303
- function ee(e, o = {}) {
304
- const t = o.origin ?? S().origin, r = new URL("/", t), a = o.fixture ?? e.fixtures?.find((s) => s.id === e.defaultFixture)?.id ?? e.fixtures?.[0]?.id;
305
- return r.searchParams.set(d.component, e.id), a && r.searchParams.set(d.fixture, a), U(r.searchParams, o.overrides), r.toString();
306
- }
307
- function te(e, o) {
308
- const t = o.commit ?? S().commit;
309
- if (!t) return;
310
- const r = o.template.replaceAll("{shortCommit}", t.slice(0, 7)).replaceAll("{commit}", t);
311
- return O(e, { origin: r });
312
- }
313
- export {
314
- B as F,
315
- p as H,
316
- $ as N,
317
- d as P,
318
- H as a,
319
- K as b,
320
- C as c,
321
- X as d,
322
- J as e,
323
- V as f,
324
- U as g,
325
- E as h,
326
- Y as i,
327
- Z as j,
328
- S as k,
329
- w as l,
330
- G as m,
331
- te as n,
332
- ee as o,
333
- D as p,
334
- N as q,
335
- _ as r,
336
- O as s,
337
- Q as t,
338
- q as u,
339
- W as v,
340
- P as w,
341
- R as x,
342
- j as y,
343
- I as z
344
- };
345
- //# sourceMappingURL=index-FIzKHaWE.js.map