@hozo/behaviors 0.1.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 (118) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +80 -0
  3. package/dist/dismissable-layer.d.ts +17 -0
  4. package/dist/dismissable-layer.d.ts.map +1 -0
  5. package/dist/dismissable-layer.js +67 -0
  6. package/dist/dismissable-layer.js.map +1 -0
  7. package/dist/dismissable-layer.native.d.ts +28 -0
  8. package/dist/dismissable-layer.native.d.ts.map +1 -0
  9. package/dist/dismissable-layer.native.js +38 -0
  10. package/dist/dismissable-layer.native.js.map +1 -0
  11. package/dist/floating-geometry.d.ts +63 -0
  12. package/dist/floating-geometry.d.ts.map +1 -0
  13. package/dist/floating-geometry.js +191 -0
  14. package/dist/floating-geometry.js.map +1 -0
  15. package/dist/floating-positioner.d.ts +24 -0
  16. package/dist/floating-positioner.d.ts.map +1 -0
  17. package/dist/floating-positioner.js +110 -0
  18. package/dist/floating-positioner.js.map +1 -0
  19. package/dist/floating-positioner.native.d.ts +43 -0
  20. package/dist/floating-positioner.native.d.ts.map +1 -0
  21. package/dist/floating-positioner.native.js +82 -0
  22. package/dist/floating-positioner.native.js.map +1 -0
  23. package/dist/focus-scope.d.ts +31 -0
  24. package/dist/focus-scope.d.ts.map +1 -0
  25. package/dist/focus-scope.js +96 -0
  26. package/dist/focus-scope.js.map +1 -0
  27. package/dist/focus-scope.native.d.ts +33 -0
  28. package/dist/focus-scope.native.d.ts.map +1 -0
  29. package/dist/focus-scope.native.js +25 -0
  30. package/dist/focus-scope.native.js.map +1 -0
  31. package/dist/hover-geometry.d.ts +64 -0
  32. package/dist/hover-geometry.d.ts.map +1 -0
  33. package/dist/hover-geometry.js +146 -0
  34. package/dist/hover-geometry.js.map +1 -0
  35. package/dist/hover-trigger.d.ts +64 -0
  36. package/dist/hover-trigger.d.ts.map +1 -0
  37. package/dist/hover-trigger.js +174 -0
  38. package/dist/hover-trigger.js.map +1 -0
  39. package/dist/hover-trigger.native.d.ts +45 -0
  40. package/dist/hover-trigger.native.d.ts.map +1 -0
  41. package/dist/hover-trigger.native.js +101 -0
  42. package/dist/hover-trigger.native.js.map +1 -0
  43. package/dist/index.d.ts +12 -0
  44. package/dist/index.d.ts.map +1 -0
  45. package/dist/index.js +12 -0
  46. package/dist/index.js.map +1 -0
  47. package/dist/index.native.d.ts +12 -0
  48. package/dist/index.native.d.ts.map +1 -0
  49. package/dist/index.native.js +12 -0
  50. package/dist/index.native.js.map +1 -0
  51. package/dist/live-region.d.ts +19 -0
  52. package/dist/live-region.d.ts.map +1 -0
  53. package/dist/live-region.js +51 -0
  54. package/dist/live-region.js.map +1 -0
  55. package/dist/live-region.native.d.ts +31 -0
  56. package/dist/live-region.native.d.ts.map +1 -0
  57. package/dist/live-region.native.js +38 -0
  58. package/dist/live-region.native.js.map +1 -0
  59. package/dist/native.d.ts +5 -0
  60. package/dist/native.d.ts.map +1 -0
  61. package/dist/native.js +4 -0
  62. package/dist/native.js.map +1 -0
  63. package/dist/portal.d.ts +26 -0
  64. package/dist/portal.d.ts.map +1 -0
  65. package/dist/portal.js +41 -0
  66. package/dist/portal.js.map +1 -0
  67. package/dist/portal.native.d.ts +44 -0
  68. package/dist/portal.native.d.ts.map +1 -0
  69. package/dist/portal.native.js +79 -0
  70. package/dist/portal.native.js.map +1 -0
  71. package/dist/roving-focus-rules.d.ts +13 -0
  72. package/dist/roving-focus-rules.d.ts.map +1 -0
  73. package/dist/roving-focus-rules.js +49 -0
  74. package/dist/roving-focus-rules.js.map +1 -0
  75. package/dist/roving-focus.d.ts +27 -0
  76. package/dist/roving-focus.d.ts.map +1 -0
  77. package/dist/roving-focus.js +52 -0
  78. package/dist/roving-focus.js.map +1 -0
  79. package/dist/roving-focus.native.d.ts +36 -0
  80. package/dist/roving-focus.native.d.ts.map +1 -0
  81. package/dist/roving-focus.native.js +28 -0
  82. package/dist/roving-focus.native.js.map +1 -0
  83. package/dist/text-child.d.ts +4 -0
  84. package/dist/text-child.d.ts.map +1 -0
  85. package/dist/text-child.js +17 -0
  86. package/dist/text-child.js.map +1 -0
  87. package/dist/text-child.native.d.ts +14 -0
  88. package/dist/text-child.native.d.ts.map +1 -0
  89. package/dist/text-child.native.js +42 -0
  90. package/dist/text-child.native.js.map +1 -0
  91. package/dist/typeahead.d.ts +36 -0
  92. package/dist/typeahead.d.ts.map +1 -0
  93. package/dist/typeahead.js +97 -0
  94. package/dist/typeahead.js.map +1 -0
  95. package/package.json +82 -0
  96. package/src/dismissable-layer.native.tsx +72 -0
  97. package/src/dismissable-layer.tsx +106 -0
  98. package/src/floating-geometry.ts +306 -0
  99. package/src/floating-positioner.native.tsx +155 -0
  100. package/src/floating-positioner.tsx +173 -0
  101. package/src/focus-scope.native.tsx +53 -0
  102. package/src/focus-scope.tsx +143 -0
  103. package/src/hover-geometry.ts +182 -0
  104. package/src/hover-trigger.native.tsx +179 -0
  105. package/src/hover-trigger.tsx +303 -0
  106. package/src/index.native.ts +77 -0
  107. package/src/index.ts +77 -0
  108. package/src/live-region.native.tsx +61 -0
  109. package/src/live-region.tsx +74 -0
  110. package/src/native.ts +15 -0
  111. package/src/portal.native.tsx +130 -0
  112. package/src/portal.tsx +68 -0
  113. package/src/roving-focus-rules.ts +79 -0
  114. package/src/roving-focus.native.tsx +81 -0
  115. package/src/roving-focus.tsx +118 -0
  116. package/src/text-child.native.tsx +44 -0
  117. package/src/text-child.ts +19 -0
  118. package/src/typeahead.ts +120 -0
