@hozo/behaviors 0.1.0 → 0.3.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 (58) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/README.md +16 -2
  3. package/dist/accessibility-focus.native.d.ts +23 -0
  4. package/dist/accessibility-focus.native.d.ts.map +1 -0
  5. package/dist/accessibility-focus.native.js +81 -0
  6. package/dist/accessibility-focus.native.js.map +1 -0
  7. package/dist/command-shortcut.d.ts +23 -0
  8. package/dist/command-shortcut.d.ts.map +1 -0
  9. package/dist/command-shortcut.js +47 -0
  10. package/dist/command-shortcut.js.map +1 -0
  11. package/dist/command-shortcut.native.d.ts +11 -0
  12. package/dist/command-shortcut.native.d.ts.map +1 -0
  13. package/dist/command-shortcut.native.js +11 -0
  14. package/dist/command-shortcut.native.js.map +1 -0
  15. package/dist/focus-scope.d.ts +9 -1
  16. package/dist/focus-scope.d.ts.map +1 -1
  17. package/dist/focus-scope.js +43 -11
  18. package/dist/focus-scope.js.map +1 -1
  19. package/dist/i18n.d.ts +140 -0
  20. package/dist/i18n.d.ts.map +1 -0
  21. package/dist/i18n.js +144 -0
  22. package/dist/i18n.js.map +1 -0
  23. package/dist/index.d.ts +3 -0
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +3 -0
  26. package/dist/index.js.map +1 -1
  27. package/dist/index.native.d.ts +3 -0
  28. package/dist/index.native.d.ts.map +1 -1
  29. package/dist/index.native.js +3 -0
  30. package/dist/index.native.js.map +1 -1
  31. package/dist/native.d.ts +3 -0
  32. package/dist/native.d.ts.map +1 -1
  33. package/dist/native.js +3 -0
  34. package/dist/native.js.map +1 -1
  35. package/dist/presence.d.ts +19 -0
  36. package/dist/presence.d.ts.map +1 -0
  37. package/dist/presence.js +96 -0
  38. package/dist/presence.js.map +1 -0
  39. package/dist/presence.native.d.ts +10 -0
  40. package/dist/presence.native.d.ts.map +1 -0
  41. package/dist/presence.native.js +18 -0
  42. package/dist/presence.native.js.map +1 -0
  43. package/dist/pressable-interaction.d.ts +30 -0
  44. package/dist/pressable-interaction.d.ts.map +1 -0
  45. package/dist/pressable-interaction.js +64 -0
  46. package/dist/pressable-interaction.js.map +1 -0
  47. package/package.json +7 -2
  48. package/src/accessibility-focus.native.ts +88 -0
  49. package/src/command-shortcut.native.ts +15 -0
  50. package/src/command-shortcut.ts +51 -0
  51. package/src/focus-scope.tsx +49 -8
  52. package/src/i18n.ts +198 -0
  53. package/src/index.native.ts +20 -0
  54. package/src/index.ts +24 -0
  55. package/src/native.ts +22 -0
  56. package/src/presence.native.ts +27 -0
  57. package/src/presence.ts +118 -0
  58. package/src/pressable-interaction.ts +79 -0
