@cratis/scene.blueprint.default 4.31.0 → 4.33.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 (226) hide show
  1. package/ComponentName.ts +24 -0
  2. package/defaultBlueprint.ts +2 -1
  3. package/defaultBlueprintComponentMetadata.ts +2 -0
  4. package/defaultBlueprintComponents.ts +9 -0
  5. package/dist/cjs/ComponentName.js +8 -0
  6. package/dist/cjs/ComponentName.js.map +1 -1
  7. package/dist/cjs/defaultBlueprint.js +9 -5
  8. package/dist/cjs/defaultBlueprint.js.map +1 -1
  9. package/dist/cjs/defaultBlueprintComponentMetadata.js +8 -0
  10. package/dist/cjs/defaultBlueprintComponentMetadata.js.map +1 -1
  11. package/dist/cjs/defaultBlueprintComponents.js +21 -1
  12. package/dist/cjs/defaultBlueprintComponents.js.map +1 -1
  13. package/dist/cjs/foundation/ActionButton.js +33 -0
  14. package/dist/cjs/foundation/ActionButton.js.map +1 -0
  15. package/dist/cjs/foundation/ChartWrapper.js +520 -0
  16. package/dist/cjs/foundation/ChartWrapper.js.map +1 -0
  17. package/dist/cjs/foundation/ColumnChooser.js +156 -0
  18. package/dist/cjs/foundation/ColumnChooser.js.map +1 -0
  19. package/dist/cjs/foundation/ComponentState.js +42 -0
  20. package/dist/cjs/foundation/ComponentState.js.map +1 -0
  21. package/dist/cjs/foundation/EmptyState.js +31 -0
  22. package/dist/cjs/foundation/EmptyState.js.map +1 -0
  23. package/dist/cjs/foundation/FilterBuilder.js +307 -0
  24. package/dist/cjs/foundation/FilterBuilder.js.map +1 -0
  25. package/dist/cjs/foundation/FoundationIcon.js +58 -0
  26. package/dist/cjs/foundation/FoundationIcon.js.map +1 -0
  27. package/dist/cjs/foundation/FoundationStates.js +62 -0
  28. package/dist/cjs/foundation/FoundationStates.js.map +1 -0
  29. package/dist/cjs/foundation/PermissionRule.js +22 -0
  30. package/dist/cjs/foundation/PermissionRule.js.map +1 -0
  31. package/dist/cjs/foundation/SavedViewsMenu.js +199 -0
  32. package/dist/cjs/foundation/SavedViewsMenu.js.map +1 -0
  33. package/dist/cjs/foundation/StatCard.js +61 -0
  34. package/dist/cjs/foundation/StatCard.js.map +1 -0
  35. package/dist/cjs/foundation/StateFrame.js +200 -0
  36. package/dist/cjs/foundation/StateFrame.js.map +1 -0
  37. package/dist/cjs/foundation/StatusChip.js +64 -0
  38. package/dist/cjs/foundation/StatusChip.js.map +1 -0
  39. package/dist/cjs/foundation/TrendChip.js +93 -0
  40. package/dist/cjs/foundation/TrendChip.js.map +1 -0
  41. package/dist/cjs/foundation/chartGeometry.js +101 -0
  42. package/dist/cjs/foundation/chartGeometry.js.map +1 -0
  43. package/dist/cjs/foundation/columnModel.js +43 -0
  44. package/dist/cjs/foundation/columnModel.js.map +1 -0
  45. package/dist/cjs/foundation/filterModel.js +123 -0
  46. package/dist/cjs/foundation/filterModel.js.map +1 -0
  47. package/dist/cjs/foundation/formatting.js +85 -0
  48. package/dist/cjs/foundation/formatting.js.map +1 -0
  49. package/dist/cjs/foundation/foundationComponentMetadata.js +69 -0
  50. package/dist/cjs/foundation/foundationComponentMetadata.js.map +1 -0
  51. package/dist/cjs/foundation/foundationDescriptors.js +385 -0
  52. package/dist/cjs/foundation/foundationDescriptors.js.map +1 -0
  53. package/dist/cjs/foundation/foundationSamples.js +201 -0
  54. package/dist/cjs/foundation/foundationSamples.js.map +1 -0
  55. package/dist/cjs/foundation/foundationStrings.js +130 -0
  56. package/dist/cjs/foundation/foundationStrings.js.map +1 -0
  57. package/dist/cjs/foundation/useElementWidth.js +31 -0
  58. package/dist/cjs/foundation/useElementWidth.js.map +1 -0
  59. package/dist/cjs/foundation/viewModel.js +24 -0
  60. package/dist/cjs/foundation/viewModel.js.map +1 -0
  61. package/dist/cjs/index.js +90 -0
  62. package/dist/cjs/index.js.map +1 -1
  63. package/dist/cjs/themes/dark.js +9 -1
  64. package/dist/cjs/themes/dark.js.map +1 -1
  65. package/dist/cjs/themes/light.js +10 -2
  66. package/dist/cjs/themes/light.js.map +1 -1
  67. package/dist/esm/ComponentName.d.ts +9 -1
  68. package/dist/esm/ComponentName.d.ts.map +1 -1
  69. package/dist/esm/ComponentName.js +8 -0
  70. package/dist/esm/ComponentName.js.map +1 -1
  71. package/dist/esm/defaultBlueprint.d.ts.map +1 -1
  72. package/dist/esm/defaultBlueprint.js +9 -5
  73. package/dist/esm/defaultBlueprint.js.map +1 -1
  74. package/dist/esm/defaultBlueprintComponentMetadata.d.ts.map +1 -1
  75. package/dist/esm/defaultBlueprintComponentMetadata.js +8 -0
  76. package/dist/esm/defaultBlueprintComponentMetadata.js.map +1 -1
  77. package/dist/esm/defaultBlueprintComponents.d.ts.map +1 -1
  78. package/dist/esm/defaultBlueprintComponents.js +21 -1
  79. package/dist/esm/defaultBlueprintComponents.js.map +1 -1
  80. package/dist/esm/foundation/ActionButton.d.ts +13 -0
  81. package/dist/esm/foundation/ActionButton.d.ts.map +1 -0
  82. package/dist/esm/foundation/ActionButton.js +31 -0
  83. package/dist/esm/foundation/ActionButton.js.map +1 -0
  84. package/dist/esm/foundation/ChartWrapper.d.ts +5 -0
  85. package/dist/esm/foundation/ChartWrapper.d.ts.map +1 -0
  86. package/dist/esm/foundation/ChartWrapper.js +517 -0
  87. package/dist/esm/foundation/ChartWrapper.js.map +1 -0
  88. package/dist/esm/foundation/ColumnChooser.d.ts +3 -0
  89. package/dist/esm/foundation/ColumnChooser.d.ts.map +1 -0
  90. package/dist/esm/foundation/ColumnChooser.js +154 -0
  91. package/dist/esm/foundation/ColumnChooser.js.map +1 -0
  92. package/dist/esm/foundation/ComponentState.d.ts +12 -0
  93. package/dist/esm/foundation/ComponentState.d.ts.map +1 -0
  94. package/dist/esm/foundation/ComponentState.js +38 -0
  95. package/dist/esm/foundation/ComponentState.js.map +1 -0
  96. package/dist/esm/foundation/EmptyState.d.ts +3 -0
  97. package/dist/esm/foundation/EmptyState.d.ts.map +1 -0
  98. package/dist/esm/foundation/EmptyState.js +29 -0
  99. package/dist/esm/foundation/EmptyState.js.map +1 -0
  100. package/dist/esm/foundation/FilterBuilder.d.ts +3 -0
  101. package/dist/esm/foundation/FilterBuilder.d.ts.map +1 -0
  102. package/dist/esm/foundation/FilterBuilder.js +305 -0
  103. package/dist/esm/foundation/FilterBuilder.js.map +1 -0
  104. package/dist/esm/foundation/Foundation.stories.d.ts +37 -0
  105. package/dist/esm/foundation/Foundation.stories.d.ts.map +1 -0
  106. package/dist/esm/foundation/Foundation.stories.js +34 -0
  107. package/dist/esm/foundation/Foundation.stories.js.map +1 -0
  108. package/dist/esm/foundation/FoundationIcon.d.ts +7 -0
  109. package/dist/esm/foundation/FoundationIcon.d.ts.map +1 -0
  110. package/dist/esm/foundation/FoundationIcon.js +55 -0
  111. package/dist/esm/foundation/FoundationIcon.js.map +1 -0
  112. package/dist/esm/foundation/FoundationStates.d.ts +8 -0
  113. package/dist/esm/foundation/FoundationStates.d.ts.map +1 -0
  114. package/dist/esm/foundation/FoundationStates.js +60 -0
  115. package/dist/esm/foundation/FoundationStates.js.map +1 -0
  116. package/dist/esm/foundation/PermissionRule.d.ts +8 -0
  117. package/dist/esm/foundation/PermissionRule.d.ts.map +1 -0
  118. package/dist/esm/foundation/PermissionRule.js +19 -0
  119. package/dist/esm/foundation/PermissionRule.js.map +1 -0
  120. package/dist/esm/foundation/SavedViewsMenu.d.ts +4 -0
  121. package/dist/esm/foundation/SavedViewsMenu.d.ts.map +1 -0
  122. package/dist/esm/foundation/SavedViewsMenu.js +196 -0
  123. package/dist/esm/foundation/SavedViewsMenu.js.map +1 -0
  124. package/dist/esm/foundation/StatCard.d.ts +3 -0
  125. package/dist/esm/foundation/StatCard.d.ts.map +1 -0
  126. package/dist/esm/foundation/StatCard.js +59 -0
  127. package/dist/esm/foundation/StatCard.js.map +1 -0
  128. package/dist/esm/foundation/StateFrame.d.ts +15 -0
  129. package/dist/esm/foundation/StateFrame.d.ts.map +1 -0
  130. package/dist/esm/foundation/StateFrame.js +197 -0
  131. package/dist/esm/foundation/StateFrame.js.map +1 -0
  132. package/dist/esm/foundation/StatusChip.d.ts +13 -0
  133. package/dist/esm/foundation/StatusChip.d.ts.map +1 -0
  134. package/dist/esm/foundation/StatusChip.js +59 -0
  135. package/dist/esm/foundation/StatusChip.js.map +1 -0
  136. package/dist/esm/foundation/TrendChip.d.ts +18 -0
  137. package/dist/esm/foundation/TrendChip.d.ts.map +1 -0
  138. package/dist/esm/foundation/TrendChip.js +88 -0
  139. package/dist/esm/foundation/TrendChip.js.map +1 -0
  140. package/dist/esm/foundation/chartGeometry.d.ts +34 -0
  141. package/dist/esm/foundation/chartGeometry.d.ts.map +1 -0
  142. package/dist/esm/foundation/chartGeometry.js +93 -0
  143. package/dist/esm/foundation/chartGeometry.js.map +1 -0
  144. package/dist/esm/foundation/columnModel.d.ts +11 -0
  145. package/dist/esm/foundation/columnModel.d.ts.map +1 -0
  146. package/dist/esm/foundation/columnModel.js +38 -0
  147. package/dist/esm/foundation/columnModel.js.map +1 -0
  148. package/dist/esm/foundation/filterModel.d.ts +33 -0
  149. package/dist/esm/foundation/filterModel.d.ts.map +1 -0
  150. package/dist/esm/foundation/filterModel.js +112 -0
  151. package/dist/esm/foundation/filterModel.js.map +1 -0
  152. package/dist/esm/foundation/formatting.d.ts +13 -0
  153. package/dist/esm/foundation/formatting.d.ts.map +1 -0
  154. package/dist/esm/foundation/formatting.js +78 -0
  155. package/dist/esm/foundation/formatting.js.map +1 -0
  156. package/dist/esm/foundation/foundationComponentMetadata.d.ts +3 -0
  157. package/dist/esm/foundation/foundationComponentMetadata.d.ts.map +1 -0
  158. package/dist/esm/foundation/foundationComponentMetadata.js +67 -0
  159. package/dist/esm/foundation/foundationComponentMetadata.js.map +1 -0
  160. package/dist/esm/foundation/foundationDescriptors.d.ts +6 -0
  161. package/dist/esm/foundation/foundationDescriptors.d.ts.map +1 -0
  162. package/dist/esm/foundation/foundationDescriptors.js +380 -0
  163. package/dist/esm/foundation/foundationDescriptors.js.map +1 -0
  164. package/dist/esm/foundation/foundationSamples.d.ts +10 -0
  165. package/dist/esm/foundation/foundationSamples.d.ts.map +1 -0
  166. package/dist/esm/foundation/foundationSamples.js +198 -0
  167. package/dist/esm/foundation/foundationSamples.js.map +1 -0
  168. package/dist/esm/foundation/foundationStrings.d.ts +103 -0
  169. package/dist/esm/foundation/foundationStrings.d.ts.map +1 -0
  170. package/dist/esm/foundation/foundationStrings.js +126 -0
  171. package/dist/esm/foundation/foundationStrings.js.map +1 -0
  172. package/dist/esm/foundation/index.d.ts +25 -0
  173. package/dist/esm/foundation/index.d.ts.map +1 -0
  174. package/dist/esm/foundation/index.js +25 -0
  175. package/dist/esm/foundation/index.js.map +1 -0
  176. package/dist/esm/foundation/useElementWidth.d.ts +3 -0
  177. package/dist/esm/foundation/useElementWidth.d.ts.map +1 -0
  178. package/dist/esm/foundation/useElementWidth.js +29 -0
  179. package/dist/esm/foundation/useElementWidth.js.map +1 -0
  180. package/dist/esm/foundation/viewModel.d.ts +7 -0
  181. package/dist/esm/foundation/viewModel.d.ts.map +1 -0
  182. package/dist/esm/foundation/viewModel.js +22 -0
  183. package/dist/esm/foundation/viewModel.js.map +1 -0
  184. package/dist/esm/gallery/widgets.js +1 -1
  185. package/dist/esm/index.d.ts +1 -0
  186. package/dist/esm/index.d.ts.map +1 -1
  187. package/dist/esm/index.js +24 -0
  188. package/dist/esm/index.js.map +1 -1
  189. package/dist/esm/themes/dark.d.ts.map +1 -1
  190. package/dist/esm/themes/dark.js +9 -1
  191. package/dist/esm/themes/dark.js.map +1 -1
  192. package/dist/esm/themes/light.d.ts.map +1 -1
  193. package/dist/esm/themes/light.js +10 -2
  194. package/dist/esm/themes/light.js.map +1 -1
  195. package/dist/esm/tsconfig.tsbuildinfo +1 -1
  196. package/foundation/ActionButton.tsx +39 -0
  197. package/foundation/ChartWrapper.tsx +252 -0
  198. package/foundation/ColumnChooser.tsx +73 -0
  199. package/foundation/ComponentState.ts +53 -0
  200. package/foundation/EmptyState.tsx +22 -0
  201. package/foundation/FilterBuilder.tsx +144 -0
  202. package/foundation/Foundation.stories.tsx +46 -0
  203. package/foundation/FoundationIcon.tsx +49 -0
  204. package/foundation/FoundationStates.tsx +46 -0
  205. package/foundation/PermissionRule.ts +26 -0
  206. package/foundation/SavedViewsMenu.tsx +94 -0
  207. package/foundation/StatCard.tsx +44 -0
  208. package/foundation/StateFrame.tsx +126 -0
  209. package/foundation/StatusChip.tsx +51 -0
  210. package/foundation/TrendChip.tsx +78 -0
  211. package/foundation/chartGeometry.ts +108 -0
  212. package/foundation/columnModel.ts +39 -0
  213. package/foundation/filterModel.ts +111 -0
  214. package/foundation/formatting.ts +69 -0
  215. package/foundation/foundationComponentMetadata.ts +21 -0
  216. package/foundation/foundationDescriptors.ts +204 -0
  217. package/foundation/foundationSamples.ts +63 -0
  218. package/foundation/foundationStrings.ts +137 -0
  219. package/foundation/index.ts +27 -0
  220. package/foundation/useElementWidth.ts +31 -0
  221. package/foundation/viewModel.ts +21 -0
  222. package/index.ts +1 -0
  223. package/package.json +9 -8
  224. package/shell/layout.css +526 -0
  225. package/themes/dark.ts +8 -0
  226. package/themes/light.ts +9 -1
