storybook-nitroui 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -9,8 +9,8 @@ Pinned to `storybook@11.0.1` and NitroUI `0.3.0`.
9
9
 
10
10
  ## Setup
11
11
 
12
- `nitro-storybook init` writes the three `.storybook` files below and adds the package scripts. The
13
- packages:
12
+ `nitro-storybook init` writes the three `.storybook` files below and adds the package scripts. In an app
13
+ without stories, it also adds an example `Button` with stories in `src/stories/`. The packages:
14
14
 
15
15
  ```sh
16
16
  bun add storybook-nitroui-controls storybook-nitroui-containers nitro-mmkv
@@ -285,6 +285,11 @@ environment. The environment globals are applied natively around the story with
285
285
  `viewport` and `backgrounds` take the same parameters as the web addons. A story can pin any of
286
286
  them with `globals`, and the panel then shows that row as locked.
287
287
 
288
+ The `layout` parameter places the story as on web: `'padded'` (default, 16 points around it),
289
+ `'centered'` or `'fullscreen'`. Previews written by `nitro-storybook init` 0.1.0 set
290
+ `parameters.nitroui.layout` instead; it still works when `layout` is unset, but replace it with
291
+ `layout` so stories can override it.
292
+
288
293
  The **Actions** tab logs `fn()` spies, `argTypes` actions and `parameters.actions.argTypesRegex`
289
294
  actions. These come from Storybook core's own annotations. Identical consecutive calls are folded
290
295
  into one row with a count.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "storybook-nitroui",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "description": "Storybook framework for NitroUI apps: on-device preview and manager, Node-side indexing and docgen.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -73,8 +73,8 @@
73
73
  "nitro-ui-navigation": "0.3.0",
74
74
  "typescript": ">=6",
75
75
  "nitro-mmkv": "0.3.0",
76
- "storybook-nitroui-containers": "^0.1.0",
77
- "storybook-nitroui-controls": "^0.1.0",
76
+ "storybook-nitroui-containers": "^0.2.1",
77
+ "storybook-nitroui-controls": "^0.2.1",
78
78
  "nitro-networking": "0.3.0",
79
79
  "nitro-ui-dev": "0.3.0"
80
80
  },
@@ -94,8 +94,8 @@
94
94
  "nitro-ui-renderer": "0.3.0",
95
95
  "react": "19.3.0",
96
96
  "storybook": "11.0.1",
97
- "storybook-nitroui-containers": "0.1.0",
98
- "storybook-nitroui-controls": "0.1.0",
97
+ "storybook-nitroui-containers": "0.2.1",
98
+ "storybook-nitroui-controls": "0.2.1",
99
99
  "typescript": "npm:@typescript/typescript6@^6.0.2"
100
100
  },
101
101
  "peerDependenciesMeta": {
@@ -8,10 +8,13 @@ export class MemorySelectionStore implements SelectionStore {
8
8
  selection?: Selection
9
9
  selectionSpecifier: SelectionStore['selectionSpecifier']
10
10
 
11
- /** `args` and `globals` are applied like web Storybook's URL args and globals. */
11
+ /**
12
+ * `args` and `globals` are applied like web Storybook's URL args and globals. Without a story, the
13
+ * first story in the index opens, as web Storybook does when the URL names none.
14
+ */
12
15
  constructor(initial?: { storyId: StoryId; args?: Args; globals?: Globals }) {
13
16
  this.selectionSpecifier = initial === undefined
14
- ? null
17
+ ? { storySpecifier: '*', viewMode: 'story' }
15
18
  : { storySpecifier: initial.storyId, viewMode: 'story', args: initial.args, globals: initial.globals }
16
19
  }
17
20
 
@@ -78,7 +78,9 @@ export const AddonPanel = Inspector
78
78
  function InspectorScroll({ keyboardAware, bottomPadding, children }: { keyboardAware: boolean; bottomPadding: number; children: ReactNode }) {
79
79
  const keyboard = useKeyboardInset()
80
80
  return (
81
- <ScrollView layout={{ flex: 1 }}>
81
+ // Nested scrolling lets Android's bottom sheet see this scroll view: without it, the sheet takes every
82
+ // downward drag once expanded, so a scrolled list could not scroll back up.
83
+ <ScrollView isNestedScrollingEnabled layout={{ flex: 1 }}>
82
84
  <ScrollViewContent layout={{ paddingBottom: bottomPadding + (keyboardAware ? keyboard : 0) + 24 }}>{children}</ScrollViewContent>
83
85
  </ScrollView>
84
86
  )
@@ -1,10 +1,12 @@
1
1
  import { useMemo, useState } from 'react'
2
2
  import { Text, View } from 'nitro-ui-renderer'
3
3
  import {
4
+ CheckboxGroup,
4
5
  ColorWell,
5
6
  DatePicker,
6
7
  MultiSelect,
7
8
  pickFile,
9
+ RadioGroup,
8
10
  SegmentedControl,
9
11
  SelectMenu,
10
12
  Slider,
@@ -13,8 +15,8 @@ import {
13
15
  type Option,
14
16
  } from 'storybook-nitroui-controls'
15
17
  import type { ControlProps, ControlRegistry } from '../controls.tsx'
16
- import { TextButton, useTap } from '../primitives.tsx'
17
- import { isIOS, useTheme } from '../theme.ts'
18
+ import { TextButton } from '../primitives.tsx'
19
+ import { useTheme } from '../theme.ts'
18
20
  import { optionEntries, optionKey, optionKeys, optionValue, presetColors, type OptionEntry } from './argRows.ts'
19
21
  import { toHex } from './color.ts'
20
22
  import { Field } from './Field.tsx'
@@ -261,46 +263,15 @@ export function InlineRadioControl(props: ControlProps) {
261
263
  )
262
264
  }
263
265
 
264
- /** Vertical list of choices: checkmark rows on iOS (as in Settings), radio buttons on Android. */
265
- function ChoiceList({ entries, selected, multiple, disabled, onToggle }: {
266
- entries: OptionEntry[]
267
- selected: (entry: OptionEntry) => boolean
268
- multiple: boolean
269
- disabled: boolean
270
- onToggle: (entry: OptionEntry) => void
271
- }) {
272
- return (
273
- <View>
274
- {entries.map((entry) => (
275
- <ChoiceRow key={entry.key} label={entry.label} on={selected(entry)} multiple={multiple} disabled={disabled} onPress={() => onToggle(entry)} />
276
- ))}
277
- </View>
278
- )
279
- }
280
-
281
- function ChoiceRow({ label, on, multiple, disabled, onPress }: { label: string; on: boolean; multiple: boolean; disabled: boolean; onPress: () => void }) {
282
- const theme = useTheme()
283
- const tap = useTap(disabled ? undefined : onPress)
284
- const mark = isIOS ? (on ? '✓' : '') : multiple ? (on ? '☑' : '☐') : on ? '◉' : '○'
285
- return (
286
- <View gestureRecognizers={tap} layout={{ flexDirection: 'row', alignItems: 'center', minHeight: isIOS ? 36 : 44, gap: 10 }} style={{ opacity: disabled ? 0.5 : 1 }}>
287
- {isIOS ? null : <Text fontSize={20} color={on ? theme.tint : theme.secondaryLabel} layout={{ width: 24 }}>{mark}</Text>}
288
- <Text color={theme.label} layout={{ flex: 1 }}>{label}</Text>
289
- {isIOS ? <Text fontWeight="semibold" color={theme.tint}>{mark}</Text> : null}
290
- </View>
291
- )
292
- }
293
-
294
266
  export function RadioControl(props: ControlProps) {
295
267
  const entries = useOptions(props)
296
268
  if (entries.length === 0) return <MissingOptions />
297
269
  return (
298
- <ChoiceList
299
- entries={entries}
300
- multiple={false}
270
+ <RadioGroup
271
+ options={asWidgetOptions(entries)}
272
+ value={optionKey(entries, props.value)}
301
273
  disabled={isReadOnly(props)}
302
- selected={(entry) => entry.value === props.value}
303
- onToggle={(entry) => props.onChange(entry.value)}
274
+ onValueChange={(key) => props.onChange(optionValue(entries, key))}
304
275
  />
305
276
  )
306
277
  }
@@ -310,13 +281,16 @@ export function CheckControl(props: ControlProps) {
310
281
  if (entries.length === 0) return <MissingOptions />
311
282
  const values = Array.isArray(props.value) ? (props.value as unknown[]) : []
312
283
  return (
313
- <ChoiceList
314
- entries={entries}
315
- multiple
284
+ <CheckboxGroup
285
+ options={asWidgetOptions(entries)}
286
+ value={optionKeys(entries, values)}
316
287
  disabled={isReadOnly(props)}
317
- selected={(entry) => values.includes(entry.value)}
318
- // As on web, the array keeps the order the options were checked in.
319
- onToggle={(entry) => props.onChange(values.includes(entry.value) ? values.filter((value) => value !== entry.value) : [...values, entry.value])}
288
+ // As on web, the array keeps the order the options were checked in: kept values stay in
289
+ // place and a newly checked one goes last.
290
+ onValueChange={(keys) => {
291
+ const next = keys.map((key) => optionValue(entries, key))
292
+ props.onChange([...values.filter((value) => next.includes(value)), ...next.filter((value) => !values.includes(value))])
293
+ }}
320
294
  />
321
295
  )
322
296
  }
@@ -1,5 +1,5 @@
1
1
  import type { ReactNode } from 'react'
2
- import { useColorScheme } from 'nitro-ui-renderer'
2
+ import { useColorScheme, View } from 'nitro-ui-renderer'
3
3
  import { PreviewContainer } from 'storybook-nitroui-containers'
4
4
  import type { Globals, Parameters, StoryContext } from 'storybook/internal/types'
5
5
  import { useStore } from '../../Store.ts'
@@ -31,6 +31,22 @@ export const deviceAnnotations = {
31
31
  ],
32
32
  }
33
33
 
34
+ type StoryLayout = 'centered' | 'fullscreen' | 'padded'
35
+
36
+ /** Web Storybook's `layout` parameter: padding matches web's 1rem, and `padded` is the default. */
37
+ const layouts = {
38
+ centered: { flex: 1, alignItems: 'center', justifyContent: 'center', padding: 16 },
39
+ padded: { flex: 1, padding: 16 },
40
+ fullscreen: { flex: 1 },
41
+ } as const
42
+
43
+ function storyLayout(parameters: Parameters): StoryLayout {
44
+ // `nitroui.layout` is the deprecated spelling that `nitro-storybook init` 0.1.0 wrote; the standard
45
+ // parameter wins, so a story's `layout` overrides a project-level `nitroui.layout`.
46
+ const layout: unknown = parameters.layout ?? parameters.nitroui?.layout
47
+ return layout === 'centered' || layout === 'fullscreen' ? layout : 'padded'
48
+ }
49
+
34
50
  /**
35
51
  * Applies the environment globals natively around the story with `PreviewContainer`, and keeps the
36
52
  * story clear of the controls sheet. It reads the inset store itself, so moving the sheet re-renders
@@ -53,7 +69,7 @@ function EnvironmentFrame({ globals, parameters, children }: { globals: Globals;
53
69
  layout={{ position: 'absolute', left: insets.left, top: insets.top, right: insets.right, bottom: insets.bottom }}
54
70
  style={{ background: environment.background ?? (dark ? 0x000000ff : 0xffffffff) }}
55
71
  >
56
- {children}
72
+ <View layout={layouts[storyLayout(parameters)]}>{children}</View>
57
73
  </PreviewContainer>
58
74
  )
59
75
  }
@@ -1,6 +1,7 @@
1
1
  /** `nitro-storybook init`: adds the `.storybook` files and package scripts to a NitroUI app. */
2
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
2
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
3
3
  import { join, relative } from 'node:path'
4
+ import { fileURLToPath } from 'node:url'
4
5
  import { CommandError } from './exec.ts'
5
6
  import type { Output } from './run.ts'
6
7
 
@@ -24,7 +25,7 @@ const PREVIEW = `import type { Preview } from 'storybook-nitroui'
24
25
 