@@ -0,0 +1,88 @@
1
+ import type { ComponentRef } from 'react'
2
+ import { AccessibilityInfo, type View } from 'react-native'
3
+
4
+ export type HozoFocusTarget = ComponentRef<typeof View>
5
+ export type HozoFocusMover = (view: HozoFocusTarget) => void
6
+
7
+ /**
8
+ * Moving accessibility focus, with `@hozo/native` able to take over.
9
+ *
10
+ * ## Registered, not resolved, and that is a correction
11
+ *
12
+ * `docs/decisions/006-shipping-native-code.md` says the capability is reached
13
+ * "through a resolved provider, never imported", pointing at
14
+ * `packages/engine/src/safe-area.native.ts:50`, which does
15
+ * `try { require('react-native-safe-area-context') } catch {}`. That shape does
16
+ * not transfer here, and the reason is Metro rather than taste.
17
+ *
18
+ * Metro resolves `require` at bundle time. A literal `require` of a package that
19
+ * is not installed is a **build failure**, `try`/`catch` or not -- the catch runs
20
+ * at runtime and the bundler never gets there. Safe areas get away with it
21
+ * because that module is only in the graph when the compiler emitted a safe-area
22
+ * class: a project that writes none never imports it. This module is in the graph
23
+ * of every application that renders a `Dialog`, so a `require` here would make an
24
+ * optional package mandatory, and would break every existing app on upgrade.
25
+ *
26
+ * So the application hands the capability in, in two lines next to wherever it
27
+ * registers its root component:
28
+ *
29
+ * ```ts
30
+ * import { setAccessibilityFocusMover } from '@hozo/behaviors/native'
31
+ * import { moveAccessibilityFocus } from '@hozo/native'
32
+ *
33
+ * setAccessibilityFocusMover(moveAccessibilityFocus)
34
+ * ```
35
+ *
36
+ * `moveAccessibilityFocus` is `undefined` on iOS and when the native module is
37
+ * not in the binary, and the setter accepts that and keeps the default -- so the
38
+ * call needs no condition around it.
39
+ *
40
+ * ## The default is what this library has always done
41
+ *
42
+ * `AccessibilityInfo.sendAccessibilityEvent(view, 'focus')`, which works about
43
+ * half the time on Android (#484). An application that registers nothing is
44
+ * exactly as well off as it was, which is the third part of the decision's gate
45
+ * and the reason the capability was admitted at all.
46
+ *
47
+ * ## Why this is in `@hozo/behaviors/native`
48
+ *
49
+ * It has one consumer today -- `Dialog` -- and the first draft of this lived in
50
+ * `@hozo/patterns` for that reason. Registration moved it: a module holding one
51
+ * mutable binding costs nothing to load, where a provider resolution would have
52
+ * run a `require` in every package that imported it, and the application doing
53
+ * the registering should not have to reach into a widget package to do it.
54
+ * `@hozo/behaviors/native` is the entry point that already exists for API with no
55
+ * Web counterpart.
56
+ */
57
+ let registered: HozoFocusMover | undefined
58
+
59
+ /**
60
+ * Hand over a better way to move accessibility focus, or `undefined` to stop.
61
+ *
62
+ * Idempotent and last-wins. Registering twice is a sign of two roots, which an
63
+ * application can legitimately have -- a test harness mounting its own -- and
64
+ * neither a throw nor a warning would help it.
65
+ */
66
+ export function setAccessibilityFocusMover(mover: HozoFocusMover | undefined | null): void {
67
+ registered = mover ?? undefined
68
+ }
69
+
70
+ /** Whether something has been registered. Read by diagnostics, not by behaviour. */
71
+ export function hasAccessibilityFocusMover(): boolean {
72
+ return registered !== undefined
73
+ }
74
+
75
+ /**
76
+ * Put accessibility focus on `view`.
77
+ *
78
+ * Read at call time rather than captured, because registration happens during the
79
+ * application's startup and a module that captured the default at load would
80
+ * never see it.
81
+ */
82
+ export function moveAccessibilityFocus(view: HozoFocusTarget): void {
83
+ if (registered) {
84
+ registered(view)
85
+ return
86
+ }
87
+ AccessibilityInfo.sendAccessibilityEvent(view, 'focus')
88
+ }
@@ -0,0 +1,15 @@
1
+ import type { CommandShortcutOptions } from './command-shortcut.ts'
2
+
3
+ export type { CommandShortcutOptions }
4
+
5
+ export function isApplePlatform(): boolean {
6
+ return false
7
+ }
8
+
9
+ /**
10
+ * Nothing on React Native: a phone has no ⌘K, and a hardware keyboard reaches
11
+ * an application through APIs React Native does not expose as one event. The
12
+ * palette is opened from a control the application draws. Kept as a hook so a
13
+ * screen written once calls it on both platforms.
14
+ */
15
+ export function useCommandShortcut(_onTrigger: () => void, _options: CommandShortcutOptions = {}) {}
@@ -0,0 +1,51 @@
1
+ import { useEffect, useRef } from 'react'
2
+
3
+ export interface CommandShortcutOptions {
4
+ /** The letter, pressed with ⌘ on Apple platforms and Ctrl elsewhere; `k` by default. */
5
+ key?: string
6
+ /** Off while something else owns the keyboard. */
7
+ enabled?: boolean
8
+ }
9
+
10
+ /** ⌘ on an Apple platform, Ctrl elsewhere -- the modifier each one's own shortcuts use. */
11
+ export function isApplePlatform(): boolean {
12
+ if (typeof navigator === 'undefined') return false
13
+ const platform =
14
+ (navigator as { userAgentData?: { platform?: string } }).userAgentData?.platform ??
15
+ navigator.platform ??
16
+ ''
17
+ return /mac|iphone|ipad|ipod/i.test(platform)
18
+ }
19
+
20
+ /**
21
+ * Calls `onTrigger` for ⌘K on a Mac and Ctrl+K elsewhere, from anywhere on the
22
+ * page (#152).
23
+ *
24
+ * The browser's default is prevented only for the press that is handled:
25
+ * Ctrl+K is Chrome's "search from the address bar", and taking it away when
26
+ * nothing opens would be taking it for nothing. A press during IME
27
+ * composition is not a shortcut -- the composition owns the keyboard -- and
28
+ * neither is a held key repeating.
29
+ *
30
+ * A behaviour rather than part of `CommandPalette`, because a shortcut is
31
+ * useful without one: to focus a search field, or open a different panel.
32
+ */
33
+ export function useCommandShortcut(onTrigger: () => void, options: CommandShortcutOptions = {}) {
34
+ const { key = 'k', enabled = true } = options
35
+ const latest = useRef(onTrigger)
36
+ latest.current = onTrigger
37
+ useEffect(() => {
38
+ if (!enabled || typeof document === 'undefined') return
39
+ const apple = isApplePlatform()
40
+ const handle = (event: KeyboardEvent) => {
41
+ if (event.isComposing || event.repeat) return
42
+ const modifier = apple ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey
43
+ if (!modifier || event.altKey || event.shiftKey) return
44
+ if (event.key.toLowerCase() !== key.toLowerCase()) return
45
+ event.preventDefault()
46
+ latest.current()
47
+ }
48
+ document.addEventListener('keydown', handle)
49
+ return () => document.removeEventListener('keydown', handle)
50
+ }, [enabled, key])
51
+ }
@@ -31,6 +31,14 @@ export interface FocusScopeProps {
31
31
  trapped?: boolean
32
32
  autoFocus?: boolean
33
33
  restoreFocus?: boolean
34
+ /**
35
+ * Whether the scope holds focus. Turning it false does what unmounting
36
+ * does -- the trap is released and focus goes back to the opener -- for
37
+ * an overlay that stays mounted while it animates out (decision 007).
38
+ * Focus left inside a panel that is fading away would be on something
39
+ * nobody can use, and on nothing once the panel goes.
40
+ */
41
+ active?: boolean
34
42
  className?: string
35
43
  style?: CSSProperties
36
44
  }
