@fabricator-ui/react-native 0.0.0-stage → 0.10.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 (46) hide show
  1. package/README.md +8 -2
  2. package/dist/LICENSE.md +25 -0
  3. package/dist/NOTICE.md +24 -0
  4. package/dist/lib/data-variants.ts +23 -0
  5. package/dist/lib/density-scale.ts +208 -0
  6. package/dist/lib/fabricator/css-object.ts +2 -0
  7. package/dist/lib/fabricator/density-scale.ts +210 -0
  8. package/dist/lib/fabricator/density-variables.ts +37 -0
  9. package/dist/lib/fabricator/motion-speeds.ts +566 -0
  10. package/dist/lib/fabricator/radius.ts +240 -0
  11. package/dist/lib/feedback.ts +124 -0
  12. package/dist/lib/field-frame.ts +53 -0
  13. package/dist/lib/field-model.ts +112 -0
  14. package/dist/lib/fluid-hover-model.ts +142 -0
  15. package/dist/lib/fluid-hover.tsx +788 -0
  16. package/dist/lib/icon-stroke.ts +38 -0
  17. package/dist/lib/motion-tokens.ts +97 -0
  18. package/dist/lib/motion.ts +292 -0
  19. package/dist/lib/overlay-model.ts +205 -0
  20. package/dist/lib/press-wash.tsx +73 -0
  21. package/dist/lib/render.tsx +53 -0
  22. package/dist/lib/select-model.ts +87 -0
  23. package/dist/lib/sheet-model.ts +101 -0
  24. package/dist/lib/sheet-surface.tsx +429 -0
  25. package/dist/lib/sound-recipes.ts +449 -0
  26. package/dist/lib/spring-model.ts +214 -0
  27. package/dist/lib/surface-color.tsx +27 -0
  28. package/dist/lib/text-children.ts +43 -0
  29. package/dist/styles.css +610 -0
  30. package/dist/ui/badge.tsx +108 -0
  31. package/dist/ui/button.tsx +285 -0
  32. package/dist/ui/card.tsx +365 -0
  33. package/dist/ui/checkbox.tsx +230 -0
  34. package/dist/ui/collapsible.tsx +194 -0
  35. package/dist/ui/density.tsx +79 -0
  36. package/dist/ui/dialog.tsx +232 -0
  37. package/dist/ui/dropdown-menu.tsx +687 -0
  38. package/dist/ui/fabricator-root.tsx +68 -0
  39. package/dist/ui/input.tsx +63 -0
  40. package/dist/ui/label.tsx +22 -0
  41. package/dist/ui/select.tsx +616 -0
  42. package/dist/ui/switch.tsx +177 -0
  43. package/dist/ui/tabs.tsx +272 -0
  44. package/dist/ui/text.tsx +125 -0
  45. package/dist/ui/textarea.tsx +65 -0
  46. package/package.json +54 -4