25
26
  const preview: Preview = {
26
27
  parameters: {
27
- nitroui: { layout: 'centered' },
28
+ layout: 'centered',
28
29
  },
29
30
  }
30
31
 
@@ -39,6 +40,74 @@ import { Storybook } from 'storybook-nitroui/device'
39
40
  registerApp(Storybook)
40
41
  `
41
42
 
43
+ // The example \`storybook init\` adds on web, for apps that have no stories yet.
44
+ const EXAMPLE_COMPONENT = `import { useMemo } from 'react'
45
+ import { TapGestureRecognizer, Text, View } from 'nitro-ui-renderer'
46
+
47
+ export type ButtonProps = {
48
+ /** Text shown in the button. */
49
+ label: string
50
+ /** Visual style. */
51
+ variant?: 'primary' | 'secondary'
52
+ /** Ignores taps and dims the button. */
53
+ disabled?: boolean
54
+ /** Called when the button is tapped. */
55
+ onPress?: () => void
56
+ }
57
+
58
+ /** A tappable button built from NitroUI primitives. */
59
+ export function Button({ label, variant = 'primary', disabled = false, onPress }: ButtonProps) {
60
+ const tap = useMemo(() => {
61
+ const recognizer = new TapGestureRecognizer()
62
+ recognizer.onTap = () => {
63
+ if (!disabled) onPress?.()
64
+ }
65
+ return [recognizer]
66
+ }, [disabled, onPress])
67
+ return (
68
+ <View
69
+ gestureRecognizers={tap}
70
+ layout={{ paddingVertical: 12, paddingHorizontal: 20 }}
71
+ style={{ background: variant === 'primary' ? 0x007affff : 0xe5e5eaff, cornerRadius: 12, opacity: disabled ? 0.4 : 1 }}
72
+ >
73
+ <Text fontSize={17} fontWeight="semibold" color={variant === 'primary' ? 0xffffffff : 0x000000ff}>{label}</Text>
74
+ </View>
75
+ )
76
+ }
77
+ `
78
+
79
+ const EXAMPLE_STORIES = `import type { Meta, StoryObj } from 'storybook-nitroui'
80
+ import { Button } from './Button'
81
+
82
+ const meta = {
83
+ title: 'Example/Button',
84
+ component: Button,
85
+ args: { label: 'Continue', variant: 'primary', disabled: false },
86
+ argTypes: { onPress: { action: 'pressed' } },
87
+ } satisfies Meta<typeof Button>
88
+
89
+ export default meta
90
+ type Story = StoryObj<typeof meta>
91
+
92
+ export const Primary: Story = {}
93
+ export const Secondary: Story = { args: { variant: 'secondary', label: 'Cancel' } }
94
+ export const Disabled: Story = { args: { disabled: true } }
95
+ `
96
+
97
+ /** The Storybook version this package is built for (its `storybook` peer dependency). */
98
+ function storybookVersion() {
99
+ const manifest = JSON.parse(readFileSync(fileURLToPath(import.meta.resolve('../../package.json')), 'utf8')) as { peerDependencies?: Record<string, string> }
100
+ return manifest.peerDependencies?.storybook ?? 'latest'
101
+ }
102
+
103
+ function hasStories(directory: string): boolean {
104
+ if (!existsSync(directory)) return false
105
+ return readdirSync(directory, { withFileTypes: true }).some((entry) =>
106
+ entry.isDirectory()
107
+ ? entry.name !== 'node_modules' && hasStories(join(directory, entry.name))
108
+ : /\.stories\.[jt]sx?$/.test(entry.name))
109
+ }
110
+
42
111
  const SCRIPTS: Record<string, string> = {
43
112
  'storybook': 'storybook dev',
44
113
  'storybook:ios': 'nitro-storybook ios',
@@ -63,6 +132,16 @@ export function initCommand(root: string, configDir: string, out: Output) {
63
132
  created.push(relative(root, path))
64
133
  }
65
134
 
135
+ // Only for apps without stories, so running init again or on an existing project adds nothing.
136
+ const exampleDir = join(root, 'src', 'stories')
137
+ if (!hasStories(join(root, 'src')) && !existsSync(exampleDir)) {
138
+ mkdirSync(exampleDir, { recursive: true })
139
+ for (const [name, contents] of [['Button.tsx', EXAMPLE_COMPONENT], ['Button.stories.tsx', EXAMPLE_STORIES]] as const) {
140
+ writeFileSync(join(exampleDir, name), contents)
141
+ created.push(relative(root, join(exampleDir, name)))
142
+ }
143
+ }
144
+
66
145
  const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as { scripts?: Record<string, string>; dependencies?: Record<string, string>; devDependencies?: Record<string, string> }
67
146
  const added: string[] = []
68
147
  manifest.scripts ??= {}
@@ -75,7 +154,12 @@ export function initCommand(root: string, configDir: string, out: Output) {
75
154
 
76
155
  const has = (name: string) => manifest.dependencies?.[name] !== undefined || manifest.devDependencies?.[name] !== undefined
77
156
  const missing = DEPENDENCIES.filter((name) => !has(name))
78
- const missingDev = DEV_DEPENDENCIES.filter((name) => !has(name))
157
+ const missingDev = DEV_DEPENDENCIES.filter((name) => !has(name)).map((name) => (name === 'storybook' ? `storybook@${storybookVersion()}` : name))
158
+ // Docgen needs TypeScript 6's compiler API; TypeScript 7 (what new NitroUI apps get) has none.
159
+ const typescript = manifest.devDependencies?.typescript ?? manifest.dependencies?.typescript
160
+ if (typescript === undefined || !/typescript6|^[~^]?6\./.test(typescript)) {
161
+ missingDev.push('typescript@npm:@typescript/typescript6@^6.0.2', '@typescript/native@npm:typescript@7.0.2')
162
+ }
79
163
  const install = [
80
164
  ...(missing.length > 0 ? [`bun add ${missing.join(' ')}`] : []),
81
165
  ...(missingDev.length > 0 ? [`bun add -d ${missingDev.join(' ')}`] : []),
package/src/launch/run.ts CHANGED
@@ -244,7 +244,7 @@ async function startStorybook(options: RunOptions, network: boolean, out: Output
244
244
 
245
245
  const port = options.port ?? await freePort(6006, options.devicePort === undefined ? [] : [options.devicePort])
246
246
  const listenHost = network || (options.host !== undefined && !isLoopback(options.host)) ? '0.0.0.0' : undefined
247
- const args = [bin, 'dev', '--ci', '--no-open', '--exact-port', '--port', String(port), '--config-dir', options.configDir, ...(listenHost === undefined ? [] : ['--host', listenHost]), ...options.storybookArgs]
247
+ const args = [bin, 'dev', '--ci', '--exact-port', '--port', String(port), '--config-dir', options.configDir, ...(listenHost === undefined ? [] : ['--host', listenHost]), ...options.storybookArgs]
248
248
  const env: Record<string, string | undefined> = { ...process.env, [ENV.host]: options.host, [ENV.port]: options.devicePort?.toString() }
249
249
 
250
250
  let log: string | undefined
@@ -18,9 +18,17 @@ export interface NitroRenderer extends Renderer {
18
18
  export type StoryContext = StoryContextBase<NitroRenderer>
19
19
 
20
20
  export interface NitroParameters {
21
+ /**
22
+ * Where the story sits, as web Storybook's `layout` parameter: `padded` (default) keeps 16 points
23
+ * around it, `centered` centres it, `fullscreen` fills the canvas.
24
+ */
25
+ layout?: 'centered' | 'fullscreen' | 'padded'
21
26
  /** NitroUI renderer configuration. */
22
27
  nitroui?: {
23
- /** Fill the canvas instead of centring the story. */
28
+ /**
29
+ * @deprecated Use `layout`. Read only when `layout` is unset, for previews written by
30
+ * `nitro-storybook init` 0.1.0.
31
+ */
24
32
  layout?: 'centered' | 'fullscreen' | 'padded'
25
33
  }
26
34
  }
@@ -132,7 +132,7 @@ function printResult(result: StoryTestResult) {
132
132
  function startStorybook(base: URL) {
133
133
  const port = base.port === '' ? '6006' : base.port
134
134
  console.log(`Starting storybook dev on port ${port}`)
135
- const child = spawn('bunx', ['storybook', 'dev', '--ci', '--no-open', '--port', port], { stdio: ['ignore', 'inherit', 'inherit'] })
135
+ const child = spawn('bunx', ['storybook', 'dev', '--ci', '--port', port], { stdio: ['ignore', 'inherit', 'inherit'] })
136
136
  return child
137
137
  }
138
138