From 50f9c8307409b648483ce404fc89d3634a6c84ef Mon Sep 17 00:00:00 2001 From: kasimkazmi Date: Mon, 2 Nov 2026 13:26:30 -0500 Subject: [PATCH 01/18] feat: Add eight more React Native components Action Tray, Confirm Dialog, Code Boxes, Hue Picker, Tab Pager, Wheel Picker, Avatar Stack and Stripe Progress, each with a preview and docs page. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 18 +- public/registry/action-tray.json | 15 + public/registry/avatar-stack.json | 15 + public/registry/code-boxes.json | 15 + public/registry/confirm-dialog.json | 15 + public/registry/hue-picker.json | 15 + public/registry/index.json | 66 +++- public/registry/stripe-progress.json | 15 + public/registry/tab-pager.json | 15 + public/registry/wheel-picker.json | 15 + src/content/docs/action-tray.mdx | 66 ++++ src/content/docs/avatar-stack.mdx | 55 +++ src/content/docs/code-boxes.mdx | 60 +++ src/content/docs/confirm-dialog.mdx | 69 ++++ src/content/docs/hue-picker.mdx | 50 +++ src/content/docs/stripe-progress.mdx | 52 +++ src/content/docs/tab-pager.mdx | 64 ++++ src/content/docs/wheel-picker.mdx | 55 +++ src/registry/action-tray-demo.tsx | 75 ++++ src/registry/action-tray.tsx | 289 +++++++++++++++ src/registry/avatar-stack-demo.tsx | 82 +++++ src/registry/avatar-stack.tsx | 296 +++++++++++++++ src/registry/code-boxes-demo.tsx | 85 +++++ src/registry/code-boxes.tsx | 299 +++++++++++++++ src/registry/confirm-dialog-demo.tsx | 109 ++++++ src/registry/confirm-dialog.tsx | 248 +++++++++++++ src/registry/demos.ts | 8 + src/registry/hue-picker-demo.tsx | 48 +++ src/registry/hue-picker.tsx | 512 ++++++++++++++++++++++++++ src/registry/index.ts | 80 ++++ src/registry/stripe-progress-demo.tsx | 96 +++++ src/registry/stripe-progress.tsx | 241 ++++++++++++ src/registry/tab-pager-demo.tsx | 79 ++++ src/registry/tab-pager.tsx | 320 ++++++++++++++++ src/registry/wheel-picker-demo.tsx | 71 ++++ src/registry/wheel-picker.tsx | 248 +++++++++++++ 36 files changed, 3851 insertions(+), 10 deletions(-) create mode 100644 public/registry/action-tray.json create mode 100644 public/registry/avatar-stack.json create mode 100644 public/registry/code-boxes.json create mode 100644 public/registry/confirm-dialog.json create mode 100644 public/registry/hue-picker.json create mode 100644 public/registry/stripe-progress.json create mode 100644 public/registry/tab-pager.json create mode 100644 public/registry/wheel-picker.json create mode 100644 src/content/docs/action-tray.mdx create mode 100644 src/content/docs/avatar-stack.mdx create mode 100644 src/content/docs/code-boxes.mdx create mode 100644 src/content/docs/confirm-dialog.mdx create mode 100644 src/content/docs/hue-picker.mdx create mode 100644 src/content/docs/stripe-progress.mdx create mode 100644 src/content/docs/tab-pager.mdx create mode 100644 src/content/docs/wheel-picker.mdx create mode 100644 src/registry/action-tray-demo.tsx create mode 100644 src/registry/action-tray.tsx create mode 100644 src/registry/avatar-stack-demo.tsx create mode 100644 src/registry/avatar-stack.tsx create mode 100644 src/registry/code-boxes-demo.tsx create mode 100644 src/registry/code-boxes.tsx create mode 100644 src/registry/confirm-dialog-demo.tsx create mode 100644 src/registry/confirm-dialog.tsx create mode 100644 src/registry/hue-picker-demo.tsx create mode 100644 src/registry/hue-picker.tsx create mode 100644 src/registry/stripe-progress-demo.tsx create mode 100644 src/registry/stripe-progress.tsx create mode 100644 src/registry/tab-pager-demo.tsx create mode 100644 src/registry/tab-pager.tsx create mode 100644 src/registry/wheel-picker-demo.tsx create mode 100644 src/registry/wheel-picker.tsx diff --git a/README.md b/README.md index 8be0d8d..048ecb6 100644 --- a/README.md +++ b/README.md @@ -92,15 +92,15 @@ For Cursor, Windsurf or VS Code setup, see [`packages/mcp`](packages/mcp). The d ## Components -| Category | Components | -| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| **Navigation** | Liquid Tabs, Flowing Menu, Morphing Navbar, Floating Dock, Notch Footer, Process Stepper | -| **Actions** | Magnet, Magic Button, Animated Button, Pulse Button | -| **Data Display** | Bounce Cards, Masonry Grid, Animated List, Kinetic Carousel, Expandable Showcase, Focus Card, Rotating Card, Tilt Card | -| **Backgrounds** | Cursor Grid, Waves, Letter Glitch, Aurora Background, Circuit Background, Grid Motion | -| **Typography** | Scroll Velocity, Text Pressure, True Focus, Gradient Text, Blur Text, Split Text, Decrypted Text, Shimmer Text, Floating Text | -| **Components** | Scratch to Reveal, Stack, Star Border, Tilted Card, Pixel Card, Click Spark, Spotlight Card, Border Glow | -| **React Native** | Swipe Actions, Snap Sheet, Glide Segments, Swipe Deck, Fan Menu, Pin Pad, Flick Toast, Fold Panel, Snap Carousel, Slide Switch, Shimmer Block, Parallax Header, Bubble Tab Bar, Roll Number, Star Rating, Value Slider, Expand Search, Intro Pager, Drag List, Long Press Menu, Slide Confirm, Calendar Strip, Step Tracker, Chip Input, Typing Dots, Marquee Ticker, Choice Chips, Hold Stepper | +| Category | Components | +| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Navigation** | Liquid Tabs, Flowing Menu, Morphing Navbar, Floating Dock, Notch Footer, Process Stepper | +| **Actions** | Magnet, Magic Button, Animated Button, Pulse Button | +| **Data Display** | Bounce Cards, Masonry Grid, Animated List, Kinetic Carousel, Expandable Showcase, Focus Card, Rotating Card, Tilt Card | +| **Backgrounds** | Cursor Grid, Waves, Letter Glitch, Aurora Background, Circuit Background, Grid Motion | +| **Typography** | Scroll Velocity, Text Pressure, True Focus, Gradient Text, Blur Text, Split Text, Decrypted Text, Shimmer Text, Floating Text | +| **Components** | Scratch to Reveal, Stack, Star Border, Tilted Card, Pixel Card, Click Spark, Spotlight Card, Border Glow | +| **React Native** | Swipe Actions, Snap Sheet, Glide Segments, Swipe Deck, Fan Menu, Pin Pad, Flick Toast, Fold Panel, Snap Carousel, Slide Switch, Shimmer Block, Parallax Header, Bubble Tab Bar, Roll Number, Star Rating, Value Slider, Expand Search, Intro Pager, Drag List, Long Press Menu, Slide Confirm, Calendar Strip, Step Tracker, Chip Input, Typing Dots, Marquee Ticker, Choice Chips, Hold Stepper, Action Tray, Confirm Dialog, Code Boxes, Hue Picker, Tab Pager, Wheel Picker, Avatar Stack, Stripe Progress | **React Native** components are Expo files that import only `react-native`, so they need no extra packages. Install them the same way (`npx @modus-ui/cli add swipe-actions`); the docs preview them live in the browser through react-native-web. diff --git a/public/registry/action-tray.json b/public/registry/action-tray.json new file mode 100644 index 0000000..ac8c95a --- /dev/null +++ b/public/registry/action-tray.json @@ -0,0 +1,15 @@ +{ + "name": "action-tray", + "title": "Action Tray", + "category": "React Native", + "type": "components:ui", + "platform": "native", + "added": "2026-11-02", + "dependencies": [], + "files": [ + { + "path": "registry/action-tray.tsx", + "content": "import { useEffect, useRef, useState } from \"react\";\nimport {\n AccessibilityInfo,\n Animated,\n PanResponder,\n Platform,\n Pressable,\n StyleSheet,\n Text,\n View,\n type LayoutChangeEvent,\n type StyleProp,\n type ViewStyle,\n} from \"react-native\";\n\nconst NATIVE_DRIVER = Platform.OS !== \"web\";\n// Space left under the tray when it is hidden, so its shadow never peeks out.\nconst HIDE_GAP = 24;\n// How far, or how fast, a drag must go to dismiss the tray.\nconst DISMISS_DISTANCE = 80;\nconst DISMISS_VELOCITY = 0.8;\n\nexport interface ActionTrayAction {\n label: string;\n onPress: () => void;\n /** Draws the action in the destructive color. */\n destructive?: boolean;\n disabled?: boolean;\n}\n\nexport interface ActionTrayColors {\n backdrop: string;\n surface: string;\n text: string;\n mutedText: string;\n destructive: string;\n divider: string;\n handle: string;\n}\n\nconst DEFAULT_COLORS: ActionTrayColors = {\n backdrop: \"rgba(0, 0, 0, 0.4)\",\n surface: \"#ffffff\",\n text: \"#111827\",\n mutedText: \"#6b7280\",\n destructive: \"#dc2626\",\n divider: \"#e5e7eb\",\n handle: \"#d1d5db\",\n};\n\nfunction useReduceMotion() {\n const [reduce, setReduce] = useState(false);\n useEffect(() => {\n AccessibilityInfo.isReduceMotionEnabled().then(setReduce);\n const sub = AccessibilityInfo.addEventListener(\"reduceMotionChanged\", setReduce);\n return () => sub.remove();\n }, []);\n return reduce;\n}\n\nexport interface ActionTrayProps {\n /** Whether the tray is showing. */\n open: boolean;\n /** Called when the tray should close: backdrop tap, Escape, a drag down, Cancel, or after an action. */\n onClose: () => void;\n title?: string;\n /** A line of smaller text under the title. */\n message?: string;\n actions: ActionTrayAction[];\n cancelLabel?: string;\n colors?: Partial;\n style?: StyleProp;\n}\n\n/**\n * A bottom action list in the style of a native action sheet. It slides up from the bottom of its\n * parent over a dimmed backdrop, with the actions as one rounded group and Cancel as a separate\n * button. Tap the backdrop, press Escape, or drag the handle down to close it. It is drawn inside\n * its parent, so the parent must fill the area the tray should cover.\n */\nexport function ActionTray({\n open,\n onClose,\n title,\n message,\n actions,\n cancelLabel = \"Cancel\",\n colors,\n style,\n}: ActionTrayProps) {\n const palette = { ...DEFAULT_COLORS, ...colors };\n const reduceMotion = useReduceMotion();\n const [height, setHeight] = useState(0);\n // Distance the tray is pushed down: 0 when open, `height + HIDE_GAP` when hidden.\n const y = useRef(new Animated.Value(0)).current;\n\n const live = useRef({ open, onClose, height, reduceMotion });\n live.current = { open, onClose, height, reduceMotion };\n\n const moveTo = (target: number) => {\n if (live.current.reduceMotion) {\n y.setValue(target);\n return;\n }\n Animated.spring(y, {\n toValue: target,\n stiffness: 360,\n damping: 34,\n mass: 1,\n useNativeDriver: NATIVE_DRIVER,\n }).start();\n };\n\n useEffect(() => {\n if (height === 0) return;\n moveTo(open ? 0 : height + HIDE_GAP);\n // moveTo reads everything it needs through the ref.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [open, height]);\n\n // Escape closes the tray on the web.\n useEffect(() => {\n if (!open || Platform.OS !== \"web\") return;\n const onKey = (event: KeyboardEvent) => {\n if (event.key === \"Escape\") live.current.onClose();\n };\n document.addEventListener(\"keydown\", onKey);\n return () => document.removeEventListener(\"keydown\", onKey);\n }, [open]);\n\n const pan = useRef(\n PanResponder.create({\n onStartShouldSetPanResponder: () => true,\n onPanResponderGrant: () => y.stopAnimation(),\n onPanResponderMove: (_, g) => y.setValue(Math.max(0, g.dy)),\n onPanResponderRelease: (_, g) => {\n if (g.dy > DISMISS_DISTANCE || g.vy > DISMISS_VELOCITY) {\n moveTo(live.current.height + HIDE_GAP);\n live.current.onClose();\n // If the parent ignores the request the tray is still open: bring it back.\n setTimeout(() => {\n if (live.current.open) moveTo(0);\n }, 80);\n } else {\n moveTo(0);\n }\n },\n onPanResponderTerminate: () => moveTo(0),\n }),\n ).current;\n\n const onLayout = (event: LayoutChangeEvent) => {\n const next = event.nativeEvent.layout.height;\n if (next === height) return;\n // Start hidden, so the first open slides in instead of appearing.\n if (height === 0) y.setValue(next + HIDE_GAP);\n setHeight(next);\n };\n\n const backdropOpacity = y.interpolate({\n inputRange: [0, (height || 1) + HIDE_GAP],\n outputRange: [1, 0],\n extrapolate: \"clamp\",\n });\n\n return (\n \n \n \n \n 0 ? 1 : 0, transform: [{ translateY: y }] }]}\n >\n \n \n \n {title ? (\n \n {title}\n \n ) : null}\n {message ? (\n {message}\n ) : null}\n \n {actions.map((action) => (\n {\n action.onPress();\n onClose();\n }}\n style={({ pressed }) => [\n styles.action,\n { borderTopColor: palette.divider },\n action.disabled && styles.disabled,\n pressed && styles.pressed,\n ]}\n >\n \n {action.label}\n \n \n ))}\n \n [\n styles.cancel,\n { backgroundColor: palette.surface },\n pressed && styles.pressed,\n ]}\n >\n {cancelLabel}\n \n \n \n );\n}\n\nconst styles = StyleSheet.create({\n root: {\n position: \"absolute\",\n top: 0,\n right: 0,\n bottom: 0,\n left: 0,\n justifyContent: \"flex-end\",\n },\n fill: { position: \"absolute\", top: 0, right: 0, bottom: 0, left: 0 },\n tray: { paddingHorizontal: 10, paddingBottom: 12, gap: 8 },\n group: { borderRadius: 16, overflow: \"hidden\" },\n // userSelect keeps a mouse drag on the web from selecting the title instead of moving the tray.\n header: {\n alignItems: \"center\",\n paddingTop: 8,\n paddingBottom: 12,\n paddingHorizontal: 16,\n gap: 4,\n userSelect: \"none\",\n },\n handle: { width: 36, height: 4, borderRadius: 2, marginBottom: 6 },\n title: { fontSize: 15, fontWeight: \"700\", textAlign: \"center\" },\n message: { fontSize: 13, textAlign: \"center\" },\n action: {\n minHeight: 54,\n alignItems: \"center\",\n justifyContent: \"center\",\n paddingHorizontal: 16,\n borderTopWidth: StyleSheet.hairlineWidth,\n },\n actionText: { fontSize: 17, fontWeight: \"500\" },\n cancel: {\n minHeight: 54,\n alignItems: \"center\",\n justifyContent: \"center\",\n borderRadius: 16,\n },\n cancelText: { fontSize: 17, fontWeight: \"700\" },\n disabled: { opacity: 0.4 },\n pressed: { opacity: 0.6 },\n});\n" + } + ] +} \ No newline at end of file diff --git a/public/registry/avatar-stack.json b/public/registry/avatar-stack.json new file mode 100644 index 0000000..a94aedc --- /dev/null +++ b/public/registry/avatar-stack.json @@ -0,0 +1,15 @@ +{ + "name": "avatar-stack", + "title": "Avatar Stack", + "category": "React Native", + "type": "components:ui", + "platform": "native", + "added": "2026-11-02", + "dependencies": [], + "files": [ + { + "path": "registry/avatar-stack.tsx", + "content": "import { useEffect, useRef, useState } from \"react\";\nimport {\n AccessibilityInfo,\n Animated,\n Image,\n Pressable,\n StyleSheet,\n Text,\n View,\n type StyleProp,\n type ViewStyle,\n} from \"react-native\";\n\n// How far apart avatars sit when the stack is spread, in place of the overlap.\nconst SPREAD_GAP = 8;\nconst RING = 2;\n// Initials avatars take a stable color from this list, chosen by the person's name.\nconst PALETTE = [\n \"#6366f1\",\n \"#0ea5e9\",\n \"#14b8a6\",\n \"#22c55e\",\n \"#f59e0b\",\n \"#ef4444\",\n \"#ec4899\",\n \"#8b5cf6\",\n];\n\nexport interface AvatarPerson {\n id: string;\n name: string;\n /** A photo URL. Without one the avatar shows the person's initials. */\n image?: string;\n}\n\nexport interface AvatarStackColors {\n /** The ring around each avatar, normally the surface color, so overlaps read as separate. */\n ring: string;\n /** Initials. */\n text: string;\n /** Background of the \"+N\" avatar. */\n plus: string;\n}\n\nconst DEFAULT_COLORS: AvatarStackColors = {\n ring: \"#ffffff\",\n text: \"#ffffff\",\n plus: \"#6b7280\",\n};\n\nfunction useReduceMotion() {\n const [reduce, setReduce] = useState(false);\n useEffect(() => {\n AccessibilityInfo.isReduceMotionEnabled().then(setReduce);\n const sub = AccessibilityInfo.addEventListener(\"reduceMotionChanged\", setReduce);\n return () => sub.remove();\n }, []);\n return reduce;\n}\n\nconst initialsOf = (name: string) =>\n name\n .split(/\\s+/)\n .filter(Boolean)\n .slice(0, 2)\n .map((word) => word[0].toUpperCase())\n .join(\"\");\n\nconst colorFor = (name: string) => {\n let sum = 0;\n for (const char of name) sum += char.charCodeAt(0);\n return PALETTE[sum % PALETTE.length];\n};\n\n/** \"Maya Chen, Leo Park and 3 others\": the first two names, then a count. */\nfunction describe(people: AvatarPerson[]) {\n const [first, second] = people;\n if (!first) return \"No people\";\n if (!second) return first.name;\n const rest = people.length - 2;\n if (rest === 0) return `${first.name} and ${second.name}`;\n return `${first.name}, ${second.name} and ${rest} ${rest === 1 ? \"other\" : \"others\"}`;\n}\n\nexport interface AvatarStackProps {\n people: AvatarPerson[];\n /** How many avatars show before the rest collapse into a \"+N\" avatar. */\n max?: number;\n /** Diameter of each avatar. */\n size?: number;\n /** How far each avatar covers the one before it, in pixels. */\n overlap?: number;\n /** Pressing the stack spreads the avatars apart and reveals the ones past `max`. */\n expandOnPress?: boolean;\n /** Called with the person whose avatar is pressed, once the stack is spread (or if it can't spread). */\n onPersonPress?: (person: AvatarPerson) => void;\n colors?: Partial;\n style?: StyleProp;\n}\n\n/**\n * Overlapping avatars with a \"+N\" for the rest. Press the stack and the avatars spring apart one after\n * another, showing everyone; press again, or anywhere outside, and they fold back. The group reads out\n * as \"Maya Chen, Leo Park and 3 others\", and with reduced motion it spreads without animating.\n */\nexport function AvatarStack({\n people,\n max = 4,\n size = 40,\n overlap = 12,\n expandOnPress = true,\n onPersonPress,\n colors,\n style,\n}: AvatarStackProps) {\n const palette = { ...DEFAULT_COLORS, ...colors };\n const reduceMotion = useReduceMotion();\n // `open` is the target; `showAll` stays true while the avatars fold back, then drops the extras.\n const [open, setOpen] = useState(false);\n const [showAll, setShowAll] = useState(false);\n // One 0 to 1 value per avatar, so they can spread one after another.\n const spreads = useRef(new Map());\n\n const hidden = Math.max(0, people.length - max);\n const shown = showAll ? people : people.slice(0, max);\n const showPlus = hidden > 0 && !showAll;\n\n const spreadFor = (key: string) => {\n let value = spreads.current.get(key);\n if (!value) {\n value = new Animated.Value(0);\n spreads.current.set(key, value);\n }\n return value;\n };\n\n useEffect(() => {\n const values = [...spreads.current.values()];\n const target = open ? 1 : 0;\n if (reduceMotion) {\n values.forEach((value) => value.setValue(target));\n if (!open) setShowAll(false);\n return;\n }\n // marginLeft is a layout property, so these springs cannot use the native driver.\n Animated.stagger(\n 45,\n values.map((value) =>\n Animated.spring(value, {\n toValue: target,\n stiffness: 260,\n damping: 18,\n mass: 1,\n useNativeDriver: false,\n }),\n ),\n ).start(({ finished }) => {\n if (finished && !open) setShowAll(false);\n });\n }, [open, showAll, reduceMotion]);\n\n const toggle = () => {\n if (open) {\n setOpen(false);\n return;\n }\n setShowAll(true);\n setOpen(true);\n };\n\n const pressPerson = (person: AvatarPerson) => {\n // A press first spreads a folded stack; once it is spread (or if it cannot spread) it picks the person.\n if (expandOnPress && !open) {\n toggle();\n return;\n }\n if (onPersonPress) onPersonPress(person);\n else if (expandOnPress) toggle();\n };\n\n const interactive = expandOnPress || !!onPersonPress;\n const hitSlop = Math.max(0, Math.ceil((44 - size) / 2));\n\n const avatarStyle = (key: string, index: number, extra: boolean) => {\n const spread = spreadFor(key);\n return {\n marginLeft:\n index === 0\n ? 0\n : spread.interpolate({ inputRange: [0, 1], outputRange: [-overlap, SPREAD_GAP] }),\n // Avatars past `max` fade and grow in as the stack spreads.\n ...(extra\n ? {\n opacity: spread.interpolate({ inputRange: [0, 0.4, 1], outputRange: [0, 1, 1] }),\n transform: [\n { scale: spread.interpolate({ inputRange: [0, 1], outputRange: [0.6, 1] }) },\n ],\n }\n : null),\n };\n };\n\n const ring = {\n width: size,\n height: size,\n borderRadius: size / 2,\n borderWidth: RING,\n borderColor: palette.ring,\n };\n\n return (\n \n {open ? (\n // Pressing anywhere outside folds the stack. Touches outside a parent's bounds are ignored on\n // Android, where the stack's own avatars and the toggle still work.\n setOpen(false)}\n style={styles.backdrop}\n />\n ) : null}\n \n {shown.map((person, index) => (\n = max)}>\n pressPerson(person)}\n style={[\n styles.avatar,\n ring,\n { backgroundColor: person.image ? palette.plus : colorFor(person.name) },\n ]}\n >\n {person.image ? (\n \n ) : (\n \n {initialsOf(person.name)}\n \n )}\n \n \n ))}\n {showPlus ? (\n \n \n \n +{hidden}\n \n \n \n ) : null}\n \n \n );\n}\n\nconst styles = StyleSheet.create({\n root: { alignSelf: \"flex-start\" },\n backdrop: { position: \"absolute\", top: -4000, right: -4000, bottom: -4000, left: -4000 },\n // userSelect keeps a quick double press on the web from selecting the initials.\n row: { flexDirection: \"row\", alignItems: \"center\", userSelect: \"none\" },\n avatar: { alignItems: \"center\", justifyContent: \"center\", overflow: \"hidden\" },\n initials: { fontWeight: \"700\", letterSpacing: 0.3 },\n});\n" + } + ] +} \ No newline at end of file diff --git a/public/registry/code-boxes.json b/public/registry/code-boxes.json new file mode 100644 index 0000000..91ac2d1 --- /dev/null +++ b/public/registry/code-boxes.json @@ -0,0 +1,15 @@ +{ + "name": "code-boxes", + "title": "Code Boxes", + "category": "React Native", + "type": "components:ui", + "platform": "native", + "added": "2026-11-02", + "dependencies": [], + "files": [ + { + "path": "registry/code-boxes.tsx", + "content": "import { useEffect, useMemo, useRef, useState } from \"react\";\nimport {\n AccessibilityInfo,\n Animated,\n Platform,\n StyleSheet,\n Text,\n TextInput,\n View,\n type StyleProp,\n type ViewStyle,\n} from \"react-native\";\n\nconst NATIVE_DRIVER = Platform.OS !== \"web\";\nconst BOX_HEIGHT = 58;\n\nexport interface CodeBoxesColors {\n box: string;\n border: string;\n focusBorder: string;\n text: string;\n error: string;\n}\n\nconst DEFAULT_COLORS: CodeBoxesColors = {\n box: \"#ffffff\",\n border: \"#d1d5db\",\n focusBorder: \"#4f46e5\",\n text: \"#111827\",\n error: \"#dc2626\",\n};\n\nfunction useReduceMotion() {\n const [reduce, setReduce] = useState(false);\n useEffect(() => {\n AccessibilityInfo.isReduceMotionEnabled().then(setReduce);\n const sub = AccessibilityInfo.addEventListener(\"reduceMotionChanged\", setReduce);\n return () => sub.remove();\n }, []);\n return reduce;\n}\n\nexport interface CodeBoxesProps {\n /** The code entered so far. */\n value: string;\n onChange: (next: string) => void;\n /** How many characters make the code. */\n length?: number;\n /** Called once when the last character arrives, with the full code. */\n onComplete?: (code: string) => void;\n /** Accept digits only and show a numeric keyboard. */\n numeric?: boolean;\n autoFocus?: boolean;\n /** Turns the boxes the error color and shakes them. */\n error?: boolean;\n disabled?: boolean;\n colors?: Partial;\n style?: StyleProp;\n}\n\n/**\n * A one-time-code field drawn as separate boxes. One real, invisible input sits over them, so paste,\n * the keyboard and SMS autofill all work, and the boxes only show what it holds. The active box has\n * a ring and a blinking caret, each character pops in, and a wrong code shakes the row.\n */\nexport function CodeBoxes({\n value,\n onChange,\n length = 6,\n onComplete,\n numeric = true,\n autoFocus = false,\n error = false,\n disabled = false,\n colors,\n style,\n}: CodeBoxesProps) {\n const palette = { ...DEFAULT_COLORS, ...colors };\n const reduceMotion = useReduceMotion();\n const [focused, setFocused] = useState(false);\n // Re-rendering with an unchanged value makes the input drop a character we refused (a letter in\n // numeric mode); bumping this is how we force that.\n const [, setRefresh] = useState(0);\n const blink = useRef(new Animated.Value(1)).current;\n const shake = useRef(new Animated.Value(0)).current;\n const completedFor = useRef(null);\n const wasError = useRef(false);\n\n const clean = (raw: string) =>\n (numeric ? raw.replace(/\\D/g, \"\") : raw.replace(/[^a-z0-9]/gi, \"\")).slice(0, length);\n\n const handleChangeText = (raw: string) => {\n const next = clean(raw);\n if (next !== value) onChange(next);\n else if (raw !== value) setRefresh((n) => n + 1);\n };\n\n // Report completion once per complete code, and again only after it has been edited.\n const onCompleteRef = useRef(onComplete);\n onCompleteRef.current = onComplete;\n useEffect(() => {\n if (value.length < length) {\n completedFor.current = null;\n return;\n }\n if (value.length === length && completedFor.current !== value) {\n completedFor.current = value;\n onCompleteRef.current?.(value);\n }\n }, [value, length]);\n\n // The caret blinks on its own value, so it keeps running while the active box moves.\n useEffect(() => {\n blink.setValue(1);\n if (!focused || reduceMotion || disabled) return;\n const loop = Animated.loop(\n Animated.sequence([\n Animated.timing(blink, { toValue: 0, duration: 500, useNativeDriver: NATIVE_DRIVER }),\n Animated.timing(blink, { toValue: 1, duration: 500, useNativeDriver: NATIVE_DRIVER }),\n ]),\n );\n loop.start();\n return () => loop.stop();\n }, [focused, reduceMotion, disabled, blink]);\n\n // Shake once each time the error turns on.\n useEffect(() => {\n if (error && !wasError.current && !reduceMotion) {\n Animated.sequence(\n [-10, 10, -7, 7, -3, 0].map((toValue) =>\n Animated.timing(shake, { toValue, duration: 55, useNativeDriver: NATIVE_DRIVER }),\n ),\n ).start();\n }\n wasError.current = error;\n }, [error, reduceMotion, shake]);\n\n const rowStyle = useMemo(() => ({ transform: [{ translateX: shake }] }), [shake]);\n const active = Math.min(value.length, length - 1);\n\n return (\n \n \n \n {Array.from({ length }, (_, index) => (\n \n ))}\n \n setFocused(true)}\n onBlur={() => setFocused(false)}\n editable={!disabled}\n autoFocus={autoFocus}\n keyboardType={numeric ? \"number-pad\" : \"default\"}\n inputMode={numeric ? \"numeric\" : \"text\"}\n textContentType=\"oneTimeCode\"\n autoComplete=\"sms-otp\"\n autoCapitalize=\"none\"\n autoCorrect={false}\n // react-native-web blurs a single-line field on Enter unless told not to.\n blurOnSubmit={false}\n caretHidden\n selectionColor=\"transparent\"\n accessibilityLabel=\"Verification code\"\n aria-label=\"Verification code\"\n aria-disabled={disabled}\n style={styles.input}\n />\n \n \n {`${value.length} of ${length} ${numeric ? \"digits\" : \"characters\"} entered`}\n \n \n );\n}\n\nfunction Box({\n char,\n isActive,\n showCaret,\n error,\n disabled,\n blink,\n reduceMotion,\n palette,\n}: {\n char: string;\n isActive: boolean;\n showCaret: boolean;\n error: boolean;\n disabled: boolean;\n blink: Animated.Value;\n reduceMotion: boolean;\n palette: CodeBoxesColors;\n}) {\n const scale = useRef(new Animated.Value(1)).current;\n const previous = useRef(char);\n\n // Pop when a character lands in an empty box.\n useEffect(() => {\n if (char && !previous.current && !reduceMotion) {\n scale.setValue(0.8);\n Animated.spring(scale, {\n toValue: 1,\n stiffness: 520,\n damping: 14,\n mass: 1,\n useNativeDriver: NATIVE_DRIVER,\n }).start();\n }\n previous.current = char;\n }, [char, reduceMotion, scale]);\n\n const popStyle = useMemo(() => ({ transform: [{ scale }] }), [scale]);\n const caretStyle = useMemo(() => ({ opacity: blink }), [blink]);\n const borderColor = error ? palette.error : isActive ? palette.focusBorder : palette.border;\n\n return (\n \n {char}\n {/* Always mounted so its blink never restarts; only its visibility follows the active box. */}\n \n \n \n \n );\n}\n\nconst styles = StyleSheet.create({\n // userSelect keeps a mouse press on the web from selecting the digits.\n root: { alignSelf: \"stretch\", userSelect: \"none\" },\n wrap: { alignSelf: \"stretch\" },\n row: { flexDirection: \"row\", gap: 8 },\n box: {\n flex: 1,\n maxWidth: 56,\n height: BOX_HEIGHT,\n borderRadius: 12,\n alignItems: \"center\",\n justifyContent: \"center\",\n },\n char: { fontSize: 26, fontWeight: \"700\" },\n caretSlot: {\n position: \"absolute\",\n top: 0,\n right: 0,\n bottom: 0,\n left: 0,\n alignItems: \"center\",\n justifyContent: \"center\",\n },\n caret: { width: 2, height: 28, borderRadius: 1 },\n // Covers the boxes so a tap anywhere focuses it and paste lands in it, but shows nothing itself.\n input: {\n position: \"absolute\",\n top: 0,\n right: 0,\n bottom: 0,\n left: 0,\n opacity: 0,\n color: \"transparent\",\n },\n // Visually hidden, but still announced by screen readers.\n status: { position: \"absolute\", width: 1, height: 1, overflow: \"hidden\", opacity: 0 },\n});\n" + } + ] +} \ No newline at end of file diff --git a/public/registry/confirm-dialog.json b/public/registry/confirm-dialog.json new file mode 100644 index 0000000..61ee2fb --- /dev/null +++ b/public/registry/confirm-dialog.json @@ -0,0 +1,15 @@ +{ + "name": "confirm-dialog", + "title": "Confirm Dialog", + "category": "React Native", + "type": "components:ui", + "platform": "native", + "added": "2026-11-02", + "dependencies": [], + "files": [ + { + "path": "registry/confirm-dialog.tsx", + "content": "import { useEffect, useRef, useState, type ElementRef } from \"react\";\nimport {\n AccessibilityInfo,\n ActivityIndicator,\n Animated,\n Platform,\n Pressable,\n StyleSheet,\n Text,\n View,\n type StyleProp,\n type ViewStyle,\n} from \"react-native\";\n\nconst NATIVE_DRIVER = Platform.OS !== \"web\";\n// Past this many characters a label no longer fits two side-by-side buttons.\nconst LONG_LABEL = 14;\n\nexport interface ConfirmDialogColors {\n surface: string;\n backdrop: string;\n title: string;\n message: string;\n border: string;\n cancelText: string;\n confirm: string;\n confirmText: string;\n destructive: string;\n}\n\nconst DEFAULT_COLORS: ConfirmDialogColors = {\n surface: \"#ffffff\",\n backdrop: \"rgba(0, 0, 0, 0.5)\",\n title: \"#111827\",\n message: \"#6b7280\",\n border: \"#e5e7eb\",\n cancelText: \"#111827\",\n confirm: \"#4f46e5\",\n confirmText: \"#ffffff\",\n destructive: \"#dc2626\",\n};\n\nfunction useReduceMotion() {\n const [reduce, setReduce] = useState(false);\n useEffect(() => {\n AccessibilityInfo.isReduceMotionEnabled().then(setReduce);\n const sub = AccessibilityInfo.addEventListener(\"reduceMotionChanged\", setReduce);\n return () => sub.remove();\n }, []);\n return reduce;\n}\n\nexport interface ConfirmDialogProps {\n open: boolean;\n onConfirm: () => void;\n onCancel: () => void;\n title: string;\n message?: string;\n confirmLabel?: string;\n cancelLabel?: string;\n /** Styles the confirm button as a warning, for actions that cannot be undone. */\n destructive?: boolean;\n /** Shows a spinner in the confirm button and disables the dialog while work is under way. */\n loading?: boolean;\n colors?: Partial;\n style?: StyleProp;\n}\n\n/**\n * A centred alert dialog, drawn inside its parent so it works in a screen, a tab or a Modal alike.\n * It pops in on a spring over a dimmed backdrop. On the web focus starts on Cancel, so pressing Enter\n * can never confirm a destructive action by accident, and Escape cancels. While `loading` it cannot\n * be dismissed.\n */\nexport function ConfirmDialog({\n open,\n onConfirm,\n onCancel,\n title,\n message,\n confirmLabel = \"Confirm\",\n cancelLabel = \"Cancel\",\n destructive = false,\n loading = false,\n colors,\n style,\n}: ConfirmDialogProps) {\n const palette = { ...DEFAULT_COLORS, ...colors };\n const reduceMotion = useReduceMotion();\n const t = useRef(new Animated.Value(0)).current;\n const [mounted, setMounted] = useState(open);\n const cancelButton = useRef>(null);\n\n const live = useRef({ onCancel, loading });\n live.current = { onCancel, loading };\n\n useEffect(() => {\n if (open) setMounted(true);\n if (reduceMotion) {\n t.setValue(open ? 1 : 0);\n if (!open) setMounted(false);\n return;\n }\n Animated.spring(t, {\n toValue: open ? 1 : 0,\n stiffness: 360,\n damping: 28,\n mass: 1,\n useNativeDriver: NATIVE_DRIVER,\n }).start(({ finished }) => {\n if (finished && !open) setMounted(false);\n });\n }, [open, reduceMotion, t]);\n\n // Web: start on Cancel and let Escape cancel.\n useEffect(() => {\n if (!open || !mounted || Platform.OS !== \"web\") return;\n const focus = setTimeout(\n () => (cancelButton.current as unknown as HTMLElement | null)?.focus?.(),\n 30,\n );\n const onKey = (event: KeyboardEvent) => {\n if (event.key === \"Escape\" && !live.current.loading) live.current.onCancel();\n };\n window.addEventListener(\"keydown\", onKey);\n return () => {\n clearTimeout(focus);\n window.removeEventListener(\"keydown\", onKey);\n };\n }, [open, mounted]);\n\n if (!mounted) return null;\n\n const stacked = confirmLabel.length > LONG_LABEL || cancelLabel.length > LONG_LABEL;\n const accent = destructive ? palette.destructive : palette.confirm;\n\n return (\n \n \n \n \n \n {title}\n {message ? (\n {message}\n ) : null}\n \n [\n styles.button,\n { borderColor: palette.border, borderWidth: 1 },\n stacked && styles.fullWidth,\n (pressed || loading) && styles.dim,\n ]}\n >\n {cancelLabel}\n \n [\n styles.button,\n { backgroundColor: accent },\n stacked && styles.fullWidth,\n pressed && styles.dim,\n ]}\n >\n {loading ? (\n \n ) : (\n \n {confirmLabel}\n \n )}\n \n \n \n \n );\n}\n\nconst styles = StyleSheet.create({\n root: {\n position: \"absolute\",\n top: 0,\n right: 0,\n bottom: 0,\n left: 0,\n alignItems: \"center\",\n justifyContent: \"center\",\n padding: 24,\n },\n fill: { position: \"absolute\", top: 0, right: 0, bottom: 0, left: 0 },\n card: {\n width: \"100%\",\n maxWidth: 320,\n borderRadius: 20,\n padding: 20,\n gap: 8,\n boxShadow: \"0 20px 50px rgba(0, 0, 0, 0.3)\",\n },\n title: { fontSize: 18, fontWeight: \"700\" },\n message: { fontSize: 15, lineHeight: 21 },\n buttons: { flexDirection: \"row\", gap: 10, marginTop: 14 },\n stacked: { flexDirection: \"column-reverse\" },\n button: {\n flex: 1,\n minHeight: 46,\n borderRadius: 12,\n alignItems: \"center\",\n justifyContent: \"center\",\n paddingHorizontal: 12,\n userSelect: \"none\",\n },\n fullWidth: { flex: 0, width: \"100%\" },\n buttonText: { fontSize: 15, fontWeight: \"600\" },\n dim: { opacity: 0.7 },\n});\n" + } + ] +} \ No newline at end of file diff --git a/public/registry/hue-picker.json b/public/registry/hue-picker.json new file mode 100644 index 0000000..82177f6 --- /dev/null +++ b/public/registry/hue-picker.json @@ -0,0 +1,15 @@ +{ + "name": "hue-picker", + "title": "Hue Picker", + "category": "React Native", + "type": "components:ui", + "platform": "native", + "added": "2026-11-02", + "dependencies": [], + "files": [ + { + "path": "registry/hue-picker.tsx", + "content": "import { useEffect, useMemo, useRef, useState } from \"react\";\nimport {\n AccessibilityInfo,\n Animated,\n PanResponder,\n Platform,\n Pressable,\n StyleSheet,\n Text,\n View,\n type LayoutChangeEvent,\n type StyleProp,\n type ViewStyle,\n} from \"react-native\";\n\nconst NATIVE_DRIVER = Platform.OS !== \"web\";\nconst THUMB = 28;\nconst TRACK_INSET = 5;\nconst HUE_SEGMENTS = 72;\nconst LIGHT_SEGMENTS = 24;\nconst STEP = 5;\n// Hue 360 is the same colour as 0, so the far end of the strip stops just short of it and the thumb\n// never jumps back to the start.\nconst MAX_HUE = 359.99;\nconst FALLBACK = \"#4f46e5\";\n\nexport interface HuePickerColors {\n ring: string;\n text: string;\n}\n\nconst DEFAULT_COLORS: HuePickerColors = {\n ring: \"#111827\",\n text: \"#111827\",\n};\n\nconst DEFAULT_SWATCHES = [\n \"#ef4444\",\n \"#f97316\",\n \"#eab308\",\n \"#22c55e\",\n \"#14b8a6\",\n \"#3b82f6\",\n \"#8b5cf6\",\n \"#ec4899\",\n];\n\nconst HUE_COLORS = Array.from(\n { length: HUE_SEGMENTS },\n (_, i) => `hsl(${(i + 0.5) * (360 / HUE_SEGMENTS)}, 100%, 50%)`,\n);\n\nfunction useReduceMotion() {\n const [reduce, setReduce] = useState(false);\n useEffect(() => {\n AccessibilityInfo.isReduceMotionEnabled().then(setReduce);\n const sub = AccessibilityInfo.addEventListener(\"reduceMotionChanged\", setReduce);\n return () => sub.remove();\n }, []);\n return reduce;\n}\n\ninterface Hsl {\n /** Degrees, 0 to 360. */\n h: number;\n /** Percent. */\n s: number;\n /** Percent. */\n l: number;\n}\n\n/** \"#abc\" or \"#aabbcc\", any case, to \"#aabbcc\"; null when it is not a hex colour. */\nfunction normalizeHex(input: string): string | null {\n const match = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(input.trim());\n if (!match) return null;\n const digits = match[1].toLowerCase();\n const full = digits.length === 3 ? digits.replace(/./g, (c) => c + c) : digits;\n return `#${full}`;\n}\n\nfunction hexToHsl(hex: string): Hsl {\n const r = parseInt(hex.slice(1, 3), 16) / 255;\n const g = parseInt(hex.slice(3, 5), 16) / 255;\n const b = parseInt(hex.slice(5, 7), 16) / 255;\n const max = Math.max(r, g, b);\n const min = Math.min(r, g, b);\n const d = max - min;\n const l = (max + min) / 2;\n const s = d === 0 ? 0 : d / (1 - Math.abs(2 * l - 1));\n let h = 0;\n if (d !== 0) {\n if (max === r) h = ((g - b) / d) % 6;\n else if (max === g) h = (b - r) / d + 2;\n else h = (r - g) / d + 4;\n }\n return { h: (h * 60 + 360) % 360, s: s * 100, l: l * 100 };\n}\n\nfunction hslToHex({ h, s, l }: Hsl): string {\n const sat = s / 100;\n const light = l / 100;\n const chroma = (1 - Math.abs(2 * light - 1)) * sat;\n const sector = (((h % 360) + 360) % 360) / 60;\n const x = chroma * (1 - Math.abs((sector % 2) - 1));\n const [r, g, b] =\n sector < 1\n ? [chroma, x, 0]\n : sector < 2\n ? [x, chroma, 0]\n : sector < 3\n ? [0, chroma, x]\n : sector < 4\n ? [0, x, chroma]\n : sector < 5\n ? [x, 0, chroma]\n : [chroma, 0, x];\n const m = light - chroma / 2;\n const byte = (v: number) =>\n Math.max(0, Math.min(255, Math.round((v + m) * 255)))\n .toString(16)\n .padStart(2, \"0\");\n return `#${byte(r)}${byte(g)}${byte(b)}`;\n}\n\nexport interface HuePickerProps {\n /** The colour as a hex string such as \"#4f46e5\". Expected to echo `onChange`. */\n value: string;\n /** Called with a lowercase \"#rrggbb\" string as the colour changes. */\n onChange: (hex: string) => void;\n /** Colours offered as one-tap swatches. */\n swatches?: string[];\n /** Show the hex text next to the preview. */\n showValue?: boolean;\n colors?: Partial;\n style?: StyleProp;\n}\n\n/**\n * A colour picker built from plain Views: a hue strip, a lightness strip for the chosen hue, and\n * swatches. Hue, saturation and lightness are kept as numbers while you drag and only turned into\n * hex on the way out, so the hex never drifts and the hue survives passing through black or white.\n */\nexport function HuePicker({\n value,\n onChange,\n swatches = DEFAULT_SWATCHES,\n showValue = true,\n colors,\n style,\n}: HuePickerProps) {\n const palette = { ...DEFAULT_COLORS, ...colors };\n const reduceMotion = useReduceMotion();\n const initial = normalizeHex(value) ?? FALLBACK;\n const [hsl, setHsl] = useState(() => hexToHsl(initial));\n const [width, setWidth] = useState(0);\n const emitted = useRef(initial);\n const dragging = useRef<\"hue\" | \"light\" | null>(null);\n const placed = useRef(false);\n const start = useRef(0);\n const hueX = useRef(new Animated.Value(0)).current;\n const lightX = useRef(new Animated.Value(0)).current;\n const hueGrow = useRef(new Animated.Value(0)).current;\n const lightGrow = useRef(new Animated.Value(0)).current;\n\n const span = Math.max(0, width - THUMB);\n const hex = hslToHex(hsl);\n\n // The responders are created once, so they read the latest values from here.\n const live = useRef({ hsl, onChange, span, reduceMotion });\n live.current = { hsl: live.current.hsl, onChange, span, reduceMotion };\n\n // Adopt a colour the parent changed, but not the one we just reported.\n useEffect(() => {\n const next = normalizeHex(value);\n if (next && next !== emitted.current) {\n emitted.current = next;\n const parsed = hexToHsl(next);\n live.current.hsl = parsed;\n setHsl(parsed);\n }\n }, [value]);\n\n const apply = (next: Hsl) => {\n live.current.hsl = next;\n setHsl(next);\n const nextHex = hslToHex(next);\n if (nextHex !== emitted.current) {\n emitted.current = nextHex;\n live.current.onChange(nextHex);\n }\n };\n\n const spring = (node: Animated.Value, toValue: number) => {\n if (live.current.reduceMotion) {\n node.setValue(toValue);\n return;\n }\n Animated.spring(node, {\n toValue,\n stiffness: 420,\n damping: 28,\n mass: 1,\n useNativeDriver: NATIVE_DRIVER,\n }).start();\n };\n\n // Put the thumbs where the colour says. Dragging moves them directly, so skip it then.\n useEffect(() => {\n if (span <= 0 || dragging.current) return;\n const targets: [Animated.Value, number][] = [\n [hueX, (hsl.h / 360) * span],\n [lightX, (hsl.l / 100) * span],\n ];\n for (const [node, px] of targets) {\n if (!placed.current) node.setValue(px);\n else spring(node, px);\n }\n placed.current = true;\n // spring reads from refs; the dependencies below are what should re-run it.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [hsl.h, hsl.l, span, reduceMotion]);\n\n const move = (kind: \"hue\" | \"light\", x: number) => {\n const room = live.current.span;\n if (room <= 0) return;\n const ratio = Math.max(0, Math.min(1, (x - THUMB / 2) / room));\n if (kind === \"hue\") {\n hueX.setValue(ratio * room);\n apply({ ...live.current.hsl, h: Math.min(MAX_HUE, ratio * 360) });\n } else {\n lightX.setValue(ratio * room);\n apply({ ...live.current.hsl, l: ratio * 100 });\n }\n };\n\n const makePan = (kind: \"hue\" | \"light\") => {\n const grow = kind === \"hue\" ? hueGrow : lightGrow;\n const finish = () => {\n if (dragging.current !== kind) return;\n dragging.current = null;\n spring(grow, 0);\n };\n return PanResponder.create({\n onStartShouldSetPanResponder: () => true,\n onPanResponderTerminationRequest: () => false,\n onPanResponderGrant: (event) => {\n dragging.current = kind;\n start.current = event.nativeEvent.locationX;\n spring(grow, 1);\n // Touching the strip puts the thumb under the finger.\n move(kind, start.current);\n },\n onPanResponderMove: (_, g) => move(kind, start.current + g.dx),\n onPanResponderRelease: finish,\n onPanResponderTerminate: finish,\n });\n };\n const huePan = useRef(makePan(\"hue\")).current;\n const lightPan = useRef(makePan(\"light\")).current;\n\n const nudge = (kind: \"hue\" | \"light\", direction: 1 | -1) => {\n const current = live.current.hsl;\n if (kind === \"hue\") {\n apply({ ...current, h: Math.max(0, Math.min(MAX_HUE, current.h + direction * STEP)) });\n } else {\n apply({ ...current, l: Math.max(0, Math.min(100, current.l + direction * STEP)) });\n }\n };\n\n const choose = (swatch: string) => {\n const normal = normalizeHex(swatch);\n if (!normal) return;\n const parsed = hexToHsl(normal);\n live.current.hsl = parsed;\n setHsl(parsed);\n if (normal !== emitted.current) {\n emitted.current = normal;\n live.current.onChange(normal);\n }\n };\n\n // The lightness strip runs dark to light in the chosen hue and saturation.\n const hueKey = Math.round(hsl.h);\n const satKey = Math.round(hsl.s);\n const lightColors = useMemo(\n () =>\n Array.from(\n { length: LIGHT_SEGMENTS },\n (_, i) => `hsl(${hueKey}, ${satKey}%, ${(i / (LIGHT_SEGMENTS - 1)) * 100}%)`,\n ),\n [hueKey, satKey],\n );\n\n return (\n setWidth(event.nativeEvent.layout.width)}\n style={[styles.root, style]}\n >\n \n \n {showValue ? {hex} : null}\n \n nudge(\"hue\", direction)}\n />\n nudge(\"light\", direction)}\n />\n \n {swatches.map((swatch, index) => (\n choose(swatch)}\n />\n ))}\n \n \n );\n}\n\nfunction Strip({\n label,\n segments,\n x,\n grow,\n thumbColor,\n panHandlers,\n now,\n max,\n text,\n onNudge,\n}: {\n label: string;\n segments: string[];\n x: Animated.Value;\n grow: Animated.Value;\n thumbColor: string;\n panHandlers: object;\n now: number;\n max: number;\n text: string;\n onNudge: (direction: 1 | -1) => void;\n}) {\n // Built once so react-native-web never restarts a running spring when this re-renders.\n const thumbStyle = useMemo(\n () => ({\n transform: [\n { translateX: x },\n { scale: grow.interpolate({ inputRange: [0, 1], outputRange: [1, 1.18] }) },\n ],\n }),\n [x, grow],\n );\n\n return (\n \n onNudge(event.nativeEvent.actionName === \"increment\" ? 1 : -1)\n }\n style={styles.strip}\n >\n \n {segments.map((color, index) => (\n \n ))}\n \n \n \n );\n}\n\nfunction Swatch({\n hex,\n selected,\n ring,\n reduceMotion,\n onPress,\n}: {\n hex: string;\n selected: boolean;\n ring: string;\n reduceMotion: boolean;\n onPress: () => void;\n}) {\n const shown = useRef(new Animated.Value(selected ? 1 : 0)).current;\n\n useEffect(() => {\n if (reduceMotion) {\n shown.setValue(selected ? 1 : 0);\n return;\n }\n Animated.spring(shown, {\n toValue: selected ? 1 : 0,\n stiffness: 420,\n damping: 24,\n mass: 1,\n useNativeDriver: NATIVE_DRIVER,\n }).start();\n }, [selected, reduceMotion, shown]);\n\n const ringStyle = useMemo(\n () => ({\n opacity: shown,\n transform: [{ scale: shown.interpolate({ inputRange: [0, 1], outputRange: [0.75, 1] }) }],\n }),\n [shown],\n );\n\n return (\n \n \n \n \n );\n}\n\nconst styles = StyleSheet.create({\n // userSelect keeps a mouse drag on the web from selecting text instead of moving a thumb.\n root: { alignSelf: \"stretch\", gap: 16, userSelect: \"none\" },\n preview: { flexDirection: \"row\", alignItems: \"center\", gap: 12 },\n chip: {\n width: 48,\n height: 48,\n borderRadius: 14,\n borderWidth: 1,\n borderColor: \"rgba(0, 0, 0, 0.12)\",\n },\n hex: { fontSize: 18, fontWeight: \"700\", letterSpacing: 0.5 },\n strip: { height: THUMB, justifyContent: \"center\" },\n clip: {\n position: \"absolute\",\n top: TRACK_INSET,\n bottom: TRACK_INSET,\n left: 0,\n right: 0,\n flexDirection: \"row\",\n borderRadius: 10,\n overflow: \"hidden\",\n },\n segment: { flex: 1 },\n thumb: {\n position: \"absolute\",\n left: 0,\n top: 0,\n width: THUMB,\n height: THUMB,\n borderRadius: THUMB / 2,\n borderWidth: 3,\n borderColor: \"#ffffff\",\n boxShadow: \"0 1px 5px rgba(0, 0, 0, 0.35)\",\n },\n swatches: { flexDirection: \"row\", flexWrap: \"wrap\", gap: 10 },\n swatchHit: { width: 34, height: 34, alignItems: \"center\", justifyContent: \"center\" },\n swatch: { width: 26, height: 26, borderRadius: 13 },\n swatchRing: {\n position: \"absolute\",\n top: 0,\n left: 0,\n right: 0,\n bottom: 0,\n borderRadius: 17,\n borderWidth: 2.5,\n },\n});\n" + } + ] +} \ No newline at end of file diff --git a/public/registry/index.json b/public/registry/index.json index c79ecf0..0ca1e3f 100644 --- a/public/registry/index.json +++ b/public/registry/index.json @@ -1,7 +1,7 @@ { "name": "Modus UI", "homepage": "https://modusui.kasimkazmi.com", - "count": 239, + "count": 247, "categories": [ "Navigation", "Actions", @@ -2824,6 +2824,70 @@ "platform": "native", "description": "A React Native plus and minus stepper that repeats while held, speeding up the longer you hold, with the value sliding in from the direction it moved.", "dependencies": [] + }, + { + "name": "action-tray", + "title": "Action Tray", + "category": "React Native", + "platform": "native", + "description": "A React Native bottom action list that slides up over a dimmed backdrop, with grouped actions, a separate cancel button and drag to dismiss.", + "dependencies": [] + }, + { + "name": "confirm-dialog", + "title": "Confirm Dialog", + "category": "React Native", + "platform": "native", + "description": "A React Native alert dialog that pops in on a spring, starts focus on Cancel so Enter never confirms by accident, and locks while work is under way.", + "dependencies": [] + }, + { + "name": "code-boxes", + "title": "Code Boxes", + "category": "React Native", + "platform": "native", + "description": "A React Native one-time-code input drawn as separate boxes, with paste, SMS autofill, a blinking caret, a pop for each digit and a shake on error.", + "dependencies": [] + }, + { + "name": "hue-picker", + "title": "Hue Picker", + "category": "React Native", + "platform": "native", + "description": "A React Native colour picker built from plain Views, with a hue strip, a lightness strip for the chosen hue, one-tap swatches and a live preview.", + "dependencies": [] + }, + { + "name": "tab-pager", + "title": "Tab Pager", + "category": "React Native", + "platform": "native", + "description": "A React Native tab header over swipeable pages, with an underline that follows your finger and labels that blend as their page arrives.", + "dependencies": [] + }, + { + "name": "wheel-picker", + "title": "Wheel Picker", + "category": "React Native", + "platform": "native", + "description": "A React Native scrolling wheel that snaps rows to the middle, fades them with distance, and settles reliably even when a mouse wheel stops.", + "dependencies": [] + }, + { + "name": "avatar-stack", + "title": "Avatar Stack", + "category": "React Native", + "platform": "native", + "description": "A React Native stack of overlapping avatars that spreads apart on a press, collapses extras into a plus count, and reads out who is in it.", + "dependencies": [] + }, + { + "name": "stripe-progress", + "title": "Stripe Progress", + "category": "React Native", + "platform": "native", + "description": "A React Native progress bar whose fill grows on a spring and whose diagonal stripes drift, with an indeterminate mode and no gradient packages.", + "dependencies": [] } ], "renamed": { diff --git a/public/registry/stripe-progress.json b/public/registry/stripe-progress.json new file mode 100644 index 0000000..3c9f3fa --- /dev/null +++ b/public/registry/stripe-progress.json @@ -0,0 +1,15 @@ +{ + "name": "stripe-progress", + "title": "Stripe Progress", + "category": "React Native", + "type": "components:ui", + "platform": "native", + "added": "2026-11-02", + "dependencies": [], + "files": [ + { + "path": "registry/stripe-progress.tsx", + "content": "import { useEffect, useMemo, useRef, useState } from \"react\";\nimport {\n AccessibilityInfo,\n Animated,\n Easing,\n Platform,\n StyleSheet,\n Text,\n View,\n type LayoutChangeEvent,\n type StyleProp,\n type ViewStyle,\n} from \"react-native\";\n\nconst NATIVE_DRIVER = Platform.OS !== \"web\";\n// The indeterminate segment is this fraction of the track.\nconst SEGMENT = 0.4;\n// Horizontal distance between two stripes.\nconst MIN_PERIOD = 16;\n\nexport interface StripeProgressColors {\n track: string;\n fill: string;\n stripe: string;\n text: string;\n}\n\nconst DEFAULT_COLORS: StripeProgressColors = {\n track: \"#e5e7eb\",\n fill: \"#4f46e5\",\n stripe: \"rgba(255, 255, 255, 0.3)\",\n text: \"#374151\",\n};\n\nfunction useReduceMotion() {\n const [reduce, setReduce] = useState(false);\n useEffect(() => {\n AccessibilityInfo.isReduceMotionEnabled().then(setReduce);\n const sub = AccessibilityInfo.addEventListener(\"reduceMotionChanged\", setReduce);\n return () => sub.remove();\n }, []);\n return reduce;\n}\n\nexport interface StripeProgressProps {\n /** Progress from 0 to 1. Leave it out for an indeterminate bar. */\n value?: number;\n /** Height of the bar. */\n height?: number;\n /** Draws diagonal stripes on the fill. */\n striped?: boolean;\n /** Lets the stripes drift while the bar is determinate. */\n animated?: boolean;\n /** Spoken name of the bar. */\n label?: string;\n /** Shows the percentage next to the bar. */\n showPercent?: boolean;\n colors?: Partial;\n style?: StyleProp;\n}\n\n/**\n * A progress bar whose fill grows with a spring and whose diagonal stripes drift along it. Leave\n * `value` out and a segment travels across the track instead. Stripes are plain rotated views, so it\n * needs no gradient or SVG package. With reduced motion nothing drifts or travels, but the fill still\n * follows the value.\n */\nexport function StripeProgress({\n value,\n height = 10,\n striped = true,\n animated = true,\n label = \"Progress\",\n showPercent = false,\n colors,\n style,\n}: StripeProgressProps) {\n const palette = { ...DEFAULT_COLORS, ...colors };\n const reduceMotion = useReduceMotion();\n const [width, setWidth] = useState(0);\n const indeterminate = value === undefined;\n const clamped = Math.max(0, Math.min(1, value ?? 0));\n const percent = Math.round(clamped * 100);\n\n const fill = useRef(new Animated.Value(clamped)).current;\n const drift = useRef(new Animated.Value(0)).current;\n const travel = useRef(new Animated.Value(0)).current;\n\n const period = Math.max(MIN_PERIOD, height * 2);\n const stripeCount = width > 0 ? Math.ceil(width / period) + 3 : 0;\n const moving = !reduceMotion;\n\n // The fill follows the value.\n useEffect(() => {\n if (indeterminate) return;\n if (reduceMotion) {\n fill.setValue(clamped);\n return;\n }\n Animated.timing(fill, {\n toValue: clamped,\n duration: 450,\n easing: Easing.out(Easing.cubic),\n useNativeDriver: false,\n }).start();\n }, [clamped, indeterminate, reduceMotion, fill]);\n\n // Both loops start once the width is known, on views that are mounted from the start.\n useEffect(() => {\n if (width <= 0 || !moving) return;\n const loops: Animated.CompositeAnimation[] = [];\n if (striped && animated && !indeterminate) {\n drift.setValue(0);\n loops.push(\n Animated.loop(\n Animated.timing(drift, {\n toValue: period,\n duration: 900,\n easing: Easing.linear,\n useNativeDriver: NATIVE_DRIVER,\n }),\n ),\n );\n }\n if (indeterminate) {\n travel.setValue(0);\n loops.push(\n Animated.loop(\n Animated.timing(travel, {\n toValue: 1,\n duration: 1300,\n easing: Easing.inOut(Easing.quad),\n useNativeDriver: NATIVE_DRIVER,\n }),\n ),\n );\n }\n loops.forEach((loop) => loop.start());\n return () => loops.forEach((loop) => loop.stop());\n }, [width, moving, striped, animated, indeterminate, period, drift, travel]);\n\n const fillWidth = useMemo(\n () => fill.interpolate({ inputRange: [0, 1], outputRange: [0, width], extrapolate: \"clamp\" }),\n [fill, width],\n );\n const segmentWidth = width * SEGMENT;\n const segmentX = useMemo(\n () => travel.interpolate({ inputRange: [0, 1], outputRange: [-segmentWidth, width] }),\n [travel, width, segmentWidth],\n );\n const stripeList = useMemo(() => Array.from({ length: stripeCount }, (_, i) => i), [stripeCount]);\n\n return (\n \n setWidth(event.nativeEvent.layout.width)}\n style={[styles.track, { height, borderRadius: height / 2, backgroundColor: palette.track }]}\n >\n \n {striped ? (\n \n {stripeList.map((i) => (\n \n ))}\n \n ) : null}\n \n \n \n {showPercent ? (\n \n {indeterminate ? \"\" : `${percent}%`}\n \n ) : null}\n \n );\n}\n\nconst styles = StyleSheet.create({\n row: { flexDirection: \"row\", alignItems: \"center\", gap: 10 },\n track: { flex: 1, overflow: \"hidden\" },\n fill: { position: \"absolute\", top: 0, bottom: 0, left: 0, overflow: \"hidden\" },\n stripes: { position: \"absolute\", top: 0, bottom: 0 },\n segment: { position: \"absolute\", top: 0, bottom: 0, left: 0 },\n percent: { minWidth: 40, textAlign: \"right\", fontSize: 13, fontWeight: \"600\" },\n});\n" + } + ] +} \ No newline at end of file diff --git a/public/registry/tab-pager.json b/public/registry/tab-pager.json new file mode 100644 index 0000000..d1c7bc6 --- /dev/null +++ b/public/registry/tab-pager.json @@ -0,0 +1,15 @@ +{ + "name": "tab-pager", + "title": "Tab Pager", + "category": "React Native", + "type": "components:ui", + "platform": "native", + "added": "2026-11-02", + "dependencies": [], + "files": [ + { + "path": "registry/tab-pager.tsx", + "content": "import { useEffect, useRef, useState, type ElementRef, type ReactNode } from \"react\";\nimport {\n AccessibilityInfo,\n Animated,\n PanResponder,\n Platform,\n Pressable,\n ScrollView,\n StyleSheet,\n View,\n type LayoutChangeEvent,\n type NativeScrollEvent,\n type NativeSyntheticEvent,\n type StyleProp,\n type ViewStyle,\n} from \"react-native\";\n\nexport interface TabPagerTab {\n id: string;\n label: string;\n}\n\nexport interface TabPagerColors {\n text: string;\n activeText: string;\n indicator: string;\n border: string;\n background: string;\n}\n\nconst DEFAULT_COLORS: TabPagerColors = {\n text: \"#6b7280\",\n activeText: \"#111827\",\n indicator: \"#4f46e5\",\n border: \"#e5e7eb\",\n background: \"#ffffff\",\n};\n\nfunction useReduceMotion() {\n const [reduce, setReduce] = useState(false);\n useEffect(() => {\n AccessibilityInfo.isReduceMotionEnabled().then(setReduce);\n const sub = AccessibilityInfo.addEventListener(\"reduceMotionChanged\", setReduce);\n return () => sub.remove();\n }, []);\n return reduce;\n}\n\nexport interface TabPagerProps {\n tabs: TabPagerTab[];\n /** Renders the content of one page. */\n renderPage: (tab: TabPagerTab, index: number) => ReactNode;\n /** The id of the selected tab. */\n value: string;\n onChange: (id: string) => void;\n colors?: Partial;\n style?: StyleProp;\n}\n\ninterface Box {\n x: number;\n width: number;\n}\n\n/**\n * Swipeable pages under a row of tabs. The underline follows your finger between the two tabs it is\n * travelling across, growing or shrinking to each label's width, and the labels blend from muted to\n * active as their page arrives. Tapping a tab scrolls to its page. On desktop browsers the pages can\n * also be dragged with a mouse.\n */\nexport function TabPager({ tabs, renderPage, value, onChange, colors, style }: TabPagerProps) {\n const palette = { ...DEFAULT_COLORS, ...colors };\n const reduceMotion = useReduceMotion();\n const [width, setWidth] = useState(0);\n const [boxes, setBoxes] = useState([]);\n // Paging snaps the scroll back on the web, so it is switched off while a mouse drags the pages.\n const [snapping, setSnapping] = useState(true);\n const pages = useRef>(null);\n const header = useRef>(null);\n const scrollX = useRef(new Animated.Value(0)).current;\n const offset = useRef(0);\n const current = useRef(\n Math.max(\n 0,\n tabs.findIndex((tab) => tab.id === value),\n ),\n );\n // True during a mouse drag and for a moment after it: the click a mouse sends on release is not a tap.\n const dragging = useRef(false);\n const dragStart = useRef(0);\n const headerWidth = useRef(0);\n\n const index = Math.max(\n 0,\n tabs.findIndex((tab) => tab.id === value),\n );\n const last = tabs.length - 1;\n\n const live = useRef({ width, last, reduceMotion, onChange, tabs, boxes });\n live.current = { width, last, reduceMotion, onChange, tabs, boxes };\n\n const goTo = (target: number, animated = !live.current.reduceMotion) => {\n const clamped = Math.max(0, Math.min(live.current.last, target));\n pages.current?.scrollTo({ x: clamped * live.current.width, animated });\n };\n\n // Keep the selected tab's page in view when `value` changes from outside.\n useEffect(() => {\n if (width <= 0 || index === current.current) return;\n current.current = index;\n goTo(index);\n // goTo reads everything through refs.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [index, width]);\n\n // Put the first page in place once the width is known.\n useEffect(() => {\n if (width <= 0) return;\n scrollX.setValue(index * width);\n pages.current?.scrollTo({ x: index * width, animated: false });\n // Only the first measurement positions the pages.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [width > 0]);\n\n // Slide the header so the selected label stays visible when there are many tabs.\n useEffect(() => {\n const box = boxes[index];\n if (!box || headerWidth.current <= 0) return;\n header.current?.scrollTo({\n x: Math.max(0, box.x - (headerWidth.current - box.width) / 2),\n animated: !reduceMotion,\n });\n }, [index, boxes, reduceMotion]);\n\n const settle = (x: number) => {\n offset.current = x;\n const next = Math.max(0, Math.min(live.current.last, Math.round(x / live.current.width)));\n if (next !== current.current) {\n current.current = next;\n live.current.onChange(live.current.tabs[next].id);\n AccessibilityInfo.announceForAccessibility(\n `${live.current.tabs[next].label}, tab ${next + 1} of ${live.current.last + 1}`,\n );\n }\n };\n\n const onScroll = (event: NativeSyntheticEvent) => {\n offset.current = event.nativeEvent.contentOffset.x;\n };\n\n // A mouse cannot drag a scroll view, so on desktop browsers the pages are dragged by hand.\n const mouseDrag = useRef(\n PanResponder.create({\n onMoveShouldSetPanResponder: (_, g) =>\n Platform.OS === \"web\" &&\n typeof window !== \"undefined\" &&\n window.matchMedia(\"(pointer: fine)\").matches &&\n Math.abs(g.dx) > 6 &&\n Math.abs(g.dx) > Math.abs(g.dy),\n onPanResponderGrant: () => {\n dragging.current = true;\n dragStart.current = offset.current;\n setSnapping(false);\n },\n onPanResponderMove: (_, g) => {\n pages.current?.scrollTo({ x: dragStart.current - g.dx, animated: false });\n },\n onPanResponderRelease: (_, g) => {\n setTimeout(() => (dragging.current = false), 80);\n setSnapping(true);\n // Carry a flick on to the next page, otherwise settle on the nearest one.\n const target = Math.round((offset.current - g.vx * 160) / live.current.width);\n const clamped = Math.max(0, Math.min(live.current.last, target));\n goTo(clamped);\n settle(clamped * live.current.width);\n },\n onPanResponderTerminate: () => {\n setTimeout(() => (dragging.current = false), 80);\n setSnapping(true);\n goTo(Math.round(offset.current / live.current.width));\n },\n }),\n ).current;\n\n const ready = width > 0 && boxes.length === tabs.length && tabs.length > 1;\n const inputRange = tabs.map((_, i) => i * width);\n\n const indicatorX = ready\n ? scrollX.interpolate({\n inputRange,\n outputRange: boxes.map((box) => box.x),\n extrapolate: \"clamp\",\n })\n : 0;\n const indicatorWidth = ready\n ? scrollX.interpolate({\n inputRange,\n outputRange: boxes.map((box) => box.width),\n extrapolate: \"clamp\",\n })\n : (boxes[0]?.width ?? 0);\n\n return (\n \n \n {\n headerWidth.current = event.nativeEvent.layout.width;\n }}\n accessibilityRole=\"tablist\"\n contentContainerStyle={styles.header}\n >\n {tabs.map((tab, i) => {\n const selected = i === index;\n const color = ready\n ? scrollX.interpolate({\n inputRange: [(i - 1) * width, i * width, (i + 1) * width],\n outputRange: [palette.text, palette.activeText, palette.text],\n extrapolate: \"clamp\",\n })\n : selected\n ? palette.activeText\n : palette.text;\n return (\n {\n const { x, width: w } = event.nativeEvent.layout;\n setBoxes((all) => {\n const next = [...all];\n next[i] = { x, width: w };\n return next;\n });\n }}\n onPress={() => {\n if (dragging.current) return;\n goTo(i);\n settle(i * live.current.width);\n }}\n style={styles.tab}\n >\n \n {tab.label}\n \n \n );\n })}\n {boxes.length > 0 ? (\n \n ) : null}\n \n \n setWidth(event.nativeEvent.layout.width)}\n style={styles.body}\n >\n {width > 0 ? (\n \n settle(event.nativeEvent.contentOffset.x)}\n onScrollEndDrag={(event) => {\n // Without momentum (a slow drag that stops on a page) the momentum event never fires.\n if (!live.current.reduceMotion) return;\n settle(event.nativeEvent.contentOffset.x);\n }}\n >\n {tabs.map((tab, i) => (\n \n {renderPage(tab, i)}\n \n ))}\n \n \n ) : null}\n \n \n );\n}\n\nconst styles = StyleSheet.create({\n root: { flex: 1 },\n headerWrap: { borderBottomWidth: StyleSheet.hairlineWidth },\n header: { paddingHorizontal: 8, position: \"relative\" },\n tab: { minHeight: 48, paddingHorizontal: 14, justifyContent: \"center\", userSelect: \"none\" },\n label: { fontSize: 15, fontWeight: \"600\" },\n indicator: { position: \"absolute\", left: 0, bottom: 0, height: 3, borderRadius: 2 },\n body: { flex: 1 },\n // userSelect keeps a mouse drag on the web from selecting the page's text instead of moving the pages.\n drag: { flex: 1, userSelect: \"none\" },\n});\n" + } + ] +} \ No newline at end of file diff --git a/public/registry/wheel-picker.json b/public/registry/wheel-picker.json new file mode 100644 index 0000000..b04c8e0 --- /dev/null +++ b/public/registry/wheel-picker.json @@ -0,0 +1,15 @@ +{ + "name": "wheel-picker", + "title": "Wheel Picker", + "category": "React Native", + "type": "components:ui", + "platform": "native", + "added": "2026-11-02", + "dependencies": [], + "files": [ + { + "path": "registry/wheel-picker.tsx", + "content": "import { useEffect, useMemo, useRef, useState, type ElementRef } from \"react\";\nimport {\n AccessibilityInfo,\n Animated,\n Platform,\n Pressable,\n ScrollView,\n StyleSheet,\n View,\n type NativeScrollEvent,\n type NativeSyntheticEvent,\n type StyleProp,\n type ViewStyle,\n} from \"react-native\";\n\nconst NATIVE_DRIVER = Platform.OS !== \"web\";\n// How long the scroll must be still before a mouse wheel counts as settled.\nconst SETTLE_MS = 140;\n\nexport interface WheelPickerOption {\n value: string;\n label: string;\n}\n\nexport interface WheelPickerColors {\n text: string;\n selectedText: string;\n highlight: string;\n}\n\nconst DEFAULT_COLORS: WheelPickerColors = {\n text: \"#6b7280\",\n selectedText: \"#111827\",\n highlight: \"#f3f4f6\",\n};\n\nfunction useReduceMotion() {\n const [reduce, setReduce] = useState(false);\n useEffect(() => {\n AccessibilityInfo.isReduceMotionEnabled().then(setReduce);\n const sub = AccessibilityInfo.addEventListener(\"reduceMotionChanged\", setReduce);\n return () => sub.remove();\n }, []);\n return reduce;\n}\n\nexport interface WheelPickerProps {\n options: WheelPickerOption[];\n /** The selected option's `value`. */\n value: string;\n /** Called once the wheel settles on a different option, not on every frame of the scroll. */\n onChange: (value: string) => void;\n /** Height of one row. */\n itemHeight?: number;\n /** How many rows are visible. Use an odd number so one row sits in the middle. */\n visibleCount?: number;\n /** Spoken name of the wheel, for example \"Hour\". */\n label?: string;\n colors?: Partial;\n style?: StyleProp;\n}\n\n/**\n * An iOS-style scrolling wheel. Rows snap to the middle, shrink and fade with their distance from it,\n * and `onChange` fires when the wheel comes to rest, including when a mouse wheel stops. A tap on a\n * row brings it to the middle, and screen readers can step through the options.\n */\nexport function WheelPicker({\n options,\n value,\n onChange,\n itemHeight = 40,\n visibleCount = 5,\n label = \"Picker\",\n colors,\n style,\n}: WheelPickerProps) {\n const palette = { ...DEFAULT_COLORS, ...colors };\n const reduceMotion = useReduceMotion();\n const scroll = useRef>(null);\n const y = useRef(new Animated.Value(0)).current;\n const offset = useRef(0);\n const timer = useRef | null>(null);\n\n const index = Math.max(\n 0,\n options.findIndex((option) => option.value === value),\n );\n // The option the wheel last settled on, so a settle that changes nothing stays quiet.\n const settled = useRef(index);\n const rows = Math.max(1, visibleCount);\n const pad = Math.floor(rows / 2) * itemHeight;\n\n const live = useRef({ options, itemHeight, reduceMotion, onChange });\n live.current = { options, itemHeight, reduceMotion, onChange };\n\n const scrollToIndex = (target: number, animated = !live.current.reduceMotion) => {\n scroll.current?.scrollTo({ y: target * live.current.itemHeight, animated });\n };\n\n const settle = () => {\n const { options: list, itemHeight: h } = live.current;\n const next = Math.max(0, Math.min(list.length - 1, Math.round(offset.current / h)));\n // On the web a wheel can stop between rows, so finish the snap by hand.\n if (Math.abs(offset.current - next * h) > 1) scrollToIndex(next);\n if (next !== settled.current) {\n settled.current = next;\n live.current.onChange(list[next].value);\n }\n };\n\n const queueSettle = () => {\n if (timer.current) clearTimeout(timer.current);\n timer.current = setTimeout(settle, SETTLE_MS);\n };\n\n useEffect(\n () => () => {\n if (timer.current) clearTimeout(timer.current);\n },\n [],\n );\n\n // Start on the selected row, and follow `value` when it changes from outside.\n useEffect(() => {\n if (index === settled.current && Math.abs(offset.current - index * itemHeight) < 2) return;\n settled.current = index;\n scrollToIndex(index, offset.current !== 0);\n // scrollToIndex reads everything through refs.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [index, itemHeight]);\n\n const onScroll = (event: NativeSyntheticEvent) => {\n offset.current = event.nativeEvent.contentOffset.y;\n queueSettle();\n };\n\n const step = (direction: 1 | -1) => {\n const next = Math.max(0, Math.min(options.length - 1, index + direction));\n if (next === index) return;\n settled.current = next;\n scrollToIndex(next);\n onChange(options[next].value);\n };\n\n const rowStyles = useMemo(\n () =>\n options.map((_, i) => {\n const at = (n: number) => (i + n) * itemHeight;\n const range = [at(-2), at(-1), at(0), at(1), at(2)];\n return {\n opacity: y.interpolate({\n inputRange: range,\n outputRange: [0.25, 0.5, 1, 0.5, 0.25],\n extrapolate: \"clamp\",\n }),\n scale: reduceMotion\n ? 1\n : y.interpolate({\n inputRange: range,\n outputRange: [0.8, 0.9, 1, 0.9, 0.8],\n extrapolate: \"clamp\",\n }),\n // The selected colour fades in over the plain one as a row nears the middle.\n selected: y.interpolate({\n inputRange: [at(-1), at(0), at(1)],\n outputRange: [0, 1, 0],\n extrapolate: \"clamp\",\n }),\n };\n }),\n [options, itemHeight, y, reduceMotion],\n );\n\n return (\n step(event.nativeEvent.actionName === \"increment\" ? 1 : -1)}\n style={[styles.root, { height: itemHeight * rows }, style]}\n >\n \n \n {options.map((option, i) => (\n {\n scrollToIndex(i);\n offset.current = i * itemHeight;\n queueSettle();\n }}\n style={{ height: itemHeight, justifyContent: \"center\", alignItems: \"center\" }}\n >\n \n \n {option.label}\n \n \n {option.label}\n \n \n \n ))}\n \n \n );\n}\n\nconst styles = StyleSheet.create({\n root: { overflow: \"hidden\", userSelect: \"none\" },\n band: { position: \"absolute\", left: 0, right: 0, borderRadius: 10 },\n label: { fontSize: 20, fontWeight: \"600\", textAlign: \"center\" },\n over: { position: \"absolute\", left: 0, right: 0, top: 0 },\n});\n" + } + ] +} \ No newline at end of file diff --git a/src/content/docs/action-tray.mdx b/src/content/docs/action-tray.mdx new file mode 100644 index 0000000..2e1248a --- /dev/null +++ b/src/content/docs/action-tray.mdx @@ -0,0 +1,66 @@ +--- +title: Action Tray +description: A React Native bottom action list that slides up over a dimmed backdrop, with grouped actions, a separate cancel button and drag to dismiss. +--- + +A bottom action list in the style of a native action sheet. It slides up from the bottom of its parent over a dimmed backdrop, with the actions as one rounded group and Cancel as a separate button. Tap the backdrop, press Escape on the web, or drag the handle down to close it. It is drawn inside its parent, so it works in a screen, a tab or a `Modal` alike, and on the web it stays inside whatever frame holds it. Built for React Native and Expo with `react-native` only; this page previews it in the browser through react-native-web. + + + +## Installation + +### CLI + +```bash +npx @modus-ui/cli add action-tray +``` + +### Manual + +1. Copy the code from the component tab. +2. Create a file at `components/ui/action-tray.tsx`. +3. Paste the code. + +It needs no packages beyond `react-native`, which your Expo or React Native app already has. + +## Usage + +```tsx +import { useState } from "react"; +import { Button, View } from "react-native"; +import { ActionTray } from "@/components/ui/action-tray"; + +export default function Example() { + const [open, setOpen] = useState(false); + + return ( + +