@@ -38,6 +46,14 @@ export interface FocusScopeProps {
38
46
  const FOCUSABLE_SELECTOR =
39
47
  'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'
40
48
 
49
+ /**
50
+ * How long to keep trying to move focus in: ten tries a frame's length
51
+ * apart. A container hidden until it is measured shows by the first or
52
+ * second; ten is a bound, not a guess at a delay.
53
+ */
54
+ const INITIAL_FOCUS_ATTEMPTS = 10
55
+ const INITIAL_FOCUS_INTERVAL_MS = 16
56
+
41
57
  /**
42
58
  * Universal `<FocusScope>` component for Web.
43
59
  * Traps Tab key navigation, moves initial focus, and safely restores focus on unmount.
@@ -47,6 +63,7 @@ export function FocusScope({
47
63
  trapped = true,
48
64
  autoFocus = true,
49
65
  restoreFocus = true,
66
+ active = true,
50
67
  className,
51
68
  style,
52
69
  }: FocusScopeProps) {
@@ -55,6 +72,7 @@ export function FocusScope({
55
72
 
56
73
  useEffect(() => {
57
74
  if (typeof document === 'undefined') return
75
+ if (!active) return
58
76
 
59
77
  // Capture the trigger element that opened this scope
60
78
  if (restoreFocus && document.activeElement instanceof HTMLElement) {
@@ -64,7 +82,10 @@ export function FocusScope({
64
82
  const container = containerRef.current
65
83
  if (!container) return
66
84
 
67
- if (autoFocus) {
85
+ // Where focus goes on the way in: the first candidate, or the container
86
+ // itself (tabIndex="-1") so a screen reader still announces the role and
87
+ // name.
88
+ const initialTarget = (): HTMLElement => {
68
89
  const focusables = Array.from(
69
90
  container.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR),
70
91
  ).filter((el) => el.offsetParent !== null || el.getClientRects().length > 0)
@@ -75,13 +96,32 @@ export function FocusScope({
75
96
  }))
76
97
 
77
98
  const targetIdx = initialFocusIndex(candidates)
78
- if (targetIdx !== null && focusables[targetIdx]) {
79
- focusables[targetIdx].focus()
80
- } else {
81
- // Fallback: focus container itself (tabIndex="-1") so screen readers announce dialog role/label
82
- container.focus()
83
- }
99
+ return (targetIdx !== null && focusables[targetIdx]) || container
100
+ }
101
+
102
+ // `focus()` on an element that cannot take focus yet does nothing, and
103
+ // says nothing. `FloatingPositioner` is the case that found it: it draws
104
+ // its content `visibility: hidden` until it has measured, in an effect
105
+ // that runs after this one, so a popover's first focus landed on nothing
106
+ // and stayed on the trigger. Trying again shortly after covers that and
107
+ // any container like it -- but only while focus is still where the scope
108
+ // found it, so a person who has moved on is not pulled back. A timer
109
+ // rather than an animation frame: `focus()` resolves style itself, so it
110
+ // needs the positioner to have rendered, not the page to have painted --
111
+ // and frames do not run at all in a tab that is not being drawn.
112
+ let retry: ReturnType<typeof setTimeout> | undefined
113
+ const moveIn = (attempt: number) => {
114
+ const target = initialTarget()
115
+ target.focus()
116
+ if (document.activeElement === target || attempt >= INITIAL_FOCUS_ATTEMPTS) return
117
+ const stillWaiting =
118
+ document.activeElement === openerRef.current ||
119
+ document.activeElement === document.body ||
120
+ document.activeElement === null
121
+ if (!stillWaiting) return
122
+ retry = setTimeout(() => moveIn(attempt + 1), INITIAL_FOCUS_INTERVAL_MS)
84
123
  }
124
+ if (autoFocus) moveIn(0)
85
125
 
86
126
  const handleKeyDown = (event: KeyboardEvent) => {
87
127
  if (!trapped || event.key !== 'Tab') return
@@ -115,6 +155,7 @@ export function FocusScope({
115
155
  container.addEventListener('keydown', handleKeyDown)
116
156
 
117
157
  return () => {
158
+ clearTimeout(retry)
118
159
  container.removeEventListener('keydown', handleKeyDown)
119
160
  if (restoreFocus) {
120
161
  const opener = openerRef.current
@@ -128,7 +169,7 @@ export function FocusScope({
128
169
  }
129
170
  }
130
171
  }
131
- }, [trapped, autoFocus, restoreFocus])
172
+ }, [trapped, autoFocus, restoreFocus, active])
132
173
 
133
174
  return (
134
175
  <div
package/src/i18n.ts ADDED
@@ -0,0 +1,198 @@
1
+ // How Hozo's own strings and locale reach an application's i18n library
2
+ // (decision 008).
3
+ //
4
+ // Hozo does not translate. Applications already have a library for that --
5
+ // i18next, react-intl, Lingui -- with plural rules, interpolation and
6
+ // catalogues, and Hozo's strings belong in the same catalogue as the rest.
7
+ // So this is only the connection: a context carrying `locale`, `dir` and a
8
+ // `translate` function, the English every component falls back to, and two
9
+ // adapters that are a few lines each and typed structurally, so no
10
+ // `@hozo/*` package depends on any library.
11
+ //
12
+ // Platform-neutral on purpose: one file, imported by both entry points, so a
13
+ // provider on one side is the same object on the other.
14
+
15
+ import { createContext, createElement, type ReactNode, useCallback, useContext } from 'react'
16
+
17
+ /**
18
+ * Every string Hozo's components show or announce, in English, by key.
19
+ *
20
+ * Exported so a project can seed its catalogue from it, and so a test can
21
+ * check none is missing. Parameters are named (`{remaining}`), because every
22
+ * library this connects to interpolates by name.
23
+ */
24
+ export const hozoMessages = {
25
+ 'hozo.avatar.label': '{name}, {status}',
26
+ 'hozo.avatar.statusBusy': 'busy',
27
+ 'hozo.avatar.statusOffline': 'offline',
28
+ 'hozo.avatar.statusOnline': 'online',
29
+ 'hozo.badge.overflow': 'more than {max}',
30
+ 'hozo.bottomSheet.handle': 'Resize',
31
+ 'hozo.calendar.nextMonth': 'Next month',
32
+ 'hozo.calendar.previousMonth': 'Previous month',
33
+ 'hozo.calendar.rangeEnd': 'end of range',
34
+ 'hozo.calendar.rangeStart': 'start of range',
35
+ 'hozo.calendar.today': 'today',
36
+ 'hozo.chip.remove': 'Remove {label}',
37
+ 'hozo.color.black': 'black',
38
+ 'hozo.color.blue': 'blue',
39
+ 'hozo.color.cyan': 'cyan',
40
+ 'hozo.color.dark': 'dark {color}',
41
+ 'hozo.color.gray': 'gray',
42
+ 'hozo.color.green': 'green',
43
+ 'hozo.color.light': 'light {color}',
44
+ 'hozo.color.orange': 'orange',
45
+ 'hozo.color.pink': 'pink',
46
+ 'hozo.color.purple': 'purple',
47
+ 'hozo.color.red': 'red',
48
+ 'hozo.color.white': 'white',
49
+ 'hozo.color.yellow': 'yellow',
50
+ 'hozo.colorPicker.alpha': 'Opacity',
51
+ 'hozo.colorPicker.alphaValue': '{value}% opaque',
52
+ 'hozo.colorPicker.described': '{name}, {hex}',
53
+ 'hozo.colorPicker.eyeDropper': 'Pick a colour from the screen',
54
+ 'hozo.colorPicker.hex': 'Hex colour',
55
+ 'hozo.colorPicker.hue': 'Hue',
56
+ 'hozo.colorPicker.hueValue': '{degrees} degrees, {name}',
57
+ 'hozo.colorPicker.lightness': 'Lightness',
58
+ 'hozo.colorPicker.percent': '{value}%',
59
+ 'hozo.colorPicker.presets': 'Presets',
60
+ 'hozo.colorPicker.saturation': 'Saturation',
61
+ 'hozo.commandPalette.empty': 'No results',
62
+ 'hozo.commandPalette.label': 'Command palette',
63
+ 'hozo.commandPalette.oneResult': '1 result',
64
+ 'hozo.commandPalette.results': '{count} results',
65
+ 'hozo.datePicker.dialog': 'Choose a date',
66
+ 'hozo.dateRangePicker.dialog': 'Choose a range of dates',
67
+ 'hozo.dateTimePicker.dialog': 'Choose a date and time',
68
+ 'hozo.dateTimePicker.done': 'Done',
69
+ 'hozo.fileDropzone.selectedMany': '{count} files selected',
70
+ 'hozo.fileDropzone.selectedOne': '{name} selected, {size}',
71
+ 'hozo.fileDropzone.tooLarge': '{name} is too large: {size}, and the limit is {limit}',
72
+ 'hozo.fileDropzone.tooMany': '{name} was not added: one pick takes {max}',
73
+ 'hozo.fileDropzone.tooSmall': '{name} is too small: {size}',
74
+ 'hozo.fileDropzone.unavailable': 'No file picker is available',
75
+ 'hozo.fileDropzone.wrongType': '{name} is not an accepted kind of file',
76
+ 'hozo.nativeSelect.cancel': 'Cancel',
77
+ 'hozo.otpInput.hint': '{length} characters',
78
+ 'hozo.pagination.label': 'Pagination',
79
+ 'hozo.pagination.next': 'Next page',
80
+ 'hozo.pagination.page': 'Page {page}',
81
+ 'hozo.pagination.previous': 'Previous page',
82
+ 'hozo.stepper.completed': 'completed',
83
+ 'hozo.stepper.current': 'current',
84
+ 'hozo.stepper.error': 'has an error',
85
+ 'hozo.stepper.label': 'Progress',
86
+ 'hozo.stepper.step': 'Step {step} of {count}: {label}, {status}',
87
+ 'hozo.stepper.upcoming': 'not started',
88
+ 'hozo.textArea.remaining': '{remaining} of {maxLength} characters left',
89
+ 'hozo.timePicker.decrease': 'Decrease',
90
+ 'hozo.timePicker.empty': '--',
91
+ 'hozo.timePicker.hour': 'Hour',
92
+ 'hozo.timePicker.increase': 'Increase',
93
+ 'hozo.timePicker.minute': 'Minute',
94
+ 'hozo.timePicker.period': 'AM or PM',
95
+ } as const
96
+
97
+ export type HozoMessageKey = keyof typeof hozoMessages
98
+ export type HozoMessageParams = Readonly<Record<string, string | number>>
99
+
100
+ export interface HozoI18n {
101
+ /** BCP 47. Used for `Intl`: dates, numbers, the first day of the week. */
102
+ locale?: string
103
+ /**
104
+ * Which way the content runs. Read by behaviours that cannot ask the
105
+ * platform; never applied. The Web's direction is `<html dir>` and
106
+ * Native's is `I18nManager`, and both are the application's to set.
107
+ */
108
+ dir?: 'ltr' | 'rtl'
109
+ /**
110
+ * The project's translation of `key`. `fallback` is Hozo's English with
111
+ * `params` already filled in, for a library that shows its default when a
112
+ * key is missing.
113
+ */
114
+ translate?: (key: HozoMessageKey, params: HozoMessageParams, fallback: string) => string
115
+ }
116
+
117
+ const HozoI18nContext = createContext<HozoI18n>({})
118
+
119
+ export interface HozoI18nProviderProps {
120
+ value: HozoI18n
121
+ children?: ReactNode
122
+ }
123
+
124
+ /**
125
+ * Puts a project's i18n where Hozo's components can read it.
126
+ *
127
+ * Give it a new `value` when the language changes -- `useMemo` on the
128
+ * language -- and every Hozo string below re-renders in it.
129
+ */
130
+ export function HozoI18nProvider({ value, children }: HozoI18nProviderProps) {
131
+ return createElement(HozoI18nContext.Provider, { value }, children)
132
+ }
133
+
134
+ export function useHozoI18n(): HozoI18n {
135
+ return useContext(HozoI18nContext)
136
+ }
137
+
138
+ function interpolate(template: string, params: HozoMessageParams): string {
139
+ return template.replace(/\{(\w+)\}/g, (whole, name: string) =>
140
+ name in params ? String(params[name]) : whole,
141
+ )
142
+ }
143
+
144
+ /**
145
+ * A function resolving one of Hozo's strings: the component's own prop if
146
+ * there is one, then the project's translation, then Hozo's English.
147
+ */
148
+ export function useHozoMessage() {
149
+ const { translate } = useHozoI18n()
150
+ return useCallback(
151
+ (key: HozoMessageKey, params: HozoMessageParams = {}, explicit?: string): string => {
152
+ if (explicit !== undefined) return explicit
153
+ const fallback = interpolate(hozoMessages[key], params)
154
+ return translate ? translate(key, params, fallback) : fallback
155
+ },
156
+ [translate],
157
+ )
158
+ }
159
+
160
+ /** The part of an i18next instance this reads. */
161
+ export interface I18nextLike {
162
+ t(key: string, options?: Record<string, unknown>): string
163
+ language?: string
164
+ dir?(language?: string): 'ltr' | 'rtl'
165
+ }
166
+
167
+ /**
168
+ * Hozo's i18n from an i18next instance: Hozo's keys are i18next keys, and
169
+ * Hozo's English is i18next's `defaultValue`.
170
+ */
171
+ export function fromI18next(i18n: I18nextLike): HozoI18n {
172
+ return {
173
+ locale: i18n.language,
174
+ dir: i18n.dir?.(i18n.language),
175
+ translate: (key, params, fallback) => i18n.t(key, { ...params, defaultValue: fallback }),
176
+ }
177
+ }
178
+
179
+ /** The part of a react-intl `IntlShape` this reads. */
180
+ export interface ReactIntlLike {
181
+ formatMessage(
182
+ descriptor: { id: string; defaultMessage?: string },
183
+ values?: Record<string, string | number>,
184
+ ): string
185
+ locale?: string
186
+ }
187
+
188
+ /**
189
+ * Hozo's i18n from react-intl: Hozo's keys are message ids, and Hozo's
190
+ * English is the `defaultMessage`.
191
+ */
192
+ export function fromReactIntl(intl: ReactIntlLike): HozoI18n {
193
+ return {
194
+ locale: intl.locale,
195
+ translate: (key, params, fallback) =>
196
+ intl.formatMessage({ id: key, defaultMessage: fallback }, params),
197
+ }
198
+ }
@@ -1,3 +1,8 @@
1
+ export {
2
+ type CommandShortcutOptions,
3
+ isApplePlatform,
4
+ useCommandShortcut,
5
+ } from './command-shortcut.native.ts'
1
6
  export {
2
7
  DismissableLayer,
3
8
  type DismissableLayerProps,
@@ -44,6 +49,20 @@ export {
44
49
  useHoverTrigger,
45
50
  useTooltipGroup,
46
51
  } from './hover-trigger.native.tsx'
52
+ export {
53
+ fromI18next,
54
+ fromReactIntl,
55
+ type HozoI18n,
56
+ HozoI18nProvider,
57
+ type HozoI18nProviderProps,
58
+ type HozoMessageKey,
59
+ type HozoMessageParams,
60
+ hozoMessages,
61
+ type I18nextLike,
62
+ type ReactIntlLike,
63
+ useHozoI18n,
64
+ useHozoMessage,
65
+ } from './i18n.ts'
47
66
  export {
48
67
  LiveRegion,
49
68
  type LiveRegionMode,
@@ -56,6 +75,7 @@ export {
56
75
  type PortalProps,
57
76
  PortalProvider,
58
77
  } from './portal.native.tsx'
78
+ export { type PresenceBinding, type PresenceState, usePresence } from './presence.native.ts'
59
79
  export {
60
80
  nextIndex,
61
81
  type Orientation,
package/src/index.ts CHANGED
@@ -1,3 +1,8 @@
1
+ export {
2
+ type CommandShortcutOptions,
3
+ isApplePlatform,
4
+ useCommandShortcut,
5
+ } from './command-shortcut.ts'
1
6
  export {
2
7
  DismissableLayer,
3
8
  type DismissableLayerProps,
@@ -44,6 +49,20 @@ export {
44
49
  useHoverTrigger,
45
50
  useTooltipGroup,
46
51
  } from './hover-trigger.tsx'
52
+ export {
53
+ fromI18next,
54
+ fromReactIntl,
55
+ type HozoI18n,
56
+ HozoI18nProvider,
57
+ type HozoI18nProviderProps,
58
+ type HozoMessageKey,
59
+ type HozoMessageParams,
60
+ hozoMessages,
61
+ type I18nextLike,
62
+ type ReactIntlLike,
63
+ useHozoI18n,
64
+ useHozoMessage,
65
+ } from './i18n.ts'
47
66
  export {
48
67
  LiveRegion,
49
68
  type LiveRegionMode,
@@ -56,6 +75,11 @@ export {
56
75
  type PortalProps,
57
76
  PortalProvider,
58
77
  } from './portal.tsx'
78
+ export {
79
+ type PresenceBinding,
80
+ type PresenceState,
81
+ usePresence,
82
+ } from './presence.ts'
59
83
  export {
60
84
  nextIndex,
61
85
  type Orientation,
package/src/native.ts CHANGED
@@ -1,3 +1,10 @@
1
+ export {
2
+ type HozoFocusMover,
3
+ type HozoFocusTarget,
4
+ hasAccessibilityFocusMover,
5
+ moveAccessibilityFocus,
6
+ setAccessibilityFocusMover,
7
+ } from './accessibility-focus.native.ts'
1
8
  export type { Placement } from './floating-geometry.ts'
2
9
  export {
3
10
  FloatingPositioner,
@@ -12,4 +19,19 @@ export {
12
19
  type UseHoverTriggerReturn,
13
20
  useHoverTrigger,
14
21
  } from './hover-trigger.native.tsx'
22
+ export {
23
+ fromI18next,
24
+ fromReactIntl,
25
+ type HozoI18n,
26
+ HozoI18nProvider,
27
+ type HozoI18nProviderProps,
28
+ type HozoMessageKey,
29
+ type HozoMessageParams,
30
+ hozoMessages,
31
+ type I18nextLike,
32
+ type ReactIntlLike,
33
+ useHozoI18n,
34
+ useHozoMessage,
35
+ } from './i18n.ts'
15
36
  export { Portal, PortalHost, type PortalProps, PortalProvider } from './portal.native.tsx'
37
+ export { type PresenceBinding, type PresenceState, usePresence } from './presence.native.ts'
@@ -0,0 +1,27 @@
1
+ // Keeping an element mounted while it animates out, on React Native
2
+ // (decision 007, slice 2). The Web half is `./presence.ts`.
3
+ //
4
+ // There is no computed style to read an exit's length from here, so the
5
+ // caller says when it is over: it runs its own `Animated` exit while
6
+ // `state` is `'closed'` and calls `done` from the completion callback.
7
+
8
+ import { useCallback, useState } from 'react'
9
+
10
+ export type PresenceState = 'open' | 'closed'
11
+
12
+ export interface PresenceBinding {
13
+ /** Whether to render the element at all. */
14
+ mounted: boolean
15
+ state: PresenceState
16
+ /** Ends the exit. Ignored once the element is shown again. */
17
+ done: () => void
18
+ }
19
+
20
+ export function usePresence(show: boolean): PresenceBinding {
21
+ const [mounted, setMounted] = useState(show)
22
+ if (show && !mounted) setMounted(true)
23
+ const done = useCallback(() => {
24
+ if (!show) setMounted(false)
25
+ }, [show])
26
+ return { mounted, state: show ? 'open' : 'closed', done }
27
+ }