@@ -0,0 +1,130 @@
1
+ import React, { createContext, type ReactNode, useContext, useEffect, useId, useState } from 'react'
2
+ import { View } from 'react-native'
3
+
4
+ export interface PortalProps {
5
+ /**
6
+ * Tailwind classes, the same prop the Web half takes.
7
+ *
8
+ * On a tag the compiler lowers it is gone by runtime, replaced by a
9
+ * `StyleSheet` entry. Anywhere else it is carried and ignored here --
10
+ * this side has no CSS engine to resolve a class list against -- and
11
+ * the type still has to accept it, because an app is type-checked
12
+ * against the source the compiler reads rather than its output.
13
+ */
14
+ className?: string
15
+ children?: ReactNode
16
+ name?: string
17
+ disabled?: boolean
18
+ }
19
+
20
+ type PortalMethods = {
21
+ mount: (id: string, children: ReactNode) => void
22
+ update: (id: string, children: ReactNode) => void
23
+ unmount: (id: string) => void
24
+ }
25
+
26
+ const PortalContext = createContext<PortalMethods | null>(null)
27
+
28
+ /**
29
+ * Global PortalProvider for React Native applications.
30
+ * Typically placed at the root of the app next to the root View.
31
+ */
32
+ export function PortalProvider({ children }: { children: ReactNode }) {
33
+ const [items, setItems] = useState<Map<string, ReactNode>>(() => new Map())
34
+
35
+ const methods: PortalMethods = {
36
+ mount: (id, node) => {
37
+ setItems((prev) => {
38
+ const next = new Map(prev)
39
+ next.set(id, node)
40
+ return next
41
+ })
42
+ },
43
+ update: (id, node) => {
44
+ setItems((prev) => {
45
+ const next = new Map(prev)
46
+ next.set(id, node)
47
+ return next
48
+ })
49
+ },
50
+ unmount: (id) => {
51
+ setItems((prev) => {
52
+ const next = new Map(prev)
53
+ next.delete(id)
54
+ return next
55
+ })
56
+ },
57
+ }
58
+
59
+ return (
60
+ <PortalContext.Provider value={methods}>
61
+ {children}
62
+ <PortalHost items={items} />
63
+ </PortalContext.Provider>
64
+ )
65
+ }
66
+
67
+ /**
68
+ * Root host that renders the active portaled items at the top of the React Native view hierarchy.
69
+ */
70
+ export function PortalHost({
71
+ items: directItems,
72
+ }: {
73
+ items?: Map<string, ReactNode>
74
+ /**
75
+ * Accepted and unused, so the two halves agree on the prop every other
76
+ * component takes. The rest of this component's props do not agree --
77
+ * the Web half is a marker `<div>` taking an `id`, this one renders the
78
+ * items -- which is a divergence of its own and not this one's to fix.
79
+ */
80
+ className?: string
81
+ }) {
82
+ if (!directItems || directItems.size === 0) {
83
+ return null
84
+ }
85
+
86
+ return React.createElement(
87
+ View,
88
+ {
89
+ pointerEvents: 'box-none',
90
+ style: {
91
+ position: 'absolute',
92
+ top: 0,
93
+ left: 0,
94
+ right: 0,
95
+ bottom: 0,
96
+ },
97
+ },
98
+ Array.from(directItems.entries()).map(([id, node]) => (
99
+ <React.Fragment key={id}>{node}</React.Fragment>
100
+ )),
101
+ )
102
+ }
103
+
104
+ /**
105
+ * Universal `<Portal>` component for React Native.
106
+ * Teleports children to the nearest `PortalHost` / `PortalProvider`.
107
+ */
108
+ export function Portal({ children, disabled = false }: PortalProps) {
109
+ const portal = useContext(PortalContext)
110
+ const id = useId()
111
+
112
+ useEffect(() => {
113
+ if (disabled || !portal) return
114
+ portal.mount(id, children)
115
+ return () => {
116
+ portal.unmount(id)
117
+ }
118
+ }, [disabled, portal, id, children])
119
+
120
+ useEffect(() => {
121
+ if (disabled || !portal) return
122
+ portal.update(id, children)
123
+ }, [disabled, portal, id, children])
124
+
125
+ if (disabled || !portal) {
126
+ return <>{children}</>
127
+ }
128
+
129
+ return null
130
+ }
package/src/portal.tsx ADDED
@@ -0,0 +1,68 @@
1
+ import { createContext, type ReactNode, useContext, useEffect, useState } from 'react'
2
+ import { createPortal } from 'react-dom'
3
+
4
+ export interface PortalProps {
5
+ children?: ReactNode
6
+ container?: Element | DocumentFragment | null
7
+ disabled?: boolean
8
+ }
9
+
10
+ const PortalContext = createContext<{
11
+ container: Element | DocumentFragment | null
12
+ }>({
13
+ container: null,
14
+ })
15
+
16
+ /**
17
+ * Optional PortalProvider to override default portal mounting target.
18
+ */
19
+ export function PortalProvider({
20
+ children,
21
+ container,
22
+ }: {
23
+ children: ReactNode
24
+ container: Element | DocumentFragment | null
25
+ }) {
26
+ return <PortalContext.Provider value={{ container }}>{children}</PortalContext.Provider>
27
+ }
28
+
29
+ /**
30
+ * Universal `<Portal>` component for Web.
31
+ * Renders children into a DOM container (default: `document.body`) outside parent DOM hierarchy.
32
+ */
33
+ export function Portal({ children, container, disabled = false }: PortalProps) {
34
+ const context = useContext(PortalContext)
35
+ const [mounted, setMounted] = useState(false)
36
+
37
+ useEffect(() => {
38
+ setMounted(true)
39
+ }, [])
40
+
41
+ if (disabled) {
42
+ return <>{children}</>
43
+ }
44
+
45
+ if (!mounted || typeof document === 'undefined') {
46
+ return null
47
+ }
48
+
49
+ const target = container ?? context.container ?? document.body
50
+ if (!target) {
51
+ return null
52
+ }
53
+
54
+ return createPortal(children, target)
55
+ }
56
+
57
+ /**
58
+ * Marker host element for Web (acts as default target anchor if placed explicitly).
59
+ */
60
+ export function PortalHost({
61
+ id = '__hozo_portal_host',
62
+ className,
63
+ }: {
64
+ id?: string
65
+ className?: string
66
+ }) {
67
+ return <div id={id} className={className} />
68
+ }
@@ -0,0 +1,79 @@
1
+ export type Orientation = 'horizontal' | 'vertical' | 'both'
2
+ export type RovingKey = 'ArrowLeft' | 'ArrowRight' | 'ArrowUp' | 'ArrowDown' | 'Home' | 'End'
3
+
4
+ export interface RovingOptions {
5
+ count: number
6
+ active: number
7
+ orientation?: Orientation
8
+ wrap?: boolean
9
+ disabled?: readonly number[]
10
+ rtl?: boolean
11
+ }
12
+
13
+ function arrowStep(
14
+ key: RovingKey,
15
+ horizontal: boolean,
16
+ vertical: boolean,
17
+ rtl: boolean,
18
+ ): number | null {
19
+ switch (key) {
20
+ case 'ArrowLeft':
21
+ return horizontal ? (rtl ? 1 : -1) : null
22
+ case 'ArrowRight':
23
+ return horizontal ? (rtl ? -1 : 1) : null
24
+ case 'ArrowUp':
25
+ return vertical ? -1 : null
26
+ case 'ArrowDown':
27
+ return vertical ? 1 : null
28
+ default:
29
+ return null
30
+ }
31
+ }
32
+
33
+ function seek(
34
+ from: number,
35
+ step: number,
36
+ count: number,
37
+ disabled: readonly number[],
38
+ wrap: boolean,
39
+ active: number,
40
+ ): number {
41
+ let index = from
42
+ for (let moved = 0; moved <= count; moved += 1) {
43
+ if (index < 0 || index >= count) {
44
+ if (!wrap) return active
45
+ index = index < 0 ? count - 1 : 0
46
+ }
47
+ if (!disabled.includes(index)) return index
48
+ index += step
49
+ }
50
+ return active
51
+ }
52
+
53
+ export function nextIndex(key: RovingKey, options: RovingOptions): number | null {
54
+ const {
55
+ count,
56
+ active,
57
+ orientation = 'horizontal',
58
+ wrap = true,
59
+ disabled = [],
60
+ rtl = false,
61
+ } = options
62
+ if (count <= 0) return null
63
+
64
+ const horizontal = orientation === 'horizontal' || orientation === 'both'
65
+ const vertical = orientation === 'vertical' || orientation === 'both'
66
+
67
+ if (key === 'Home') return seek(0, 1, count, disabled, false, active)
68
+ if (key === 'End') return seek(count - 1, -1, count, disabled, false, active)
69
+
70
+ const step = arrowStep(key, horizontal, vertical, rtl)
71
+ if (step === null) return null
72
+ return seek(active + step, step, count, disabled, wrap, active)
73
+ }
74
+
75
+ export function tabStops(options: Pick<RovingOptions, 'count' | 'active' | 'disabled'>): number[] {
76
+ const { count, active, disabled = [] } = options
77
+ const stop = disabled.includes(active) ? seek(0, 1, count, disabled, false, active) : active
78
+ return Array.from({ length: count }, (_, index) => (index === stop ? 0 : -1))
79
+ }
@@ -0,0 +1,81 @@
1
+ import React, { createContext, type ReactNode, useContext, useMemo } from 'react'
2
+ import { type StyleProp, View, type ViewStyle } from 'react-native'
3
+
4
+ import type { Orientation } from './roving-focus-rules.ts'
5
+
6
+ export {
7
+ nextIndex,
8
+ type Orientation,
9
+ type RovingKey,
10
+ type RovingOptions,
11
+ tabStops,
12
+ } from './roving-focus-rules.ts'
13
+
14
+ interface RovingFocusContextValue {
15
+ active: number
16
+ onItemFocus: (index: number) => void
17
+ }
18
+
19
+ const RovingFocusContext = createContext<RovingFocusContextValue | null>(null)
20
+
21
+ export interface RovingFocusGroupProps {
22
+ /**
23
+ * Tailwind classes, the same prop the Web half takes.
24
+ *
25
+ * On a tag the compiler lowers it is gone by runtime, replaced by a
26
+ * `StyleSheet` entry. Anywhere else it is carried and ignored here --
27
+ * this side has no CSS engine to resolve a class list against -- and
28
+ * the type still has to accept it, because an app is type-checked
29
+ * against the source the compiler reads rather than its output.
30
+ */
31
+ className?: string
32
+ children?: ReactNode
33
+ count: number
34
+ active: number
35
+ onActiveChange: (index: number) => void
36
+ orientation?: Orientation
37
+ wrap?: boolean
38
+ disabled?: readonly number[]
39
+ rtl?: boolean
40
+ style?: StyleProp<ViewStyle>
41
+ }
42
+
43
+ /**
44
+ * Universal `<RovingFocusGroup>` component for React Native.
45
+ */
46
+ export function RovingFocusGroup({
47
+ children,
48
+ active,
49
+ onActiveChange,
50
+ style,
51
+ ...props
52
+ }: RovingFocusGroupProps) {
53
+ const contextValue = useMemo<RovingFocusContextValue>(
54
+ () => ({
55
+ active,
56
+ onItemFocus: onActiveChange,
57
+ }),
58
+ [active, onActiveChange],
59
+ )
60
+
61
+ return React.createElement(
62
+ View,
63
+ { style, ...props },
64
+ React.createElement(RovingFocusContext.Provider, { value: contextValue }, children),
65
+ )
66
+ }
67
+
68
+ export function useRovingItem(index: number) {
69
+ const context = useContext(RovingFocusContext)
70
+ if (!context) {
71
+ return {
72
+ isActive: true,
73
+ onFocus: () => {},
74
+ }
75
+ }
76
+
77
+ return {
78
+ isActive: context.active === index,
79
+ onFocus: () => context.onItemFocus(index),
80
+ }
81
+ }
@@ -0,0 +1,118 @@
1
+ import {
2
+ type CSSProperties,
3
+ createContext,
4
+ type KeyboardEvent,
5
+ type ReactNode,
6
+ useCallback,
7
+ useContext,
8
+ useMemo,
9
+ } from 'react'
10
+
11
+ import { nextIndex, type Orientation, type RovingKey, tabStops } from './roving-focus-rules.ts'
12
+
13
+ export {
14
+ nextIndex,
15
+ type Orientation,
16
+ type RovingKey,
17
+ type RovingOptions,
18
+ tabStops,
19
+ } from './roving-focus-rules.ts'
20
+
21
+ /** Context for composite roving focus items */
22
+ interface RovingFocusContextValue {
23
+ active: number
24
+ tabStops: number[]
25
+ onItemFocus: (index: number) => void
26
+ onItemKeyDown: (index: number, event: KeyboardEvent) => void
27
+ }
28
+
29
+ const RovingFocusContext = createContext<RovingFocusContextValue | null>(null)
30
+
31
+ export interface RovingFocusGroupProps {
32
+ children?: ReactNode
33
+ count: number
34
+ active: number
35
+ onActiveChange: (index: number) => void
36
+ orientation?: Orientation
37
+ wrap?: boolean
38
+ disabled?: readonly number[]
39
+ rtl?: boolean
40
+ className?: string
41
+ style?: CSSProperties
42
+ }
43
+
44
+ /**
45
+ * Universal `<RovingFocusGroup>` component for Web.
46
+ * Coordinates 1D and 2D arrow key navigation with a single active tab stop.
47
+ */
48
+ export function RovingFocusGroup({
49
+ children,
50
+ count,
51
+ active,
52
+ onActiveChange,
53
+ orientation = 'horizontal',
54
+ wrap = true,
55
+ disabled = [],
56
+ rtl = false,
57
+ className,
58
+ style,
59
+ }: RovingFocusGroupProps) {
60
+ const stops = useMemo(() => tabStops({ count, active, disabled }), [count, active, disabled])
61
+
62
+ const handleItemKeyDown = useCallback(
63
+ (index: number, event: KeyboardEvent) => {
64
+ const key = event.key as RovingKey
65
+ const next = nextIndex(key, {
66
+ count,
67
+ active: index,
68
+ orientation,
69
+ wrap,
70
+ disabled,
71
+ rtl,
72
+ })
73
+
74
+ if (next !== null && next !== index) {
75
+ event.preventDefault()
76
+ onActiveChange(next)
77
+ }
78
+ },
79
+ [count, orientation, wrap, disabled, rtl, onActiveChange],
80
+ )
81
+
82
+ const contextValue = useMemo<RovingFocusContextValue>(
83
+ () => ({
84
+ active,
85
+ tabStops: stops,
86
+ onItemFocus: onActiveChange,
87
+ onItemKeyDown: handleItemKeyDown,
88
+ }),
89
+ [active, stops, onActiveChange, handleItemKeyDown],
90
+ )
91
+
92
+ return (
93
+ <RovingFocusContext.Provider value={contextValue}>
94
+ <div className={className} style={style}>
95
+ {children}
96
+ </div>
97
+ </RovingFocusContext.Provider>
98
+ )
99
+ }
100
+
101
+ export function useRovingItem(index: number) {
102
+ const context = useContext(RovingFocusContext)
103
+ if (!context) {
104
+ return {
105
+ tabIndex: 0,
106
+ onFocus: () => {},
107
+ onKeyDown: () => {},
108
+ isActive: true,
109
+ }
110
+ }
111
+
112
+ return {
113
+ tabIndex: context.tabStops[index] ?? -1,
114
+ isActive: context.active === index,
115
+ onFocus: () => context.onItemFocus(index),
116
+ onKeyDown: (event: KeyboardEvent) => context.onItemKeyDown(index, event),
117
+ }
118
+ }
@@ -0,0 +1,44 @@
1
+ // Text inside a box, which React Native will not have.
2
+ //
3
+ // "Text strings must be rendered within a `<Text>` component" is what a
4
+ // bare string inside a `View` gets, at runtime, on a device. Hozo's Native
5
+ // backend already knows this and wraps every literal text child it lowers:
6
+ //
7
+ // <ListItem>Apple</ListItem> => <View role="listitem"><Text>Apple</Text></View>
8
+ //
9
+ // Uniformly, for every primitive that becomes a `View` -- there is no
10
+ // component where the answer is different, which is worth saying because
11
+ // it is what makes this mechanical rather than a judgement about which
12
+ // boxes people put labels in.
13
+ //
14
+ // The uncompiled fallbacks are supposed to behave the way that output
15
+ // does, and did not: they passed children through, so `<ListItem>Apple
16
+ // </ListItem>` crashed on exactly the path that exists for files the
17
+ // compiler could not reach (#295). Two of them were fixed by hand in
18
+ // #294, which is where the second occurrence stopped being a coincidence.
19
+ //
20
+ // This is stricter than the compiler in one place, deliberately. The
21
+ // backend leaves `<View>{label}</View>` alone because it cannot know what
22
+ // the expression is; this runs at render time, where the answer is
23
+ // simply available. A fallback being right about a case the compiler has
24
+ // to leave is not a divergence worth removing.
25
+
26
+ import { Children, type ReactNode } from 'react'
27
+ import { Text } from 'react-native'
28
+
29
+ /**
30
+ * Children with every text one inside a `Text`, and nothing else touched.
31
+ *
32
+ * Per child rather than around the lot, which is what the backend does:
33
+ * `<View><Text>a</Text>tail</View>` lowers to two `Text` elements rather
34
+ * than one wrapping both, and wrapping everything would put whatever else
35
+ * is in there inside a `Text` too.
36
+ *
37
+ * Numbers as well as strings. React renders both as text nodes, and React
38
+ * Native rejects both for the same reason.
39
+ */
40
+ export function hozoTextChildren(children: ReactNode): ReactNode {
41
+ return Children.map(children, (child) =>
42
+ typeof child === 'string' || typeof child === 'number' ? <Text>{child}</Text> : child,
43
+ )
44
+ }
@@ -0,0 +1,19 @@
1
+ // The Web half, which the browser already is.
2
+ //
3
+ // A string inside a `<div>` is a text node and there is nothing to fix, so
4
+ // this returns what it was given. It exists for the same reason
5
+ // `disclosure.tsx` and `ruby.tsx` do: a package resolves `@hozo/engine`'s
6
+ // types through the Web entry whichever platform it is building for, so a
7
+ // name the native halves import has to be nameable here or `@hozo/core`
8
+ // cannot compile.
9
+ //
10
+ // `.ts` rather than `.tsx`, since there is no JSX in it -- and that
11
+ // matters for `@hozo/behaviors`'s own tests, which run through Node's type
12
+ // stripping and have no JSX transform.
13
+
14
+ import type { ReactNode } from 'react'
15
+
16
+ /** Identity. See above, and `text-child.native.tsx` for the real one. */
17
+ export function hozoTextChildren(children: ReactNode): ReactNode {
18
+ return children
19
+ }
@@ -0,0 +1,120 @@
1
+ import { useRef } from 'react'
2
+
3
+ /** How long a keystroke stays part of the same search, in milliseconds. */
4
+ export const TYPEAHEAD_TIMEOUT_MS = 1000
5
+
6
+ /**
7
+ * Derives the search string after `key`, given what was typed before and time elapsed.
8
+ */
9
+ export function nextSearch(previous: string, key: string, sinceLastKey: number): string {
10
+ const buffer = sinceLastKey > TYPEAHEAD_TIMEOUT_MS ? '' : previous
11
+ return buffer + key.toLowerCase()
12
+ }
13
+
14
+ export interface TypeaheadOptions {
15
+ /** The items' accessible labels in order. */
16
+ labels: readonly string[]
17
+ /** Which item currently has focus/active index. */
18
+ active: number
19
+ /** Items that cannot take focus, by index. */
20
+ disabled?: readonly number[]
21
+ }
22
+
23
+ /**
24
+ * Searches for the next matching index based on query string.
25
+ * Supports consecutive single-letter cycling (e.g. pressing 's' repeatedly walks every 's' item).
26
+ * If a multi-character query yields no match, safely falls back to the last typed character
27
+ * with an explicit recursion guard to prevent any possibility of infinite loops.
28
+ */
29
+ export function searchIndex(
30
+ search: string,
31
+ options: TypeaheadOptions,
32
+ allowFallback = true,
33
+ ): number | null {
34
+ const { labels, active, disabled = [] } = options
35
+ if (search === '' || labels.length === 0) return null
36
+
37
+ const first = search.slice(0, 1)
38
+ const repeated = search.length > 1 && [...search].every((character) => character === first)
39
+ const needle = repeated ? first : search
40
+ const from = repeated ? active + 1 : active
41
+
42
+ for (let offset = 0; offset < labels.length; offset += 1) {
43
+ const index = (from + offset + labels.length) % labels.length
44
+ if (disabled.includes(index)) continue
45
+ const label = labels[index]
46
+ if (label?.trim().toLowerCase().startsWith(needle)) return index
47
+ }
48
+
49
+ // Smart fallback: If multi-character search (e.g. "tts") has no match,
50
+ // try matching just the newly typed last character ("s").
51
+ // Hard guard: only recurse once if search.length > 1 and allowFallback is true.
52
+ if (allowFallback && search.length > 1) {
53
+ const lastChar = search.slice(-1)
54
+ return searchIndex(lastChar, options, false)
55
+ }
56
+
57
+ return null
58
+ }
59
+
60
+ /**
61
+ * Checks whether a keypress is printable search text rather than an action key.
62
+ */
63
+ export function isTypeaheadKey(key: string, searching: boolean): boolean {
64
+ if (key.length !== 1) return false
65
+ if (key === ' ') return searching
66
+ return true
67
+ }
68
+
69
+ /**
70
+ * React Hook managing incremental typeahead search state.
71
+ */
72
+ export function useTypeahead(
73
+ labels: readonly string[],
74
+ active: number,
75
+ onSelect: (index: number) => void,
76
+ disabled: readonly number[] = [],
77
+ ) {
78
+ const bufferRef = useRef('')
79
+ const lastKeyTimeRef = useRef(0)
80
+
81
+ const handleKeyDown = (event: { key: string; defaultPrevented?: boolean }) => {
82
+ if (event.defaultPrevented) return
83
+ const now = Date.now()
84
+ const elapsed = now - lastKeyTimeRef.current
85
+ const isSearching = elapsed <= TYPEAHEAD_TIMEOUT_MS && bufferRef.current.length > 0
86
+
87
+ if (!isTypeaheadKey(event.key, isSearching)) return
88
+
89
+ const query = nextSearch(bufferRef.current, event.key, elapsed)
90
+ lastKeyTimeRef.current = now
91
+
92
+ // First try matching full query without fallback
93
+ let next = searchIndex(query, { labels, active, disabled }, false)
94
+ if (next !== null) {
95
+ bufferRef.current = query
96
+ } else if (query.length > 1) {
97
+ // Fallback: full query yielded no match, try newly pressed key as fresh start
98
+ const fallbackKey = event.key.toLowerCase()
99
+ next = searchIndex(fallbackKey, { labels, active, disabled }, false)
100
+ if (next !== null) {
101
+ bufferRef.current = fallbackKey
102
+ } else {
103
+ bufferRef.current = query
104
+ }
105
+ } else {
106
+ bufferRef.current = query
107
+ }
108
+
109
+ if (next !== null && next !== active) {
110
+ onSelect(next)
111
+ }
112
+ }
113
+
114
+ const reset = () => {
115
+ bufferRef.current = ''
116
+ lastKeyTimeRef.current = 0
117
+ }
118
+
119
+ return { handleKeyDown, reset }
120
+ }