@@ -0,0 +1,240 @@
1
+ // Fabricator radius: the look's three shapes and the corner roles.
2
+ //
3
+ // A shape (Rounded, Squircle, Pill) sets each role's corner as
4
+ // `control height × ratio + base`. The control height is `--density-36`, so
5
+ // corners follow the density and a component's `size`. The roles:
6
+ //
7
+ // - control: single-line controls (button, input, select trigger, toggle).
8
+ // - surface: containers (card, popover, menu, dialog, alert, toast).
9
+ // - panel: large frames (App Shell frame and inset, sheet edges).
10
+ // - card: cards, rounder than popups and equal to the panel at the default
11
+ // density, so a grid of cards reads soft without loosening menus.
12
+ // - mark: small parts (checkbox, kbd, tooltip, inline code).
13
+ //
14
+ // Layered corners stay concentric: an inner corner is the outer one minus the
15
+ // distance between the two edges (`--radius-nested` for a row in a `p-1`
16
+ // popup, `--radius-inner` for a part inside a control), and a wrapper hugging
17
+ // one control is the control's corner plus the distance (`--radius-wrap` for
18
+ // a track with `p-(--density-4)`). Other gaps write the same sum inline:
19
+ // `rounded-[calc(var(--radius-control)+var(--density-8))]`.
20
+ //
21
+ // Style maps write `rounded-(--radius-control)` and friends: CSS variables, so
22
+ // class merging (cn) still lets a consumer's `rounded-none` win. The roles are
23
+ // declared on :root and again in every density scope, because a variable is
24
+ // resolved where it is declared.
25
+ //
26
+ // Squircle draws a superellipse `corner-shape` where the browser supports it
27
+ // (Chromium 139+, Electron), with radii scaled by SQUIRCLE_CORNER_SCALE, since
28
+ // a superellipse at the same radius reads tighter than a round corner.
29
+ // Elsewhere it is a slightly softer Rounded. React Native draws iOS's
30
+ // continuous corners at the base radii (`borderCurve`), and round corners on
31
+ // Android. `__tests__/radius-usage.test.ts` fails on fixed radii in the style
32
+ // maps.
33
+
34
+ import type { CssObject } from "./css-object"
35
+
36
+ export const RADIUS_SHAPES = ["rounded", "squircle", "pill"] as const
37
+ export type RadiusShape = (typeof RADIUS_SHAPES)[number]
38
+
39
+ export const DEFAULT_RADIUS_SHAPE: RadiusShape = "rounded"
40
+
41
+ export const RADIUS_ROLES = [
42
+ "control",
43
+ "surface",
44
+ "panel",
45
+ "mark",
46
+ "card",
47
+ ] as const
48
+ export type RadiusRole = (typeof RADIUS_ROLES)[number]
49
+
50
+ /** A role's corner: `control height × ratio + base`, in px. */
51
+ export type RoleRadius = { ratio: number; base: number }
52
+
53
+ export const SHAPE_RADII: Record<
54
+ RadiusShape,
55
+ Record<RadiusRole, RoleRadius>
56
+ > = {
57
+ // 8px on a 36px control, 12px containers holding 8px rows.
58
+ rounded: {
59
+ control: { ratio: 2 / 9, base: 0 },
60
+ surface: { ratio: 0, base: 12 },
61
+ panel: { ratio: 0, base: 16 },
62
+ mark: { ratio: 0, base: 4 },
63
+ // 12 / 16 / 20px from compact to spacious.
64
+ card: { ratio: 0.5, base: -2 },
65
+ },
66
+ // Softer than Rounded, the proportions of Apple's controls and cards.
67
+ squircle: {
68
+ control: { ratio: 0.25, base: 0 },
69
+ surface: { ratio: 0, base: 14 },
70
+ panel: { ratio: 0, base: 20 },
71
+ mark: { ratio: 0, base: 5 },
72
+ // 16 / 20 / 24px: the proportions of an iOS widget.
73
+ card: { ratio: 0.5, base: 2 },
74
+ },
75
+ // Capsule controls. Containers stay moderate: half a control plus a popup's
76
+ // 4px padding, so the capsule rows inside a menu are concentric.
77
+ pill: {
78
+ control: { ratio: 0.5, base: 0 },
79
+ surface: { ratio: 0.5, base: 4 },
80
+ panel: { ratio: 0.5, base: 8 },
81
+ mark: { ratio: 0, base: 6 },
82
+ card: { ratio: 0.5, base: 8 },
83
+ },
84
+ }
85
+
86
+ /** shadcn's `--radius` per shape, for a project's own `rounded-lg`. */
87
+ export const SHAPE_ROOT_RADIUS: Record<RadiusShape, string> = {
88
+ rounded: "0.5rem",
89
+ squircle: "0.625rem",
90
+ pill: "0.75rem",
91
+ }
92
+
93
+ /**
94
+ * Squircle's CSS curve. `squircle` (superellipse(2)) covers as much of a
95
+ * corner as a circle about half its radius; superellipse(1.5) scaled by 1.35
96
+ * covers what a circle of the base radius does, eased into the edges like
97
+ * Apple's continuous corners.
98
+ */
99
+ export const SQUIRCLE_CORNER_SHAPE = "superellipse(1.5)"
100
+
101
+ /** How much larger a superellipse radius is than the round one it matches. */
102
+ export const SQUIRCLE_CORNER_SCALE = 1.35
103
+
104
+ /** The padding of menus, selects and other popups around their rows. */
105
+ export const POPUP_INSET = 4
106
+
107
+ /** A role's corner in px, before the squircle scale (what native draws). */
108
+ export function getRoleRadius(
109
+ shape: RadiusShape,
110
+ role: RadiusRole,
111
+ controlHeight: number
112
+ ) {
113
+ const { ratio, base } = SHAPE_RADII[shape][role]
114
+ return controlHeight * ratio + base
115
+ }
116
+
117
+ /** The corner of a layer inside another: outer minus the gap, at least a mark. */
118
+ export function getNestedRadius({
119
+ outer,
120
+ inset,
121
+ mark,
122
+ }: {
123
+ outer: number
124
+ inset: number
125
+ mark: number
126
+ }) {
127
+ return Math.max(mark, outer - inset)
128
+ }
129
+
130
+ /** The corner of a wrapper hugging one control: the control's plus the gap. */
131
+ export function getWrappingRadius({
132
+ inner,
133
+ inset,
134
+ }: {
135
+ inner: number
136
+ inset: number
137
+ }) {
138
+ return inner + inset
139
+ }
140
+
141
+ /** Every corner in px for React Native, which has no calc(). */
142
+ export function getNativeRadii(
143
+ shape: RadiusShape,
144
+ density: { space: { 4: number; 36: number } }
145
+ ) {
146
+ const height = density.space[36]
147
+ const control = getRoleRadius(shape, "control", height)
148
+ const surface = getRoleRadius(shape, "surface", height)
149
+ const panel = getRoleRadius(shape, "panel", height)
150
+ const mark = getRoleRadius(shape, "mark", height)
151
+ const card = getRoleRadius(shape, "card", height)
152
+ return {
153
+ control,
154
+ surface,
155
+ panel,
156
+ mark,
157
+ card,
158
+ cardSmall: Math.max(surface, card - density.space[4]),
159
+ cardInner: getNestedRadius({ outer: card, inset: density.space[4], mark }),
160
+ nested: getNestedRadius({ outer: surface, inset: POPUP_INSET, mark }),
161
+ inner: getNestedRadius({ outer: control, inset: density.space[4], mark }),
162
+ wrap: getWrappingRadius({ inner: control, inset: density.space[4] }),
163
+ }
164
+ }
165
+
166
+ const px = (value: number) => `${value}px`
167
+
168
+ /** The variables a shape sets on :root, keyed by name without the `--`. */
169
+ export function toShapeVars(shape: RadiusShape): Record<string, string> {
170
+ return {
171
+ ...Object.fromEntries(
172
+ RADIUS_ROLES.flatMap((role) => [
173
+ [`radius-${role}-ratio`, String(SHAPE_RADII[shape][role].ratio)],
174
+ [`radius-${role}-base`, px(SHAPE_RADII[shape][role].base)],
175
+ ])
176
+ ),
177
+ "corner-shape": shape === "squircle" ? SQUIRCLE_CORNER_SHAPE : "round",
178
+ ...(shape === "squircle" && {
179
+ "radius-squircle-scale": String(SQUIRCLE_CORNER_SCALE),
180
+ }),
181
+ }
182
+ }
183
+
184
+ /** The shape variables that differ from Rounded, for a look's cssVars. */
185
+ export function toChangedShapeVars(shape: RadiusShape) {
186
+ const defaults = toShapeVars(DEFAULT_RADIUS_SHAPE)
187
+ return Object.fromEntries(
188
+ Object.entries(toShapeVars(shape)).filter(
189
+ ([name, value]) => defaults[name] !== value
190
+ )
191
+ )
192
+ }
193
+
194
+ /**
195
+ * The role corners, resolved wherever they are declared: :root and every
196
+ * density scope (density.ts adds them to its switches and utilities).
197
+ */
198
+ export const RADIUS_ROLE_VARS: Record<string, string> = {
199
+ ...Object.fromEntries(
200
+ RADIUS_ROLES.map((role) => [
201
+ `radius-${role}`,
202
+ `calc((var(--density-36) * var(--radius-${role}-ratio, 0) + var(--radius-${role}-base, 0px)) * var(--radius-corner-scale, 1))`,
203
+ ])
204
+ ),
205
+ // A row in a popup's `p-1`.
206
+ "radius-nested": `max(var(--radius-mark), calc(var(--radius-surface) - ${px(POPUP_INSET)}))`,
207
+ // A small part inside a control: an input group's button, a chip.
208
+ "radius-inner":
209
+ "max(var(--radius-mark), calc(var(--radius-control) - var(--density-4)))",
210
+ // A track or group hugging controls with `p-(--density-4)`.
211
+ "radius-wrap": "calc(var(--radius-control) + var(--density-4))",
212
+ // A `size="sm"` card: its inset is one step smaller, so its corner is too.
213
+ "radius-card-sm":
214
+ "max(var(--radius-surface), calc(var(--radius-card) - var(--density-4)))",
215
+ // The lifted panel inside a tray card's `p-(--density-4)` shell.
216
+ "radius-card-inner":
217
+ "max(var(--radius-mark), calc(var(--radius-card) - var(--density-4)))",
218
+ }
219
+
220
+ /**
221
+ * The corner shape for every element, in the base layer (a variable, so
222
+ * Squircle switches it in one place). Round things (`rounded-full`) stay
223
+ * circles.
224
+ */
225
+ export const RADIUS_BASE_CSS: CssObject = {
226
+ "*, ::before, ::after": {
227
+ "corner-shape": "var(--corner-shape, round)",
228
+ },
229
+ "[class*='rounded-full'], [class*='rounded-full']::before, [class*='rounded-full']::after":
230
+ { "corner-shape": "round" },
231
+ }
232
+
233
+ /** Scales the roles only where `corner-shape` draws, so a fallback stays put. */
234
+ export const RADIUS_SUPPORTS_CSS: CssObject = {
235
+ "@supports (corner-shape: squircle)": {
236
+ ":root": {
237
+ "--radius-corner-scale": "var(--radius-squircle-scale, 1)",
238
+ },
239
+ },
240
+ }
@@ -0,0 +1,124 @@
1
+ import * as React from "react"
2
+
3
+ /*
4
+ * What a control plays when it's used: a sound and a haptic. The website's
5
+ * <SoundEffects /> listens on the document; React Native has no document, so
6
+ * controls call this hook. With no <SoundEffects /> mounted it does nothing, and
7
+ * adds no dependency. It isn't React context: overlays render in a portal, which
8
+ * leaves the tree a provider would sit in.
9
+ */
10
+ export type FeedbackName =
11
+ | "tap"
12
+ | "press"
13
+ | "thud"
14
+ | "tick"
15
+ | "copy"
16
+ | "check"
17
+ | "uncheck"
18
+ | "pick"
19
+ | "toggle-on"
20
+ | "toggle-off"
21
+ | "latch"
22
+ | "unlatch"
23
+ | "note"
24
+ | "page"
25
+ | "whisk"
26
+ | "pop"
27
+ | "dismiss"
28
+ | "open"
29
+ | "close"
30
+ | "alert"
31
+ | "slide-in"
32
+ | "slide-out"
33
+ | "expand"
34
+ | "collapse"
35
+ | "notify"
36
+ | "success"
37
+ | "warning"
38
+ | "error"
39
+ | "notch"
40
+ | "grab"
41
+ | "drop"
42
+ | "deny"
43
+
44
+ export type FeedbackOptions = {
45
+ /** Multiplies every frequency in the sound (1 is the designed pitch). */
46
+ pitch?: number
47
+ }
48
+
49
+ type FeedbackPlayer = (name: FeedbackName, options?: FeedbackOptions) => void
50
+
51
+ let player: FeedbackPlayer | null = null
52
+
53
+ function playFeedback(name: FeedbackName, options?: FeedbackOptions) {
54
+ player?.(name, options)
55
+ }
56
+
57
+ // A surface only sounds right after a touch, as on the website: one that opens by
58
+ // itself, from a timer or `defaultOpen`, stays quiet.
59
+ const GESTURE_WINDOW_MS = 1000
60
+
61
+ let lastGestureAt: number | null = null
62
+
63
+ /** Notes a touch. FabricatorRoot calls this for every one, and takes none of them. */
64
+ function markGesture(now = Date.now()) {
65
+ lastGestureAt = now
66
+ }
67
+
68
+ function isAfterGesture(now: number, gestureAt: number | null) {
69
+ return gestureAt !== null && now - gestureAt < GESTURE_WINDOW_MS
70
+ }
71
+
72
+ function playSurfaceFeedback(name: FeedbackName) {
73
+ if (isAfterGesture(Date.now(), lastGestureAt)) playFeedback(name)
74
+ }
75
+
76
+ /** Installs what plays feedback. <SoundEffects /> calls this. */
77
+ function setFeedbackPlayer(next: FeedbackPlayer | null) {
78
+ player = next
79
+ }
80
+
81
+ /** Plays a control's feedback, if the app turned it on. */
82
+ function useFeedback() {
83
+ return playFeedback
84
+ }
85
+
86
+ const SURFACE_FEEDBACK = {
87
+ popup: ["pop", "dismiss"],
88
+ dialog: ["open", "close"],
89
+ alert: ["alert", "close"],
90
+ panel: ["slide-in", "slide-out"],
91
+ } as const satisfies Record<string, readonly [FeedbackName, FeedbackName]>
92
+
93
+ /** Plays a surface's sound as it opens and closes, and nothing as it mounts. */
94
+ function useSurfaceFeedback(
95
+ kind: keyof typeof SURFACE_FEEDBACK,
96
+ isOpen: boolean
97
+ ) {
98
+ const wasOpen = React.useRef(isOpen)
99
+ React.useEffect(() => {
100
+ if (wasOpen.current === isOpen) return
101
+ wasOpen.current = isOpen
102
+ playSurfaceFeedback(SURFACE_FEEDBACK[kind][isOpen ? 0 : 1])
103
+ }, [isOpen, kind])
104
+ }
105
+
106
+ /**
107
+ * For a surface that only renders while it's open, like a popup's content: plays
108
+ * its opening sound as it mounts, and its closing one as it unmounts.
109
+ */
110
+ function useMountFeedback(kind: keyof typeof SURFACE_FEEDBACK) {
111
+ React.useEffect(() => {
112
+ playSurfaceFeedback(SURFACE_FEEDBACK[kind][0])
113
+ return () => playSurfaceFeedback(SURFACE_FEEDBACK[kind][1])
114
+ }, [kind])
115
+ }
116
+
117
+ export {
118
+ isAfterGesture,
119
+ markGesture,
120
+ setFeedbackPlayer,
121
+ useFeedback,
122
+ useMountFeedback,
123
+ useSurfaceFeedback,
124
+ }
@@ -0,0 +1,53 @@
1
+ import * as React from "react"
2
+ import type { TextInput } from "react-native"
3
+ import { useResolveClassNames } from "uniwind"
4
+
5
+ import { useMotion } from "./motion"
6
+
7
+ type FocusEvents = Pick<
8
+ React.ComponentProps<typeof TextInput>,
9
+ "onFocus" | "onBlur"
10
+ >
11
+
12
+ /**
13
+ * A text field's frame, which lifts on focus and eases there on the feedback
14
+ * timing: a `focus:` class could only snap. The two class names resolve to the
15
+ * colours it moves between. An invalid field keeps its class's frame.
16
+ */
17
+ function useFieldFrame({
18
+ restClassName,
19
+ focusClassName,
20
+ isInvalid,
21
+ onFocus,
22
+ onBlur,
23
+ }: FocusEvents & {
24
+ restClassName: string
25
+ focusClassName: string
26
+ isInvalid: boolean
27
+ }) {
28
+ const [isFocused, setIsFocused] = React.useState(false)
29
+ const motion = useMotion("feedback")
30
+ const rest = useResolveClassNames(restClassName)
31
+ const focus = useResolveClassNames(focusClassName)
32
+ const colors = isFocused ? focus : rest
33
+ return {
34
+ isFocused,
35
+ onFocus: ((event) => {
36
+ setIsFocused(true)
37
+ onFocus?.(event)
38
+ }) satisfies FocusEvents["onFocus"],
39
+ onBlur: ((event) => {
40
+ setIsFocused(false)
41
+ onBlur?.(event)
42
+ }) satisfies FocusEvents["onBlur"],
43
+ frameStyle: {
44
+ backgroundColor: colors.backgroundColor,
45
+ ...(isInvalid ? {} : { borderColor: colors.borderColor }),
46
+ transitionProperty: ["backgroundColor", "borderColor"],
47
+ transitionDuration: motion.enterMs,
48
+ transitionTimingFunction: "ease",
49
+ },
50
+ }
51
+ }
52
+
53
+ export { useFieldFrame }
@@ -0,0 +1,112 @@
1
+ // What a Field and its control tell each other. The website gets this from the
2
+ // DOM: `<label for>` presses the control, and `group-data-*` and `has-*` carry
3
+ // state. React Native has neither, so a control joins the nearest Field here.
4
+ import * as React from "react"
5
+
6
+ export function getFieldErrorMessages(
7
+ errors: ({ message?: string } | undefined)[] | undefined
8
+ ) {
9
+ const messages = (errors ?? []).flatMap((error) =>
10
+ error?.message ? [error.message] : []
11
+ )
12
+ return [...new Set(messages)]
13
+ }
14
+
15
+ type FieldScope = {
16
+ isInvalid: boolean
17
+ isDisabled: boolean
18
+ /** Whether the control inside is on, for a label that is a choice card. */
19
+ isChecked: boolean
20
+ /** Presses the control: focuses it, or toggles it. */
21
+ activate: () => void
22
+ register: (activate: () => void) => () => void
23
+ setChecked: (isChecked: boolean) => void
24
+ }
25
+
26
+ const FieldContext = React.createContext<FieldScope | null>(null)
27
+
28
+ /**
29
+ * A scope controls can join. Scopes nest: a label wrapping a Field hears about
30
+ * the control inside it, and a label beside a control presses its Field's.
31
+ */
32
+ function useFieldScope({
33
+ isInvalid = false,
34
+ isDisabled = false,
35
+ }: {
36
+ isInvalid?: boolean
37
+ isDisabled?: boolean
38
+ }) {
39
+ const parent = React.use(FieldContext)
40
+ const control = React.useRef<(() => void) | null>(null)
41
+ const [isChecked, setIsChecked] = React.useState(false)
42
+ const parentRegister = parent?.register
43
+ const parentSetChecked = parent?.setChecked
44
+ const parentActivate = parent?.activate
45
+
46
+ const register = React.useCallback(
47
+ (activate: () => void) => {
48
+ control.current = activate
49
+ const leaveParent = parentRegister?.(activate)
50
+ return () => {
51
+ control.current = null
52
+ leaveParent?.()
53
+ }
54
+ },
55
+ [parentRegister]
56
+ )
57
+ const setChecked = React.useCallback(
58
+ (next: boolean) => {
59
+ setIsChecked(next)
60
+ parentSetChecked?.(next)
61
+ },
62
+ [parentSetChecked]
63
+ )
64
+ const activate = React.useCallback(() => {
65
+ if (control.current) control.current()
66
+ else parentActivate?.()
67
+ }, [parentActivate])
68
+
69
+ const isScopeInvalid = isInvalid || (parent?.isInvalid ?? false)
70
+ const isScopeDisabled = isDisabled || (parent?.isDisabled ?? false)
71
+ return React.useMemo<FieldScope>(
72
+ () => ({
73
+ isInvalid: isScopeInvalid,
74
+ isDisabled: isScopeDisabled,
75
+ isChecked,
76
+ activate,
77
+ register,
78
+ setChecked,
79
+ }),
80
+ [isScopeInvalid, isScopeDisabled, isChecked, activate, register, setChecked]
81
+ )
82
+ }
83
+
84
+ /**
85
+ * Joins the nearest Field, so its label presses this control and it follows the
86
+ * Field's invalid and disabled state. Outside a Field it does nothing.
87
+ */
88
+ function useFieldControl({
89
+ activate,
90
+ isChecked = false,
91
+ }: {
92
+ activate?: () => void
93
+ isChecked?: boolean
94
+ } = {}) {
95
+ const field = React.use(FieldContext)
96
+ const latest = React.useRef(activate)
97
+ React.useEffect(() => {
98
+ latest.current = activate
99
+ })
100
+ const register = field?.register
101
+ React.useEffect(() => register?.(() => latest.current?.()), [register])
102
+ const setChecked = field?.setChecked
103
+ React.useEffect(() => {
104
+ setChecked?.(isChecked)
105
+ }, [setChecked, isChecked])
106
+ return {
107
+ isInvalid: field?.isInvalid ?? false,
108
+ isDisabled: field?.isDisabled ?? false,
109
+ }
110
+ }
111
+
112
+ export { FieldContext, useFieldControl, useFieldScope }
@@ -0,0 +1,142 @@
1
+ // What Fluid Hover does under a finger. No React Native imports, so it stays
2
+ // testable anywhere; the "worklet" directive lets a gesture run it on the UI
3
+ // thread.
4
+
5
+ export type Rect = { top: number; left: number; width: number; height: number }
6
+
7
+ export type FluidAxis = "x" | "y" | "xy"
8
+
9
+ export type FluidRow = { key: string; rect: Rect; disabled?: boolean }
10
+
11
+ type Point = { x: number; y: number }
12
+
13
+ /** Only the old and new row need to redraw when the highlight moves. */
14
+ export function createFluidHoverStore() {
15
+ let key: string | null = null
16
+ const listeners = new Map<string, Set<() => void>>()
17
+ const notifyRows = (row: string | null) => {
18
+ const subscribers = row === null ? undefined : listeners.get(row)
19
+ if (!subscribers) return
20
+ for (const notify of subscribers) notify()
21
+ }
22
+ return {
23
+ get: () => key,
24
+ set(next: string | null) {
25
+ if (key === next) return
26
+ const previous = key
27
+ key = next
28
+ notifyRows(previous)
29
+ notifyRows(next)
30
+ },
31
+ subscribe(row: string, listener: () => void) {
32
+ let subscribers = listeners.get(row)
33
+ if (!subscribers) {
34
+ subscribers = new Set()
35
+ listeners.set(row, subscribers)
36
+ }
37
+ subscribers.add(listener)
38
+ return () => {
39
+ subscribers.delete(listener)
40
+ if (subscribers.size === 0 && listeners.get(row) === subscribers)
41
+ listeners.delete(row)
42
+ }
43
+ },
44
+ }
45
+ }
46
+
47
+ export function sameRect(a: Rect | null, b: Rect | null) {
48
+ "worklet"
49
+ return (
50
+ a === b ||
51
+ (!!a &&
52
+ !!b &&
53
+ a.top === b.top &&
54
+ a.left === b.left &&
55
+ a.width === b.width &&
56
+ a.height === b.height)
57
+ )
58
+ }
59
+
60
+ /** Should the overlay slide, or appear in place? It only slides between rows. */
61
+ export function shouldGlide(previous: Rect | null, next: Rect | null) {
62
+ "worklet"
63
+ return Boolean(previous && next)
64
+ }
65
+
66
+ /**
67
+ * The row to light for a finger. Grids take the row under it, else the nearest
68
+ * centre. Lists and strips measure along their axis, so the gaps between rows
69
+ * stay lit; when a strip wraps, the row under the finger comes first, so rows
70
+ * stacked in other lines never win. The website's `pickNearest`, on plain rects.
71
+ */
72
+ export function pickNearestRow(
73
+ rows: FluidRow[],
74
+ point: Point,
75
+ axis: FluidAxis
76
+ ) {
77
+ "worklet"
78
+ let best: string | null = null
79
+ let bestLine = Infinity
80
+ let bestInside = Infinity
81
+ let bestCentre = Infinity
82
+ for (const row of rows) {
83
+ if (row.disabled) continue
84
+ const { top, left, width, height } = row.rect
85
+ const gapX = Math.max(left - point.x, 0, point.x - (left + width))
86
+ const gapY = Math.max(top - point.y, 0, point.y - (top + height))
87
+ const toCentreX = Math.abs(point.x - (left + width / 2))
88
+ const toCentreY = Math.abs(point.y - (top + height / 2))
89
+ const line = axis === "xy" ? 0 : axis === "x" ? gapY : gapX
90
+ const along = axis === "x" ? gapX : gapY
91
+ const inside = (axis === "xy" ? gapX === 0 && gapY === 0 : along === 0)
92
+ ? 0
93
+ : 1
94
+ const centre =
95
+ axis === "xy"
96
+ ? Math.hypot(toCentreX, toCentreY)
97
+ : axis === "x"
98
+ ? toCentreX
99
+ : toCentreY
100
+ if (
101
+ line < bestLine ||
102
+ (line === bestLine &&
103
+ (inside < bestInside || (inside === bestInside && centre < bestCentre)))
104
+ ) {
105
+ best = row.key
106
+ bestLine = line
107
+ bestInside = inside
108
+ bestCentre = centre
109
+ }
110
+ }
111
+ return best
112
+ }
113
+
114
+ /** Whether a finger is still over the rows, or within `slop` of them. */
115
+ export function isNearRows(rows: FluidRow[], point: Point, slop: number) {
116
+ "worklet"
117
+ if (rows.length === 0) return false
118
+ let top = Infinity
119
+ let left = Infinity
120
+ let right = -Infinity
121
+ let bottom = -Infinity
122
+ for (const { rect } of rows) {
123
+ top = Math.min(top, rect.top)
124
+ left = Math.min(left, rect.left)
125
+ right = Math.max(right, rect.left + rect.width)
126
+ bottom = Math.max(bottom, rect.top + rect.height)
127
+ }
128
+ return (
129
+ point.x >= left - slop &&
130
+ point.x <= right + slop &&
131
+ point.y >= top - slop &&
132
+ point.y <= bottom + slop
133
+ )
134
+ }
135
+
136
+ /**
137
+ * How long a released highlight stays. A finger has no hover before it, so a
138
+ * quick tap would fade out before it had faded in: it holds until it's been seen.
139
+ */
140
+ export function getFadeOutDelay(pressedFor: number, holdFor: number) {
141
+ return Math.max(0, holdFor - pressedFor)
142
+ }