@@ -0,0 +1,49 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ /** The icons the foundation components draw themselves, so none of them depends on an icon font being loaded. */
5
+ export type FoundationIconName =
6
+ | 'check' | 'close' | 'arrow-up' | 'arrow-down' | 'minus' | 'alert' | 'info' | 'lock' | 'clock' | 'inbox' | 'refresh'
7
+ | 'plus' | 'chevron-right' | 'chevron-down' | 'upload' | 'file' | 'user' | 'columns' | 'filter' | 'star' | 'circle';
8
+
9
+ const paths: Record<FoundationIconName, string> = {
10
+ check: 'M5 13l4 4L19 7',
11
+ close: 'M6 6l12 12M18 6L6 18',
12
+ 'arrow-up': 'M12 19V5M5 12l7-7 7 7',
13
+ 'arrow-down': 'M12 5v14M5 12l7 7 7-7',
14
+ minus: 'M5 12h14',
15
+ alert: 'M12 8v5M12 16.5v.5M10.3 3.9L2.5 17.5A2 2 0 004.2 20.5h15.6a2 2 0 001.7-3L13.7 3.9a2 2 0 00-3.4 0z',
16
+ info: 'M12 11v6M12 7.5v.5M12 21a9 9 0 100-18 9 9 0 000 18z',
17
+ lock: 'M7 11V8a5 5 0 0110 0v3M6 11h12a1 1 0 011 1v8a1 1 0 01-1 1H6a1 1 0 01-1-1v-8a1 1 0 011-1z',
18
+ clock: 'M12 7v5l3 2M12 21a9 9 0 100-18 9 9 0 000 18z',
19
+ inbox: 'M3 13l3-8h12l3 8M3 13v6a1 1 0 001 1h16a1 1 0 001-1v-6M3 13h5l1 3h6l1-3h5',
20
+ refresh: 'M20 11a8 8 0 10-2.3 6.3M20 4v7h-7',
21
+ plus: 'M12 5v14M5 12h14',
22
+ 'chevron-right': 'M9 5l7 7-7 7',
23
+ 'chevron-down': 'M5 9l7 7 7-7',
24
+ upload: 'M12 16V4M7 9l5-5 5 5M4 17v2a1 1 0 001 1h14a1 1 0 001-1v-2',
25
+ file: 'M14 3H7a1 1 0 00-1 1v16a1 1 0 001 1h10a1 1 0 001-1V7l-4-4zM14 3v4h4',
26
+ user: 'M12 12a4 4 0 100-8 4 4 0 000 8zM4 21a8 8 0 0116 0',
27
+ columns: 'M4 5h16v14H4zM9.5 5v14M14.5 5v14',
28
+ filter: 'M4 5h16l-6 8v6l-4-2v-4L4 5z',
29
+ star: 'M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1L3.2 9.5l6.1-.9L12 3z',
30
+ circle: 'M12 20a8 8 0 100-16 8 8 0 000 16z',
31
+ };
32
+
33
+ /** Whether a name is one of the icons drawn here. */
34
+ export function isFoundationIcon(name: string): name is FoundationIconName {
35
+ return name in paths;
36
+ }
37
+
38
+ /**
39
+ * One icon. It is decorative unless given a label: the meaning an icon carries is always repeated in text, so no status is
40
+ * conveyed by color or shape alone (WCAG 1.4.1).
41
+ */
42
+ export function FoundationIcon({ name, label }: { name: FoundationIconName; label?: string }) {
43
+ return (
44
+ <svg className='foundation-icon' viewBox='0 0 24 24' width='1em' height='1em' fill='none' stroke='currentColor' strokeWidth='2'
45
+ strokeLinecap='round' strokeLinejoin='round' aria-hidden={label ? undefined : true} role={label ? 'img' : undefined} aria-label={label}>
46
+ <path d={paths[name]} />
47
+ </svg>
48
+ );
49
+ }
@@ -0,0 +1,46 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import { componentRegistryKey, SceneThemeProvider } from '@cratis/scene.react';
5
+ import { defaultBlueprintComponents } from '../defaultBlueprintComponents';
6
+ import { defaultBlueprintName } from '../packageName';
7
+ import { darkTheme, lightTheme } from '../themes';
8
+ import { ComponentState, componentStates } from './ComponentState';
9
+ import { foundationElement, foundationSamples } from './foundationSamples';
10
+
11
+ export interface FoundationStatesProps {
12
+ /** The bare name of the foundation component. */
13
+ component: string;
14
+
15
+ /** The theme the states are drawn in. */
16
+ theme: 'light' | 'dark';
17
+
18
+ /** Properties to lay over the sample, to show a variant. */
19
+ properties?: Record<string, unknown>;
20
+
21
+ /** Whether the page reads right to left. */
22
+ rightToLeft?: boolean;
23
+ }
24
+
25
+ /**
26
+ * Every standard state of one foundation component side by side in one theme: the preview of spec Part B 6 ("all standard states
27
+ * implemented and previewable"), used by the stories and by the gallery.
28
+ */
29
+ export function FoundationStates({ component, theme, properties, rightToLeft }: FoundationStatesProps) {
30
+ const Component = defaultBlueprintComponents[componentRegistryKey(defaultBlueprintName, component)];
31
+ const sample = foundationSamples[component];
32
+ const states = sample?.stateful ? componentStates : [ComponentState.Ready];
33
+
34
+ return (
35
+ <SceneThemeProvider theme={theme === 'dark' ? darkTheme : lightTheme}>
36
+ <div dir={rightToLeft ? 'rtl' : 'ltr'} className='foundation-states' style={{ display: 'grid', gap: '1rem', padding: '1rem', gridTemplateColumns: 'repeat(auto-fill, minmax(18rem, 1fr))', background: 'var(--scene-surface-background)', color: 'var(--scene-text-color)' }}>
37
+ {states.map(state => (
38
+ <figure key={state} style={{ margin: 0 }}>
39
+ <figcaption style={{ fontSize: '0.75rem', textTransform: 'uppercase', marginBlockEnd: '0.5rem' }}>{state}</figcaption>
40
+ <Component element={foundationElement(component, { ...sample?.properties, ...properties }, state === ComponentState.Ready ? undefined : state)} slots={{}} />
41
+ </figure>
42
+ ))}
43
+ </div>
44
+ </SceneThemeProvider>
45
+ );
46
+ }
@@ -0,0 +1,26 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import { ExternalComponent } from '@cratis/scene.model';
5
+
6
+ /**
7
+ * What an action control does when the user lacks the permission it needs (spec Part B 1.5): it is shown and works, shown and
8
+ * refuses, or not shown. A template never assumes a role, so every action declares one of these and the host's permission
9
+ * evaluation sets it.
10
+ */
11
+ export enum PermissionRule {
12
+ /** The control works. */
13
+ Enabled = 'enabled',
14
+
15
+ /** The control is shown but cannot be used, and says why. */
16
+ Disabled = 'disabled',
17
+
18
+ /** The control is not rendered. */
19
+ Hidden = 'hidden',
20
+ }
21
+
22
+ /** Reads a permission rule from a property, defaulting to Enabled for anything that is not a rule. */
23
+ export function readPermissionRule(element: ExternalComponent, property = 'permission'): PermissionRule {
24
+ const value = element.properties[property];
25
+ return value === PermissionRule.Disabled || value === PermissionRule.Hidden ? value : PermissionRule.Enabled;
26
+ }
@@ -0,0 +1,94 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import { KeyboardEvent, useEffect, useId, useMemo, useRef, useState } from 'react';
5
+ import { RegisteredComponentProps, useValueOutput } from '@cratis/scene.react';
6
+ import { ComponentState, readComponentState } from './ComponentState';
7
+ import { FoundationIcon } from './FoundationIcon';
8
+ import { readFoundationStrings } from './foundationStrings';
9
+ import { PermissionRule, readPermissionRule } from './PermissionRule';
10
+ import { FoundationFrame } from './StateFrame';
11
+ import { readOptionalString } from '../shell/elementProperties';
12
+ import { readViews } from './viewModel';
13
+
14
+ /** The output a menu action is published under: `save` or `manage`, which the host acts on. */
15
+ export const savedViewActionOutput = 'action';
16
+
17
+ /**
18
+ * The `savedViewsMenu` component: a list's saved views as a menu button, with the current view as its label.
19
+ *
20
+ * `views` are the choices (id, label, description) and `activeView` the one in force. Choosing a view publishes its id as the `value`
21
+ * output and runs the behaviors attached to the element, so a screen binds its query to the view. The menu follows the ARIA menu
22
+ * pattern: arrows, Home and End move, Enter chooses, Escape closes and returns focus to the button. "Save current view" and
23
+ * "Manage views" publish `save` or `manage` on the `action` output, and each honours its own permission rule (`savePermission`,
24
+ * `managePermission`): hidden, or disabled with the reason.
25
+ */
26
+ export function SavedViewsMenu({ element, interactions, bindingOutputs }: RegisteredComponentProps) {
27
+ const views = useMemo(() => readViews(element.properties.views), [element.properties.views]);
28
+ const suppliedActive = readOptionalString(element, 'activeView') ?? views[0]?.id;
29
+ const [active, setActive] = useState<string | undefined>(suppliedActive);
30
+ const [open, setOpen] = useState(false);
31
+ const strings = readFoundationStrings(element);
32
+ const state = readComponentState(element, views.length > 0);
33
+ const menuId = useId();
34
+ const button = useRef<HTMLButtonElement>(null);
35
+ const menu = useRef<HTMLDivElement>(null);
36
+ const rules = { save: readPermissionRule(element, 'savePermission'), manage: readPermissionRule(element, 'managePermission') };
37
+
38
+ useEffect(() => setActive(suppliedActive), [suppliedActive]);
39
+ useValueOutput(bindingOutputs, active);
40
+ useEffect(() => { if (open) menu.current?.querySelector<HTMLElement>('[role^="menuitem"]:not([aria-disabled="true"])')?.focus(); }, [open]);
41
+
42
+ const items = () => Array.from(menu.current?.querySelectorAll<HTMLElement>('[role^="menuitem"]:not([aria-disabled="true"])') ?? []);
43
+ const move = (event: KeyboardEvent) => {
44
+ const entries = items();
45
+ const index = entries.indexOf(document.activeElement as HTMLElement);
46
+ const target = event.key === 'ArrowDown' ? (index + 1) % entries.length : event.key === 'ArrowUp' ? (index - 1 + entries.length) % entries.length
47
+ : event.key === 'Home' ? 0 : event.key === 'End' ? entries.length - 1 : -1;
48
+
49
+ if (target >= 0) { event.preventDefault(); entries[target]?.focus(); }
50
+ if (event.key === 'Escape') { setOpen(false); button.current?.focus(); }
51
+ if (event.key === 'Tab') setOpen(false);
52
+ };
53
+ const choose = (id: string) => { setActive(id); setOpen(false); button.current?.focus(); interactions?.onSelect?.(); };
54
+ const run = (action: 'save' | 'manage') => { bindingOutputs?.setOutput(savedViewActionOutput, action); setOpen(false); button.current?.focus(); interactions?.onClick?.({ stopPropagation: () => undefined }); };
55
+ const label = views.find(view => view.id === active)?.label ?? strings.viewsDefault;
56
+
57
+ return (
58
+ <FoundationFrame element={element} interactions={interactions} name='saved-views' state={state} skeleton={[45]}>
59
+ {state !== ComponentState.Loading && (
60
+ <div className='foundation-popover-host'>
61
+ <button ref={button} type='button' className='foundation-button' data-emphasis='secondary' aria-haspopup='menu' aria-expanded={open} aria-controls={menuId}
62
+ onClick={() => setOpen(!open)} onKeyDown={event => { if (event.key === 'ArrowDown' && !open) { event.preventDefault(); setOpen(true); } }}>
63
+ <span className='foundation-visually-hidden'>{`${strings.viewsLabel}: `}</span>
64
+ <span>{label}</span>
65
+ <FoundationIcon name='chevron-down' />
66
+ </button>
67
+ <div id={menuId} ref={menu} className='foundation-popover' role='menu' aria-label={strings.viewsLabel} hidden={!open} onKeyDown={move}>
68
+ {views.length === 0 && <span className='foundation-count'>{strings.viewsNone}</span>}
69
+ {views.map(view => (
70
+ <button key={view.id} type='button' role='menuitemradio' aria-checked={view.id === active} className='foundation-menu-item' tabIndex={-1} onClick={() => choose(view.id)}>
71
+ <span className='foundation-menu-check'>{view.id === active && <FoundationIcon name='check' />}</span>
72
+ <span>{view.label}</span>
73
+ {view.description && <span className='foundation-count'>{view.description}</span>}
74
+ </button>
75
+ ))}
76
+ {(rules.save !== PermissionRule.Hidden || rules.manage !== PermissionRule.Hidden) && <hr className='foundation-separator' />}
77
+ {rules.save !== PermissionRule.Hidden && (
78
+ <button type='button' role='menuitem' className='foundation-menu-item' tabIndex={-1} aria-disabled={rules.save === PermissionRule.Disabled || undefined}
79
+ title={rules.save === PermissionRule.Disabled ? strings.disabledNoPermission : undefined} onClick={rules.save === PermissionRule.Enabled ? () => run('save') : undefined}>
80
+ <span className='foundation-menu-check' /><span>{strings.viewsSave}</span>
81
+ </button>
82
+ )}
83
+ {rules.manage !== PermissionRule.Hidden && (
84
+ <button type='button' role='menuitem' className='foundation-menu-item' tabIndex={-1} aria-disabled={rules.manage === PermissionRule.Disabled || undefined}
85
+ title={rules.manage === PermissionRule.Disabled ? strings.disabledNoPermission : undefined} onClick={rules.manage === PermissionRule.Enabled ? () => run('manage') : undefined}>
86
+ <span className='foundation-menu-check' /><span>{strings.viewsManage}</span>
87
+ </button>
88
+ )}
89
+ </div>
90
+ </div>
91
+ )}
92
+ </FoundationFrame>
93
+ );
94
+ }
@@ -0,0 +1,44 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import { RegisteredComponentProps } from '@cratis/scene.react';
5
+ import { ComponentState, readComponentState } from './ComponentState';
6
+ import { FoundationFrame } from './StateFrame';
7
+ import { TrendChipView } from './TrendChip';
8
+ import { formatNumber, readLocale, readNumberFormat } from './formatting';
9
+ import { readFoundationStrings } from './foundationStrings';
10
+ import { readOptionalString, readString } from '../shell/elementProperties';
11
+
12
+ /**
13
+ * The `statCard` component: one key figure with its label, its trend and what the trend is compared to - the unit of a dashboard's
14
+ * `kpis` slot.
15
+ *
16
+ * The value is a bound number, never embedded in the component (a figure is data, not design); it is formatted for the locale as
17
+ * a number, currency, percent or compact. With no value the card is empty, and it shows all five standard states
18
+ * independently of its neighbours, so a dashboard whose one query failed still shows the other cards.
19
+ */
20
+ export function StatCard({ element, interactions }: RegisteredComponentProps) {
21
+ const value = element.properties.value;
22
+ const hasValue = typeof value === 'number';
23
+ const state = readComponentState(element, hasValue);
24
+ const locale = readLocale(element);
25
+ const label = readString(element, 'label');
26
+ const change = element.properties.change;
27
+ const currency = readOptionalString(element, 'currency');
28
+
29
+ return (
30
+ <FoundationFrame element={element} interactions={interactions}
31
+ name='stat-card' state={state} skeleton={[40, 70, 30]}>
32
+ {state !== ComponentState.Loading && (
33
+ <>
34
+ <h3 className='foundation-stat-label'>{label}</h3>
35
+ <p className='foundation-stat-value'>{hasValue ? formatNumber(value, locale, readNumberFormat(element), currency, typeof element.properties.fractionDigits === 'number' ? element.properties.fractionDigits : undefined) : ''}</p>
36
+ {typeof change === 'number' && (
37
+ <TrendChipView change={change} locale={locale} goodDirection={element.properties.goodDirection === 'down' ? 'down' : 'up'}
38
+ comparison={readOptionalString(element, 'comparison')} strings={readFoundationStrings(element)} />
39
+ )}
40
+ </>
41
+ )}
42
+ </FoundationFrame>
43
+ );
44
+ }
@@ -0,0 +1,126 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import { ReactNode } from 'react';
5
+ import { ExternalComponent } from '@cratis/scene.model';
6
+ import { RegisteredComponentProps } from '@cratis/scene.react';
7
+ import { readOptionalString, readStrings } from '../shell/elementProperties';
8
+ import { ActionButton } from './ActionButton';
9
+ import { ComponentState } from './ComponentState';
10
+ import { FoundationIcon, FoundationIconName } from './FoundationIcon';
11
+ import { FoundationStrings, formatText, readFoundationStrings } from './foundationStrings';
12
+ import { readPermissionRule } from './PermissionRule';
13
+ import { readLocale } from './formatting';
14
+
15
+ export interface FoundationFrameProps extends Pick<RegisteredComponentProps, 'element' | 'interactions'> {
16
+ /** The component's own class, added after `foundation`. */
17
+ name: string;
18
+
19
+ /** The state the component is in; compute it with `readComponentState`. */
20
+ state: ComponentState;
21
+
22
+ /** The shape of the skeleton, as the width of each block in percent; the skeleton keeps the footprint of the content. */
23
+ skeleton?: number[];
24
+
25
+ /** What the component draws when it is ready or partial. */
26
+ children?: ReactNode;
27
+ }
28
+
29
+ /** The accessible name of a region, from the element's `label` property. */
30
+ function regionLabel(element: ExternalComponent): string | undefined {
31
+ return readOptionalString(element, 'label') ?? readOptionalString(element, 'title');
32
+ }
33
+
34
+ /**
35
+ * The root every foundation component renders, and the five standard states of spec Part B 1.4 in one place:
36
+ * a skeleton while loading (never a spinner alone), an explanation with the primary action when empty, a message with a
37
+ * retry on error, what is missing - and nothing of the data - when the user is not allowed, and the loaded part with a
38
+ * note naming what failed when only some regions did.
39
+ *
40
+ * The region carries an ARIA landmark role when it has a label, a `dir` is left to the document so right-to-left is
41
+ * inherited, and every piece of text comes from the strings table.
42
+ */
43
+ export function FoundationFrame({ element, interactions, name, state, skeleton = [60, 100, 80], children }: FoundationFrameProps) {
44
+ const strings = readFoundationStrings(element);
45
+ const label = regionLabel(element);
46
+ const density = element.properties.density === 'compact' ? 'compact' : 'comfortable';
47
+
48
+ return (
49
+ <section className={`foundation foundation-${name}`} data-scene-id={element.id} data-state={state} data-density={density}
50
+ lang={readLocale(element)} role={label ? 'region' : undefined} aria-label={label} aria-busy={state === ComponentState.Loading || undefined}>
51
+ {renderState(element, interactions, strings, state, skeleton, children)}
52
+ </section>
53
+ );
54
+ }
55
+
56
+ function renderState(element: ExternalComponent, interactions: RegisteredComponentProps['interactions'], strings: FoundationStrings, state: ComponentState, skeleton: number[], children: ReactNode) {
57
+ switch (state) {
58
+ case ComponentState.Loading:
59
+ return (
60
+ <div className='foundation-skeleton' role='status'>
61
+ <span className='foundation-visually-hidden'>{strings.loading}</span>
62
+ {skeleton.map((width, index) => <span key={index} className='foundation-skeleton-block' style={{ width: `${width}%` }} aria-hidden='true' />)}
63
+ </div>
64
+ );
65
+ case ComponentState.Empty:
66
+ return <EmptyStateView element={element} interactions={interactions} strings={strings} />;
67
+ case ComponentState.Error:
68
+ return (
69
+ <div className='foundation-message' data-tone='danger' role='alert'>
70
+ <FoundationIcon name='alert' />
71
+ <div className='foundation-message-text'>
72
+ <strong>{strings.errorHeadline}</strong>
73
+ <span>{typeof element.properties.error === 'string' && element.properties.error.length > 0 ? element.properties.error : strings.errorHint}</span>
74
+ </div>
75
+ <ActionButton emphasis='secondary' disabledReason={strings.disabledNoPermission} onClick={interactions?.onClick}>{strings.retry}</ActionButton>
76
+ </div>
77
+ );
78
+ case ComponentState.NoPermission: {
79
+ const subject = readOptionalString(element, 'permissionSubject') ?? strings.noPermissionSubject;
80
+ return (
81
+ <div className='foundation-message' data-tone='neutral' role='status'>
82
+ <FoundationIcon name='lock' />
83
+ <div className='foundation-message-text'>
84
+ <strong>{strings.noPermissionHeadline}</strong>
85
+ <span>{formatText(strings.noPermissionHint, { subject })}</span>
86
+ </div>
87
+ </div>
88
+ );
89
+ }
90
+
91
+ case ComponentState.Partial:
92
+ return (
93
+ <>
94
+ <div className='foundation-message' data-tone='warning' role='status'>
95
+ <FoundationIcon name='alert' />
96
+ <div className='foundation-message-text'>
97
+ <strong>{strings.partialHeadline}</strong>
98
+ {readStrings(element, 'failedRegions').length > 0 && <span>{formatText(strings.partialHint, { regions: readStrings(element, 'failedRegions').join(', ') })}</span>}
99
+ </div>
100
+ <ActionButton emphasis='secondary' disabledReason={strings.disabledNoPermission} onClick={interactions?.onClick}>{strings.retry}</ActionButton>
101
+ </div>
102
+ {children}
103
+ </>
104
+ );
105
+ default:
106
+ return <>{children}</>;
107
+ }
108
+ }
109
+
110
+ /** What an empty region says: an icon, a headline, a hint and the primary action, with the action's permission rule applied. */
111
+ export function EmptyStateView({ element, interactions, strings }: Pick<FoundationFrameProps, 'element' | 'interactions'> & { strings: FoundationStrings }) {
112
+ const icon = (readOptionalString(element, 'emptyIcon') ?? readOptionalString(element, 'icon')) as FoundationIconName | undefined;
113
+ const actionLabel = readOptionalString(element, 'emptyActionLabel') ?? readOptionalString(element, 'actionLabel');
114
+
115
+ return (
116
+ <div className='foundation-empty' role='status'>
117
+ <span className='foundation-empty-icon'><FoundationIcon name={icon ?? 'inbox'} /></span>
118
+ <strong className='foundation-empty-headline'>{readOptionalString(element, 'emptyHeadline') ?? readOptionalString(element, 'headline') ?? strings.emptyHeadline}</strong>
119
+ <span className='foundation-empty-hint'>{readOptionalString(element, 'emptyHint') ?? readOptionalString(element, 'hint') ?? strings.emptyHint}</span>
120
+ {actionLabel && (
121
+ <ActionButton rule={readPermissionRule(element, 'actionPermission')} disabledReason={strings.disabledNoPermission} onClick={interactions?.onClick}>{actionLabel}</ActionButton>
122
+ )}
123
+ </div>
124
+ );
125
+ }
126
+
@@ -0,0 +1,51 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import { RegisteredComponentProps } from '@cratis/scene.react';
5
+ import { readFoundationStrings } from './foundationStrings';
6
+ import { FoundationIcon, FoundationIconName } from './FoundationIcon';
7
+ import { readOptionalString, readString } from '../shell/elementProperties';
8
+
9
+ /** The semantic tone of a status. */
10
+ export enum StatusTone {
11
+ Success = 'success',
12
+ Warning = 'warning',
13
+ Danger = 'danger',
14
+ Info = 'info',
15
+ Neutral = 'neutral',
16
+ }
17
+
18
+ /** The icon each tone gets, so a status is told by shape as well as color (WCAG 1.4.1). */
19
+ export const statusToneIcons: Record<StatusTone, FoundationIconName> = {
20
+ [StatusTone.Success]: 'check',
21
+ [StatusTone.Warning]: 'alert',
22
+ [StatusTone.Danger]: 'close',
23
+ [StatusTone.Info]: 'info',
24
+ [StatusTone.Neutral]: 'circle',
25
+ };
26
+
27
+ /** Reads a tone, defaulting to Neutral. */
28
+ export function readStatusTone(value: unknown): StatusTone {
29
+ return (Object.values(StatusTone) as string[]).includes(value as string) ? (value as StatusTone) : StatusTone.Neutral;
30
+ }
31
+
32
+ /**
33
+ * The `statusChip` component: a status as a semantic color, an icon and its text.
34
+ *
35
+ * The text is always shown - the status of a record is never only a colored dot - and the tone picks the icon and the color from
36
+ * the theme's status tokens. A status the application names ("Awaiting approval") is its own `status` text; `tone` maps it onto
37
+ * one of the five tones.
38
+ */
39
+ export function StatusChip({ element }: RegisteredComponentProps) {
40
+ const tone = readStatusTone(element.properties.tone);
41
+ const strings = readFoundationStrings(element);
42
+ const fallback = { success: strings.statusSuccess, warning: strings.statusWarning, danger: strings.statusDanger, info: strings.statusInfo, neutral: strings.statusNeutral }[tone];
43
+ const text = readString(element, 'status', readOptionalString(element, 'label') ?? fallback);
44
+
45
+ return (
46
+ <span className='foundation foundation-chip foundation-status-chip' data-scene-id={element.id} data-tone={tone}>
47
+ <FoundationIcon name={statusToneIcons[tone]} />
48
+ <span>{text}</span>
49
+ </span>
50
+ );
51
+ }
@@ -0,0 +1,78 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import { RegisteredComponentProps } from '@cratis/scene.react';
5
+ import { FoundationIcon } from './FoundationIcon';
6
+ import { formatNumber, NumberFormat, readLocale } from './formatting';
7
+ import { formatText, readFoundationStrings } from './foundationStrings';
8
+ import { readOptionalString } from '../shell/elementProperties';
9
+
10
+ /** The direction a measure moved. */
11
+ export type TrendDirection = 'up' | 'down' | 'flat';
12
+
13
+ /** Whether a movement is good, bad or neither, which is independent of whether the number rose: falling response time is good. */
14
+ export type TrendOutcome = 'good' | 'bad' | 'neutral';
15
+
16
+ /** The direction a change moved in. */
17
+ export function trendDirection(change: number): TrendDirection {
18
+ return change > 0 ? 'up' : change < 0 ? 'down' : 'flat';
19
+ }
20
+
21
+ /** Whether a movement is good for a measure, given which direction is the good one. */
22
+ export function trendOutcome(direction: TrendDirection, goodDirection: 'up' | 'down'): TrendOutcome {
23
+ return direction === 'flat' ? 'neutral' : direction === goodDirection ? 'good' : 'bad';
24
+ }
25
+
26
+ /** The tone each outcome is drawn in. */
27
+ const tones: Record<TrendOutcome, string> = { good: 'success', bad: 'danger', neutral: 'neutral' };
28
+
29
+ /** The props of a trend chip drawn directly, as the stat card does. */
30
+ export interface TrendChipViewProps {
31
+ change: number;
32
+ locale: string;
33
+ goodDirection?: 'up' | 'down';
34
+ comparison?: string;
35
+ format?: NumberFormat;
36
+ strings: ReturnType<typeof readFoundationStrings>;
37
+ }
38
+
39
+ /**
40
+ * A change, drawn as an arrow, the change and what it is compared to.
41
+ *
42
+ * Color says whether the movement is good, but never alone: the arrow gives direction and a visually hidden sentence
43
+ * says all of it ("up 12.5% compared to last month"), so the chip reads the same without color.
44
+ */
45
+ export function TrendChipView({ change, locale, goodDirection = 'up', comparison, format = NumberFormat.Percent, strings }: TrendChipViewProps) {
46
+ const direction = trendDirection(change);
47
+ const outcome = trendOutcome(direction, goodDirection);
48
+ const magnitude = formatNumber(Math.abs(change), locale, format);
49
+ const spoken = direction === 'flat' ? strings.trendFlat : formatText(direction === 'up' ? strings.trendUp : strings.trendDown, { value: magnitude });
50
+
51
+ return (
52
+ <span className='foundation-chip foundation-trend' data-tone={tones[outcome]} data-direction={direction}>
53
+ <FoundationIcon name={direction === 'up' ? 'arrow-up' : direction === 'down' ? 'arrow-down' : 'minus'} />
54
+ <span aria-hidden='true'>{direction === 'flat' ? magnitude : magnitude}</span>
55
+ <span className='foundation-visually-hidden'>{spoken}{comparison ? ` ${formatText(strings.trendComparison, { period: comparison })}` : ''}</span>
56
+ {comparison && <span className='foundation-trend-comparison' aria-hidden='true'>{formatText(strings.trendComparison, { period: comparison })}</span>}
57
+ </span>
58
+ );
59
+ }
60
+
61
+ /**
62
+ * The `trendChip` component: a change with its direction, whether that is good, and what it is compared to.
63
+ *
64
+ * `change` is the movement as a number (a percentage by default), `goodDirection` says which way is good, and `comparison` names
65
+ * the period. Without a number the chip is empty, and then it draws nothing rather than an invented zero.
66
+ */
67
+ export function TrendChip({ element }: RegisteredComponentProps) {
68
+ const change = element.properties.change;
69
+ if (typeof change !== 'number') return undefined;
70
+
71
+ return (
72
+ <span className='foundation foundation-trend-chip' data-scene-id={element.id}>
73
+ <TrendChipView change={change} locale={readLocale(element)} goodDirection={element.properties.goodDirection === 'down' ? 'down' : 'up'}
74
+ comparison={readOptionalString(element, 'comparison')} strings={readFoundationStrings(element)}
75
+ {...(typeof element.properties.format === 'string' && (Object.values(NumberFormat) as string[]).includes(element.properties.format) ? { format: element.properties.format as NumberFormat } : {})} />
76
+ </span>
77
+ );
78
+ }
@@ -0,0 +1,108 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ /** The kinds of chart the wrapper draws (spec Part B 2.3: line, bar, stacked, donut, funnel). */
5
+ export enum ChartKind {
6
+ Line = 'line',
7
+ Bar = 'bar',
8
+ Stacked = 'stacked',
9
+ Donut = 'donut',
10
+ Funnel = 'funnel',
11
+ }
12
+
13
+ /** One named series of values, one per category. */
14
+ export interface ChartSeries {
15
+ name: string;
16
+ values: number[];
17
+ }
18
+
19
+ /** A rounded-up axis maximum and the tick values below it, so an axis reads 0, 25, 50, 75, 100 and not 0, 23.4, 46.8. */
20
+ export interface ChartScale {
21
+ maximum: number;
22
+ ticks: number[];
23
+ }
24
+
25
+ /** Builds a scale from zero to a rounded-up maximum of the values, in about `target` steps. */
26
+ export function niceScale(maximum: number, target = 4): ChartScale {
27
+ if (!Number.isFinite(maximum) || maximum <= 0) return { maximum: 1, ticks: [0, 1] };
28
+
29
+ const rough = maximum / target;
30
+ const magnitude = 10 ** Math.floor(Math.log10(rough));
31
+ const residual = rough / magnitude;
32
+ const step = (residual <= 1 ? 1 : residual <= 2 ? 2 : residual <= 5 ? 5 : 10) * magnitude;
33
+ const top = Math.ceil(maximum / step) * step;
34
+ const ticks: number[] = [];
35
+ for (let tick = 0; tick <= top + step / 2; tick += step) ticks.push(Number(tick.toFixed(10)));
36
+ return { maximum: top, ticks };
37
+ }
38
+
39
+ /** Reads series out of a property value, dropping anything that is not a named list of numbers, so a half-bound chart draws what it has. */
40
+ export function readSeries(value: unknown): ChartSeries[] {
41
+ if (!Array.isArray(value)) return [];
42
+
43
+ return value.flatMap((entry): ChartSeries[] => {
44
+ if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) return [];
45
+ const { name, values } = entry as Record<string, unknown>;
46
+ if (typeof name !== 'string' || !Array.isArray(values)) return [];
47
+ return [{ name, values: values.map(item => (typeof item === 'number' && Number.isFinite(item) ? item : 0)) }];
48
+ });
49
+ }
50
+
51
+ /** The extent of the values a chart of this kind has to fit: stacked series add up, the others are compared one by one. */
52
+ export function dataMaximum(kind: ChartKind, series: ChartSeries[], categoryCount: number): number {
53
+ if (kind === ChartKind.Stacked) {
54
+ return Math.max(0, ...Array.from({ length: categoryCount }, (_, index) => series.reduce((sum, item) => sum + Math.max(0, item.values[index] ?? 0), 0)));
55
+ }
56
+
57
+ return Math.max(0, ...series.flatMap(item => item.values));
58
+ }
59
+
60
+ /** A slice of a donut, in radians clockwise from the top. */
61
+ export interface DonutSlice {
62
+ index: number;
63
+ value: number;
64
+ share: number;
65
+ start: number;
66
+ end: number;
67
+ }
68
+
69
+ /** Divides the positive values into slices that together make one turn. */
70
+ export function donutSlices(values: number[]): DonutSlice[] {
71
+ const positive = values.map(value => Math.max(0, value));
72
+ const total = positive.reduce((sum, value) => sum + value, 0);
73
+ if (total === 0) return [];
74
+
75
+ let angle = 0;
76
+ return positive.flatMap((value, index) => {
77
+ if (value === 0) return [];
78
+ const share = value / total;
79
+ const slice = { index, value, share, start: angle, end: angle + share * Math.PI * 2 };
80
+ angle = slice.end;
81
+ return [slice];
82
+ });
83
+ }
84
+
85
+ /** The SVG path of a ring segment between two radii; a full turn is drawn as two halves, because one arc cannot start and end on the same point. */
86
+ export function ringPath(centerX: number, centerY: number, outer: number, inner: number, start: number, end: number): string {
87
+ const point = (radius: number, angle: number) => `${(centerX + radius * Math.sin(angle)).toFixed(2)} ${(centerY - radius * Math.cos(angle)).toFixed(2)}`;
88
+ if (end - start >= Math.PI * 2 - 1e-6) {
89
+ const middle = start + Math.PI;
90
+ return `${ringPath(centerX, centerY, outer, inner, start, middle)} ${ringPath(centerX, centerY, outer, inner, middle, end)}`;
91
+ }
92
+
93
+ const large = end - start > Math.PI ? 1 : 0;
94
+ return `M ${point(outer, start)} A ${outer} ${outer} 0 ${large} 1 ${point(outer, end)} L ${point(inner, end)} A ${inner} ${inner} 0 ${large} 0 ${point(inner, start)} Z`;
95
+ }
96
+
97
+ /** One stage of a funnel: a centered bar whose width is its share of the widest stage. */
98
+ export interface FunnelStage {
99
+ index: number;
100
+ value: number;
101
+ widthRatio: number;
102
+ }
103
+
104
+ /** Sizes the stages of a funnel against the largest value. */
105
+ export function funnelStages(values: number[]): FunnelStage[] {
106
+ const maximum = Math.max(0, ...values);
107
+ return values.map((value, index) => ({ index, value, widthRatio: maximum === 0 ? 0 : Math.max(0, value) / maximum }));
108
+ }