wip convo ui

This commit is contained in:
2026-06-23 00:59:06 +01:00
parent 25713ef614
commit 57c3275cce
30 changed files with 1649 additions and 251 deletions

View File

@@ -15,6 +15,8 @@
"create-admin": "bun run src/scripts/create-admin.ts"
},
"dependencies": {
"@better-auth/core": "^1.6.20",
"@better-auth/expo": "^1.6.20",
"@earendil-works/pi-coding-agent": "^0.79.1",
"@freya/agent-protocol": "workspace:*",
"@freya/core": "workspace:*",
@@ -29,7 +31,7 @@
"@nym.sh/jrpc": "^0.1.0",
"@openrouter/sdk": "^0.9.11",
"arktype": "^2.1.29",
"better-auth": "^1",
"better-auth": "^1.6.20",
"drizzle-orm": "^0.45.1",
"hono": "^4",
"lodash.merge": "^4.6.2",

View File

@@ -1,3 +1,4 @@
import { expo } from "@better-auth/expo"
import { betterAuth } from "better-auth"
import { drizzleAdapter } from "better-auth/adapters/drizzle"
import { admin } from "better-auth/plugins"
@@ -32,7 +33,7 @@ export function createAuth(db: Database) {
},
},
},
plugins: [admin()],
plugins: [admin(), expo()],
})
}

View File

@@ -255,7 +255,8 @@
}
],
"expo-web-browser",
"expo-image"
"expo-image",
"expo-secure-store"
],
"experiments": {
"typedRoutes": true,

View File

@@ -1,61 +1,72 @@
{
"name": "freya-client",
"version": "1.0.0",
"private": true,
"main": "expo-router/entry",
"scripts": {
"start": "./scripts/run-dev-server.sh",
"reset-project": "node ./scripts/reset-project.js",
"android": "expo start --android",
"ios": "expo start --ios",
"web": "expo start --web",
"lint": "expo lint",
"build:ios": "bunx eas-cli build --profile development --platform ios --non-interactive",
"build:ios-simulator": "bunx eas-cli build --profile development-simulator --platform ios --non-interactive",
"debugger": "bun run scripts/open-debugger.ts"
},
"dependencies": {
"@expo-google-fonts/inter": "^0.4.2",
"@expo-google-fonts/source-serif-4": "^0.4.1",
"@expo/vector-icons": "^15.0.3",
"@freya/core": "workspace:*",
"@json-render/react-native": "^0.13.0",
"@shopify/flash-list": "2.0.2",
"@tanstack/react-query": "^5.90.21",
"arktype": "^2.2.1",
"expo": "^56.0.0",
"expo-blur": "~56.0.3",
"expo-constants": "~56.0.18",
"expo-dev-client": "~56.0.20",
"expo-font": "~56.0.7",
"expo-glass-effect": "~0.1.10",
"expo-haptics": "~56.0.3",
"expo-image": "~56.0.11",
"expo-linking": "~56.0.14",
"expo-location": "~56.0.18",
"expo-router": "~56.2.11",
"expo-splash-screen": "~56.0.10",
"expo-status-bar": "~56.0.4",
"expo-symbols": "~56.0.6",
"expo-system-ui": "~56.0.5",
"expo-web-browser": "~56.0.5",
"react": "19.2.3",
"react-dom": "19.2.3",
"react-native": "0.85.3",
"react-native-gesture-handler": "~2.31.1",
"react-native-reanimated": "4.3.1",
"react-native-safe-area-context": "~5.7.0",
"react-native-screens": "4.25.2",
"react-native-svg": "15.15.4",
"react-native-web": "~0.21.0",
"react-native-worklets": "0.8.3",
"twrnc": "^4.16.0",
"zod": "^4.3.6"
},
"devDependencies": {
"@types/react": "~19.2.10",
"eslint": "^9.25.0",
"eslint-config-expo": "~56.0.4",
"typescript": "~6.0.3"
}
"name": "freya-client",
"version": "1.0.0",
"private": true,
"main": "expo-router/entry",
"scripts": {
"start": "./scripts/run-dev-server.sh",
"reset-project": "node ./scripts/reset-project.js",
"android": "expo start --android",
"ios": "expo start --ios",
"web": "expo start --web",
"lint": "expo lint",
"build:ios": "bunx eas-cli build --profile development --platform ios --non-interactive",
"build:ios-simulator": "bunx eas-cli build --profile development-simulator --platform ios --non-interactive",
"debugger": "bun run scripts/open-debugger.ts"
},
"dependencies": {
"@better-auth/core": "^1.6.20",
"@better-auth/expo": "^1.6.20",
"@expo-google-fonts/inter": "^0.4.2",
"@expo-google-fonts/source-serif-4": "^0.4.1",
"@expo/vector-icons": "^15.0.3",
"@freya/core": "workspace:*",
"@json-render/react-native": "^0.13.0",
"@react-native-masked-view/masked-view": "0.3.2",
"@shopify/flash-list": "2.0.2",
"@tanstack/react-query": "^5.90.21",
"arktype": "^2.2.1",
"better-auth": "^1.6.20",
"class-variance-authority": "^0.7.1",
"expo": "^56.0.0",
"expo-blur": "~56.0.3",
"expo-constants": "~56.0.18",
"expo-dev-client": "~56.0.20",
"expo-font": "~56.0.7",
"expo-glass-effect": "~0.1.10",
"expo-haptics": "~56.0.3",
"expo-image": "~56.0.11",
"expo-linear-gradient": "~56.0.4",
"expo-linking": "~56.0.14",
"expo-location": "~56.0.18",
"expo-network": "~56.0.5",
"expo-router": "~56.2.11",
"expo-secure-store": "~56.0.4",
"expo-splash-screen": "~56.0.10",
"expo-status-bar": "~56.0.4",
"expo-symbols": "~56.0.6",
"expo-system-ui": "~56.0.5",
"expo-web-browser": "~56.0.5",
"jotai": "^2.20.1",
"react": "19.2.3",
"react-dom": "19.2.3",
"react-native": "0.85.3",
"react-native-easing-gradient": "^1.1.1",
"react-native-gesture-handler": "~2.31.1",
"react-native-keyboard-controller": "1.21.6",
"react-native-reanimated": "4.3.1",
"react-native-safe-area-context": "~5.7.0",
"react-native-screens": "4.25.2",
"react-native-svg": "15.15.4",
"react-native-web": "~0.21.0",
"react-native-worklets": "0.8.3",
"twrnc": "^4.16.0",
"zod": "^4.3.6"
},
"devDependencies": {
"@types/react": "~19.2.10",
"eslint": "^9.25.0",
"eslint-config-expo": "~56.0.4",
"typescript": "~6.0.3"
}
}

View File

@@ -23,6 +23,8 @@ function forwardHeaders(headers: Headers): Headers {
interface WsData {
upstream: WebSocket
upstreamUrl: string
path: string
isDevice: boolean
}
@@ -42,8 +44,10 @@ Bun.serve<WsData>({
// WebSocket upgrade — bridge to Metro's ws endpoint
if (req.headers.get("upgrade")?.toLowerCase() === "websocket") {
const wsUrl = `${METRO_WS_BASE}${url.pathname}${url.search}`
const upstream = new WebSocket(wsUrl)
const path = `${url.pathname}${url.search}`
const wsUrl = `${METRO_WS_BASE}${path}`
console.log(`[proxy] ws connecting ${path}`)
const upstream = connectUpstreamWebSocket(wsUrl, getWebSocketHeaders(req, url))
// Wait for upstream to connect before upgrading the client
try {
@@ -56,7 +60,7 @@ Bun.serve<WsData>({
}
const isDevice = url.pathname.startsWith("/inspector/device")
const ok = server.upgrade(req, { data: { upstream, isDevice } })
const ok = server.upgrade(req, { data: { upstream, upstreamUrl: wsUrl, path, isDevice } })
if (!ok) {
upstream.close()
return new Response("WebSocket upgrade failed", { status: 500 })
@@ -83,19 +87,28 @@ Bun.serve<WsData>({
websocket: {
message(ws: ServerWebSocket<WsData>, msg) {
ws.data.upstream.send(msg)
sendUpstream(ws.data.upstream, msg)
},
open(ws: ServerWebSocket<WsData>) {
const { upstream } = ws.data
console.log(`[proxy] ws open ${ws.data.path}`)
upstream.addEventListener("message", (ev) => {
if (typeof ev.data === "string") {
ws.send(ev.data)
} else if (ev.data instanceof ArrayBuffer) {
ws.sendBinary(new Uint8Array(ev.data))
} else if (ev.data instanceof Blob) {
ev.data.arrayBuffer().then((buffer) => ws.sendBinary(new Uint8Array(buffer)))
}
})
upstream.addEventListener("close", () => ws.close())
upstream.addEventListener("error", () => ws.close())
upstream.addEventListener("close", (ev) => {
console.log(`[proxy] upstream close ${ws.data.path} code=${ev.code} reason=${ev.reason}`)
ws.close(ev.code, ev.reason)
})
upstream.addEventListener("error", () => {
console.error(`[proxy] upstream error ${ws.data.upstreamUrl}`)
ws.close()
})
// Print debugger URL shortly after a device connects,
// giving Metro time to register the target.
@@ -104,6 +117,7 @@ Bun.serve<WsData>({
}
},
close(ws: ServerWebSocket<WsData>) {
console.log(`[proxy] client close ${ws.data.path}`)
ws.data.upstream.close()
},
},
@@ -120,7 +134,7 @@ async function printDebuggerUrl() {
if (!Array.isArray(parsedTargets)) return
const targets = parsedTargets.filter(isDebugTarget)
const target = targets.find((t) => t.reactNative?.capabilities?.prefersFuseboxFrontend)
const target = targets.find(prefersFuseboxFrontend) ?? targets[0]
if (!target) return
const wsPath = getProxyWebSocketPath(target.webSocketDebuggerUrl)
@@ -153,6 +167,29 @@ async function fetchUpstream(
}
}
function sendUpstream(upstream: WebSocket, msg: string | Buffer) {
if (typeof msg === "string") {
upstream.send(msg)
return
}
upstream.send(new Uint8Array(msg))
}
function getWebSocketHeaders(req: Request, url: URL) {
return {
Origin: req.headers.get("origin") ?? url.origin,
}
}
function connectUpstreamWebSocket(url: string, headers: Record<string, string>) {
const BunWebSocket = WebSocket as unknown as {
new (url: string, options: { headers: Record<string, string> }): WebSocket
}
return new BunWebSocket(url, { headers })
}
function isDebugTarget(value: unknown): value is DebugTarget {
if (!isRecord(value) || typeof value.webSocketDebuggerUrl !== "string") return false
@@ -168,6 +205,10 @@ function isDebugTarget(value: unknown): value is DebugTarget {
return prefersFuseboxFrontend === undefined || typeof prefersFuseboxFrontend === "boolean"
}
function prefersFuseboxFrontend(target: DebugTarget) {
return target.reactNative?.capabilities?.prefersFuseboxFrontend === true
}
function getProxyWebSocketPath(webSocketDebuggerUrl: string) {
const url = new URL(webSocketDebuggerUrl)
return `${tsIp}:${PROXY_PORT}${url.pathname}${url.search}`

View File

@@ -29,7 +29,7 @@ if (!Array.isArray(parsedTargets)) {
}
const targets = parsedTargets.filter(isDebugTarget)
const target = targets.find((t) => t.reactNative?.capabilities?.prefersFuseboxFrontend)
const target = targets.find(prefersFuseboxFrontend) ?? targets[0]
if (!target) {
console.error("No debug target found. Is the app connected?")
@@ -68,6 +68,10 @@ function isDebugTarget(value: unknown): value is DebugTarget {
return prefersFuseboxFrontend === undefined || typeof prefersFuseboxFrontend === "boolean"
}
function prefersFuseboxFrontend(target: DebugTarget) {
return target.reactNative?.capabilities?.prefersFuseboxFrontend === true
}
function getProxyWebSocketPath(webSocketDebuggerUrl: string) {
const url = new URL(webSocketDebuggerUrl)
return `${tsIp}:${PROXY_PORT}${url.pathname}${url.search}`

View File

@@ -1,6 +0,0 @@
import { ApiRequestMiddleware } from "./client"
export const authMiddleware: ApiRequestMiddleware = (_url, init) => {
// TODO: placeholder auth middleware
return init
}

View File

@@ -27,9 +27,12 @@ export class ApiClient {
(prevInit, middleware) => middleware(url, prevInit),
init,
)
return fetch(this.baseUrl ? new URL(url.toString(), this.baseUrl) : url, finalInit).then(
(res) => Promise.all([Promise.resolve(res), res.json()]),
)
return fetch(this.baseUrl ? this.baseUrl + url : url, finalInit)
.then((res) => Promise.all([Promise.resolve(res), res.json()]))
.catch((err) => {
console.log(`request error: ${url}`, err)
throw err
})
}
}

View File

@@ -0,0 +1,134 @@
import { Link } from "expo-router"
import { Pressable, ScrollView, View } from "react-native"
import tw from "twrnc"
import { FeedCard } from "@/components/ui/feed-card"
import { MonospaceText } from "@/components/ui/monospace-text"
import { SansSerifText } from "@/components/ui/sans-serif-text"
import { SerifText } from "@/components/ui/serif-text"
import { ChatOverlay } from "@/conversations/chat-overlay"
export default function HomeScreen() {
return (
<View style={tw`bg-stone-100 dark:bg-stone-950 flex-1 relative`}>
<ScrollView
contentContainerStyle={tw`px-5 pt-6 pb-28 gap-3 justify-end flex-grow`}
showsVerticalScrollIndicator={false}
>
<FeedCard style={tw`bg-white dark:bg-stone-900 p-4 gap-3`}>
<View style={tw`flex-row items-center justify-between gap-3`}>
<SansSerifText style={tw`text-xs text-stone-500 dark:text-stone-400 uppercase`}>
Morning brief
</SansSerifText>
<MonospaceText style={tw`text-xs text-teal-700 dark:text-teal-300`}>
08:42
</MonospaceText>
</View>
<SerifText style={tw`text-3xl leading-9`}>
A calm start with two useful windows.
</SerifText>
<SansSerifText style={tw`text-base leading-6 text-stone-600 dark:text-stone-300`}>
Your morning is light until the project sync. Rain holds off until late afternoon, and
your last note suggests starting with the proposal outline.
</SansSerifText>
<View style={tw`flex-row flex-wrap gap-2`}>
<View style={tw`rounded-full bg-teal-50 dark:bg-teal-950 px-3 py-1`}>
<SansSerifText style={tw`text-xs text-teal-700 dark:text-teal-200`}>
90 min focus
</SansSerifText>
</View>
<View style={tw`rounded-full bg-stone-100 dark:bg-stone-800 px-3 py-1`}>
<SansSerifText style={tw`text-xs text-stone-600 dark:text-stone-300`}>
2 reminders
</SansSerifText>
</View>
<View style={tw`rounded-full bg-stone-100 dark:bg-stone-800 px-3 py-1`}>
<SansSerifText style={tw`text-xs text-stone-600 dark:text-stone-300`}>
Low email volume
</SansSerifText>
</View>
</View>
</FeedCard>
<FeedCard style={tw`bg-white dark:bg-stone-900 p-4 gap-4`}>
<View style={tw`flex-row items-baseline justify-between gap-3`}>
<SerifText style={tw`text-2xl`}>Next up</SerifText>
<SansSerifText style={tw`text-xs text-stone-500 dark:text-stone-400`}>
Today
</SansSerifText>
</View>
<View style={tw`gap-3`}>
<View style={tw`flex-row gap-3`}>
<MonospaceText style={tw`w-14 text-xs text-stone-500 dark:text-stone-400`}>
09:30
</MonospaceText>
<View style={tw`flex-1 gap-1`}>
<SansSerifText style={tw`font-semibold`}>Project sync prep</SansSerifText>
<SansSerifText style={tw`text-sm leading-5 text-stone-600 dark:text-stone-300`}>
Three notes from yesterday are ready to skim.
</SansSerifText>
</View>
</View>
<View style={tw`h-px bg-stone-200 dark:bg-stone-800`} />
<View style={tw`flex-row gap-3`}>
<MonospaceText style={tw`w-14 text-xs text-stone-500 dark:text-stone-400`}>
11:00
</MonospaceText>
<View style={tw`flex-1 gap-1`}>
<SansSerifText style={tw`font-semibold`}>Quiet work block</SansSerifText>
<SansSerifText style={tw`text-sm leading-5 text-stone-600 dark:text-stone-300`}>
Best slot for the proposal before the day gets busy.
</SansSerifText>
</View>
</View>
</View>
</FeedCard>
<FeedCard style={tw`bg-white dark:bg-stone-900 p-4 gap-3`}>
<View style={tw`flex-row items-center justify-between gap-3`}>
<SerifText style={tw`text-2xl`}>Personal radar</SerifText>
<MonospaceText style={tw`text-xs text-stone-500 dark:text-stone-400`}>
4 signals
</MonospaceText>
</View>
<View style={tw`gap-2.5`}>
<View style={tw`flex-row gap-2.5`}>
<View style={tw`mt-1.5 size-2 rounded-full bg-teal-500`} />
<SansSerifText
style={tw`flex-1 text-sm leading-5 text-stone-600 dark:text-stone-300`}
>
Package is likely to arrive before 2 PM.
</SansSerifText>
</View>
<View style={tw`flex-row gap-2.5`}>
<View style={tw`mt-1.5 size-2 rounded-full bg-amber-500`} />
<SansSerifText
style={tw`flex-1 text-sm leading-5 text-stone-600 dark:text-stone-300`}
>
Energy prices dip again after midnight.
</SansSerifText>
</View>
<View style={tw`flex-row gap-2.5`}>
<View style={tw`mt-1.5 size-2 rounded-full bg-sky-500`} />
<SansSerifText
style={tw`flex-1 text-sm leading-5 text-stone-600 dark:text-stone-300`}
>
A recipe you saved matches what is in the fridge.
</SansSerifText>
</View>
</View>
</FeedCard>
<Link href="/components" asChild>
<Pressable style={tw`self-start px-1 py-1`}>
<SansSerifText style={tw`text-sm text-teal-700 dark:text-teal-300`}>
View component library
</SansSerifText>
</Pressable>
</Link>
</ScrollView>
<ChatOverlay />
</View>
)
}

View File

@@ -3,11 +3,12 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { Stack } from "expo-router"
import { StatusBar } from "expo-status-bar"
import React from "react"
import { useColorScheme } from "react-native"
import { useColorScheme, View } from "react-native"
import { KeyboardProvider } from "react-native-keyboard-controller"
import tw, { useDeviceContext } from "twrnc"
import { authMiddleware } from "@/api/auth-middleware"
import { ApiClient, ApiClientContext } from "@/api/client"
import { auth, authMiddleware } from "@/auth/auth"
const queryClient = new QueryClient()
const apiClient = new ApiClient({
@@ -22,6 +23,12 @@ export default function RootLayout() {
const headerBg = colorScheme === "dark" ? "#1c1917" : "#f5f5f4"
const headerTint = colorScheme === "dark" ? "#e7e5e4" : "#1c1917"
const { data: session, isPending: isLoadingSession } = auth.useSession()
if (isLoadingSession) {
return null
}
return (
<ContextProvider>
<Stack
@@ -30,26 +37,34 @@ export default function RootLayout() {
contentStyle: { backgroundColor: headerBg },
}}
>
<Stack.Screen
name="components/index"
options={{
headerShown: true,
title: "Components",
headerStyle: { backgroundColor: headerBg },
headerTintColor: headerTint,
headerShadowVisible: false,
}}
/>
<Stack.Screen
name="components/[name]"
options={{
headerShown: true,
title: "",
headerStyle: { backgroundColor: headerBg },
headerTintColor: headerTint,
headerShadowVisible: false,
}}
/>
<Stack.Protected guard={!session}>
<Stack.Screen name="sign-in" />
</Stack.Protected>
<Stack.Protected guard={Boolean(session)}>
<Stack.Screen name="(app)" />
<Stack.Screen
name="components/index"
options={{
headerShown: true,
title: "Components",
headerStyle: { backgroundColor: headerBg },
headerTintColor: headerTint,
headerShadowVisible: false,
}}
/>
<Stack.Screen
name="components/[name]"
options={{
headerShown: true,
title: "",
headerStyle: { backgroundColor: headerBg },
headerTintColor: headerTint,
headerShadowVisible: false,
}}
/>
</Stack.Protected>
</Stack>
<StatusBar style="auto" />
</ContextProvider>
@@ -58,8 +73,10 @@ export default function RootLayout() {
function ContextProvider({ children }: React.PropsWithChildren) {
return (
<QueryClientProvider client={queryClient}>
<ApiClientContext value={apiClient}>{children}</ApiClientContext>
</QueryClientProvider>
<KeyboardProvider>
<QueryClientProvider client={queryClient}>
<ApiClientContext value={apiClient}>{children}</ApiClientContext>
</QueryClientProvider>
</KeyboardProvider>
)
}

View File

@@ -1,43 +0,0 @@
import { BlurView } from "expo-blur"
import { GlassView } from "expo-glass-effect"
import { Link } from "expo-router"
import { Pressable, View, Text, TextInput } from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"
import tw from "twrnc"
import { Button } from "@/components/ui/button"
import { FeedCard } from "@/components/ui/feed-card"
import { MonospaceText } from "@/components/ui/monospace-text"
import { SansSerifText } from "@/components/ui/sans-serif-text"
import { SerifText } from "@/components/ui/serif-text"
export default function HomeScreen() {
return (
<SafeAreaView
style={tw`bg-stone-100 dark:bg-stone-900 flex-1 px-5 pt-6 gap-4 relative dark:text-stone-100`}
>
<FeedCard>
<SerifText style={tw`text-4xl`}>Hello world asdsadsa</SerifText>
<SansSerifText style={tw`text-4xl font-bold`}>Hello world</SansSerifText>
<MonospaceText style={tw`text-4xl`}>asdjsakljdl</MonospaceText>
<Button style={tw`self-start`} label="Test" />
</FeedCard>
<Link href="/components" asChild>
<Pressable>
<SansSerifText style={tw`text-teal-600`}>View component library</SansSerifText>
</Pressable>
</Link>
<View style={tw`absolute bottom-10 left-0 right-0 px-3`}>
<BlurView
style={tw`flex flex-row w-full py-2 pl-4 pr-2 bg-stone-800 border border-stone-700 rounded-full overflow-hidden`}
>
<TextInput
style={tw`text-stone-300 dark:text-stone-200 flex-1`}
placeholder="Message Freya..."
/>
<Button style={tw`size-8 p-0`} leadingIcon={<Button.Icon name="arrow-up" />} />
</BlurView>
</View>
</SafeAreaView>
)
}

View File

@@ -0,0 +1,221 @@
import { mutationOptions, useMutation } from "@tanstack/react-query"
import { useRouter } from "expo-router"
/* eslint-disable react-hooks/immutability */
import { useCallback, useImperativeHandle, useRef } from "react"
import { ActivityIndicator, Alert, View } from "react-native"
import { KeyboardAvoidingView, useKeyboardHandler } from "react-native-keyboard-controller"
import Animated, {
useAnimatedStyle,
useSharedValue,
withDelay,
withSpring,
} from "react-native-reanimated"
import { SafeAreaView, useSafeAreaInsets } from "react-native-safe-area-context"
import tw from "twrnc"
import { auth, signInMutation } from "@/auth/auth"
import { InvalidCredentialsError, BetterAuthError } from "@/auth/error"
import { Button } from "@/components/ui/button"
import { SansSerifText } from "@/components/ui/sans-serif-text"
import { SerifText } from "@/components/ui/serif-text"
import { TextInput } from "@/components/ui/text-input"
export default function SignInPage() {
console.log("sing in page ")
const loginFormRef = useRef<LoginFormContainerRef>(null)
const emailButtonHeight = useRef(0)
return (
<View style={tw`size-full relative`}>
<SafeAreaView
style={tw`flex-1 bg-stone-50 dark:bg-stone-900 justify-center items-start px-6`}
>
<View style={tw`flex-1 justify-center items-start`}>
<SerifText style={tw`text-lg mb-1.5`}>I&apos;m Freya!</SerifText>
<SerifText style={tw`text-lg opacity-70 leading-tight`}>
Before I can help you with your daily routines, please sign in below.
</SerifText>
</View>
<Button
onLayout={({ nativeEvent: { layout } }) => {
emailButtonHeight.current = layout.height
}}
intent="secondary"
style={tw`w-full`}
onPress={() => {
loginFormRef.current?.show({
fromHeight: emailButtonHeight.current,
})
}}
>
<Button.Label>Continue with email</Button.Label>
</Button>
</SafeAreaView>
<LoginFormContainer ref={loginFormRef}>
<LoginForm />
</LoginFormContainer>
</View>
)
}
interface LoginFormContainerRef {
show: ({ fromHeight }: { fromHeight: number }) => void
}
function LoginFormContainer({
ref,
children,
}: React.PropsWithChildren<{ ref?: React.Ref<LoginFormContainerRef> }>) {
console.log("LoginFormContainer")
const safeAreaInsets = useSafeAreaInsets()
const opacity = useSharedValue(0)
const contentOpacity = useSharedValue(0)
const insetX = useSharedValue(0)
const bottom = useSharedValue(0)
const height = useSharedValue(0)
const finalHeight = useRef(0)
const show = useCallback(
({ fromHeight }: { fromHeight: number }) => {
insetX.value = 24
bottom.value = safeAreaInsets.bottom
height.value = fromHeight
opacity.value = 1
insetX.value = withSpring(0)
bottom.value = withSpring(0)
height.value = withSpring(finalHeight.current)
contentOpacity.value = withDelay(100, withSpring(1))
},
[opacity, insetX, bottom, safeAreaInsets.bottom, height, contentOpacity],
)
useImperativeHandle(ref, () => ({ show }))
useKeyboardHandler({
onMove: ({ progress, height, duration }) => {
"worklet"
bottom.value = height
},
})
const animatedStyle = useAnimatedStyle(() => ({
height: opacity.value !== 0 ? height.value : undefined,
opacity: opacity.value,
left: insetX.value,
right: insetX.value,
bottom: bottom.value,
}))
return (
<Animated.View
onLayout={({ nativeEvent: { layout } }) => {
finalHeight.current = layout.height
}}
style={[
tw`absolute overflow-hidden border border-stone-200 dark:border-stone-700 rounded-2xl`,
animatedStyle,
]}
>
<KeyboardAvoidingView behavior="padding">
<SafeAreaView
edges={["bottom"]}
style={tw`px-4 bg-stone-100 dark:bg-stone-800 overflow-hidden`}
>
<Animated.View style={[tw`w-full`, { opacity: contentOpacity }]}>
{children}
</Animated.View>
</SafeAreaView>
</KeyboardAvoidingView>
</Animated.View>
)
}
function LoginForm() {
console.log("LoginForm")
const emailRef = useRef("")
const passwordRef = useRef("")
const router = useRouter()
const { mutate: signIn, isPending: isSigningIn } = useMutation(
mutationOptions({
...signInMutation,
onSuccess: (data) => {
if (data) {
router.replace("/")
} else {
// if no data is returned, nothing was done, so do nothing
}
},
onError: (error) => {
console.log(error)
if (error instanceof InvalidCredentialsError) {
Alert.alert("Failed to sign in", "Incorrect email or password")
} else if (error instanceof BetterAuthError) {
Alert.alert(
"Failed to sign in",
"This is a fault on Freya's end. Please try again later.",
)
} else {
Alert.alert(
"Unable to connect to Freya",
"Please check your internet connection and try again.",
)
}
},
}),
)
const handleSignInButtonPress = () => {
signIn({
email: emailRef.current,
password: passwordRef.current,
})
}
return (
<View style={[tw`w-full py-4`]}>
<View style={tw`flex flex-row w-full`}>
<View>
<View style={tw`h-8 justify-center mr-4`}>
<SansSerifText>Email</SansSerifText>
</View>
<View style={tw`my-1 h-px w-full bg-stone-200 dark:bg-stone-700 rounded-l-full`} />
<View style={tw`h-8 justify-center mr-4`}>
<SansSerifText>Password</SansSerifText>
</View>
</View>
<View style={tw`flex-1`}>
<TextInput
defaultValue=""
autoCapitalize="none"
keyboardType="email-address"
style={tw`w-full h-8 font-medium`}
onChangeText={(text) => {
emailRef.current = text
}}
/>
<View style={tw`my-1 h-px w-full bg-stone-200 dark:bg-stone-700 rounded-r-full`} />
<TextInput
defaultValue=""
secureTextEntry
style={tw`w-full h-8 font-medium`}
onChangeText={(text) => {
passwordRef.current = text
}}
/>
</View>
</View>
<Button
intent="primary"
style={tw`w-full mt-6`}
onPress={handleSignInButtonPress}
enabled={!isSigningIn}
>
{isSigningIn ? <Button.Loading /> : <Button.Label>Sign in</Button.Label>}
</Button>
</View>
)
}

View File

@@ -0,0 +1,57 @@
import { expoClient } from "@better-auth/expo/client"
import { mutationOptions } from "@tanstack/react-query"
import { createAuthClient } from "better-auth/react"
import * as SecureStore from "expo-secure-store"
import type { ApiRequestMiddleware } from "../api/client"
import { BetterAuthError, InvalidCredentialsError } from "./error"
export const auth = createAuthClient({
baseURL: process.env.EXPO_PUBLIC_SERVER_URL,
plugins: [
expoClient({
scheme: "freya",
storagePrefix: "chat.freya",
storage: SecureStore,
}),
],
})
export const authMiddleware: ApiRequestMiddleware = (_url, init) => {
const cookie = auth.getCookie()
const headers = new Headers(init.headers)
if (cookie) {
headers.set("Cookie", cookie)
}
return {
...init,
credentials: "omit",
headers,
}
}
export const signInMutation = mutationOptions({
mutationFn: async ({ email, password }: { email: string; password: string }) => {
if (email && password) {
const result = await auth.signIn.email({
email,
password,
})
if (result.error?.code) {
switch (result.error.code) {
case "INVALID_EMAIL":
throw new InvalidCredentialsError("Invalid email")
case "INVALID_PASSWORD":
throw new InvalidCredentialsError("Invalid password")
case "INVALID_EMAIL_OR_PASSWORD":
throw new InvalidCredentialsError("Invalid email or password")
default:
throw new BetterAuthError(result.error)
}
}
return result
}
return null
},
})

View File

@@ -0,0 +1,27 @@
import type { auth } from "./auth"
export class InvalidCredentialsError extends Error {
constructor(cause: unknown) {
super(`Invalid credentials: ${cause}`)
}
}
export class BetterAuthError extends Error {
// the type is copied from the shape of result.error from authClient.signIn.email
constructor(error: {
code?: string | undefined
message?: string | undefined
status: number
statusText: string
}) {
super(`${error.message ?? "BetterAuthError"}: ${error.status} ${error.statusText}`)
}
}
type BetterAuthErrorTypes = Partial<Record<keyof typeof auth.$ERROR_CODES, string>>
export const AuthErrorCode = {
INVALID_EMAIL: "INVALID_EMAIL",
INVALID_PASSWORD: "INVALID_PASSWORD",
INVALID_EMAIL_OR_PASSWORD: "INVALID_EMAIL_OR_PASSWORD",
} satisfies BetterAuthErrorTypes

View File

@@ -8,25 +8,28 @@ function ButtonShowcase() {
return (
<View style={tw`gap-6`}>
<Section title="Default">
<Button style={tw`self-start`} label="Press me" />
<Button style={tw`self-start`}>
<Button.Label>Press me</Button.Label>
</Button>
</Section>
<Section title="Leading icon">
<Button style={tw`self-start`} label="Add item" leadingIcon={<Button.Icon name="plus" />} />
<Button style={tw`self-start`}>
<Button.Icon name="plus" />
<Button.Label>Add item</Button.Label>
</Button>
</Section>
<Section title="Trailing icon">
<Button
style={tw`self-start`}
label="Next"
trailingIcon={<Button.Icon name="arrow-right" />}
/>
<Button style={tw`self-start`}>
<Button.Label>Next</Button.Label>
<Button.Icon name="arrow-right" />
</Button>
</Section>
<Section title="Both icons">
<Button
style={tw`self-start`}
label="Download"
leadingIcon={<Button.Icon name="download" />}
trailingIcon={<Button.Icon name="chevron-down" />}
/>
<Button style={tw`self-start`}>
<Button.Icon name="download" />
<Button.Label>Download</Button.Label>
<Button.Icon name="chevron-down" />
</Button>
</Section>
</View>
)

View File

@@ -1,51 +1,214 @@
import Feather from "@expo/vector-icons/Feather"
import { type PressableProps, Pressable, type StyleProp, View, type ViewStyle } from "react-native"
import { createContext, useContext } from "react"
import {
type PressableProps,
Pressable,
type TextStyle,
useColorScheme,
ActivityIndicator,
} from "react-native"
import tw from "twrnc"
import { rva, type RvaProps } from "@/lib/rva"
import { SansSerifText } from "./sans-serif-text"
type FeatherIconName = React.ComponentProps<typeof Feather>["name"]
const button = rva(
tw.style("rounded-2xl px-4 py-3 w-fit flex-row items-center justify-center gap-1.5 h-10", {
borderCurve: "continuous",
}),
{
variants: {
intent: {
primary: tw`bg-teal-600`,
secondary: tw`bg-stone-100 dark:bg-stone-800`,
},
pressed: {
true: tw`translate-y-px`,
false: null,
},
enabled: {
true: null,
false: tw`opacity-50`,
},
dark: {
true: null,
false: null,
},
},
defaultVariants: {
intent: "primary",
pressed: false,
enabled: true,
dark: false,
},
compoundVariants: [
// primary variants
{
intent: "primary",
enabled: true,
pressed: false,
style: {
boxShadow:
"inset 0 1px 0 0 #2dd4bf66, inset 0 -1px 0 0 #0f766eb3, 0 2px 4px 0 #0000001a, 0 0 0 1px #0f766e",
},
},
{
intent: "primary",
enabled: true,
pressed: true,
style: tw.style("bg-teal-700", {
boxShadow:
"inset 0 1px 2px 0 #042f2e80, inset 0 0 0 1px #0f766e, inset 0 -1px 0 0 #2dd4bf26",
}),
},
// secondary variants
{
intent: "secondary",
dark: false,
enabled: true,
pressed: false,
style: {
boxShadow: "inset 0 1px 0 0 #fdfdfd, 0 2px 4px 0 #0000001a, 0 0 0 1px #00000029",
},
},
{
intent: "secondary",
dark: false,
enabled: true,
pressed: true,
style: tw.style("bg-stone-200", {
boxShadow:
"inset 0 1px 2px 0 #0000001f, inset 0 0 0 1px #00000012, inset 0 -1px 0 0 #ffffff80",
}),
},
{
intent: "secondary",
dark: true,
enabled: true,
pressed: false,
style: tw.style("bg-stone-800", {
boxShadow:
"inset 0 1px 0 0 #4b4951, inset 0 -1px 0 0 #313036, 0 2px 4px 0 #0000001a, 0 0 0 1px #0d0d0d",
}),
},
{
intent: "secondary",
dark: true,
enabled: true,
pressed: true,
style: tw.style("bg-stone-900", {
boxShadow:
"inset 0 1px 2px 0 #00000080, inset 0 0 0 1px #00000066, inset 0 -1px 0 0 #ffffff0a",
}),
},
],
},
)
const label = rva<TextStyle>(
{},
{
variants: {
intent: {
primary: tw`text-stone-100 dark:text-stone-200 font-medium`,
secondary: tw`text-stone-800 dark:text-stone-200 font-medium`,
},
},
},
)
type ButtonVariants = Omit<RvaProps<typeof button>, "dark" | "pressed">
type ButtonProps = PressableProps & ButtonVariants
interface ButtonContext extends ButtonVariants {}
const Context = createContext<ButtonContext>({})
export function Button({ style, intent = "primary", enabled = true, ...props }: ButtonProps) {
const theme = useColorScheme()
return (
<Context value={{ enabled, intent }}>
<Pressable
style={(state) => [
button({
intent,
enabled,
pressed: state.pressed,
dark: theme === "dark",
}),
typeof style === "function" ? style(state) : style,
]}
{...props}
/>
</Context>
)
}
type ButtonIconProps = {
name: FeatherIconName
}
function ButtonIcon({ name }: ButtonIconProps) {
return <Feather name={name} size={18} color={tw.color("text-stone-100 dark:text-stone-200")} />
const context = useContext(Context)
let color: string
switch (context.intent) {
case "primary":
color = tw.color("text-stone-100 dark:text-stone-200") ?? ""
break
case "secondary":
color = tw.color("text-stone-800 dark:text-stone-200") ?? ""
break
default:
color = ""
break
}
return <Feather name={name} size={18} color={color} />
}
type ButtonProps = Omit<PressableProps, "children" | "style"> & {
label?: string
leadingIcon?: React.ReactNode
style?: StyleProp<ViewStyle>
trailingIcon?: React.ReactNode
}
export function Button({ style, label, leadingIcon, trailingIcon, ...props }: ButtonProps) {
const hasIcons = leadingIcon != null || trailingIcon != null
const textElement = label ? (
<SansSerifText style={tw`text-stone-100 dark:text-stone-200 font-medium`}>
{label}
</SansSerifText>
) : null
type ButtonLabelProps = React.ComponentProps<typeof SansSerifText>
function ButtonLabel({ style, ...props }: ButtonLabelProps) {
const context = useContext(Context)
return (
<Pressable
style={[tw`rounded-full bg-teal-600 px-4 py-3 w-fit flex items-center justify-center`, style]}
<SansSerifText
style={[
label({
intent: context.intent,
}),
style,
]}
{...props}
>
{hasIcons ? (
<View style={tw`flex-row items-center gap-1.5`}>
{leadingIcon}
{textElement}
{trailingIcon}
</View>
) : (
textElement
)}
</Pressable>
/>
)
}
function ButtonLoadingIndicator() {
const context = useContext(Context)
let color: string
switch (context.intent) {
case "primary":
color = tw.color("text-stone-100 dark:text-stone-200") ?? ""
break
case "secondary":
color = tw.color("text-stone-800 dark:text-stone-200") ?? ""
break
default:
color = ""
break
}
return <ActivityIndicator color={color} />
}
Button.Icon = ButtonIcon
Button.Label = ButtonLabel
Button.Loading = ButtonLoadingIndicator

View File

@@ -19,7 +19,9 @@ function FeedCardShowcase() {
<FeedCard style={tw`p-4 gap-2`}>
<SerifText style={tw`text-xl`}>Title</SerifText>
<SansSerifText>Body text inside a feed card.</SansSerifText>
<Button style={tw`self-start mt-2`} label="Action" />
<Button style={tw`self-start mt-2`}>
<Button.Label>Action</Button.Label>
</Button>
</FeedCard>
</Section>
</View>

View File

@@ -0,0 +1,6 @@
import { TextInput as NativeTextInput, type TextInputProps } from "react-native"
import tw from "twrnc"
export function TextInput({ style, ...props }: TextInputProps) {
return <NativeTextInput style={[tw`text-stone-800 dark:text-stone-200`, style]} {...props} />
}

View File

@@ -0,0 +1,284 @@
/* eslint-disable react-hooks/immutability */
import MaskedView from "@react-native-masked-view/masked-view"
import { BlurView } from "expo-blur"
import { LinearGradient } from "expo-linear-gradient"
import { atom, useAtomValue, useSetAtom, useStore } from "jotai"
import { useCallback, useEffect, useImperativeHandle, useMemo, useRef } from "react"
import { useColorScheme, View, StyleSheet, Platform, Dimensions } from "react-native"
import { easeGradient } from "react-native-easing-gradient"
import { useKeyboardHandler } from "react-native-keyboard-controller"
import Animated, { FadeIn, FadeOut, useSharedValue, withSpring } from "react-native-reanimated"
import { useSafeAreaInsets } from "react-native-safe-area-context"
import tw from "twrnc"
import { Button } from "@/components/ui/button"
import { TextInput } from "@/components/ui/text-input"
import { ConversationList } from "./conversation-list"
interface BottomProgressiveBlurRef {
setBlurHeight: (height: number) => void
}
interface ConversationListContainerRef {
showFullChat: () => void
}
const ChatViewMode = {
Hidden: "hidden",
Peek: "peek",
FullChat: "full-chat",
} as const
type ChatViewMode = (typeof ChatViewMode)[keyof typeof ChatViewMode]
const chatInputHeightAtom = atom(0)
const isChatInputFocusedAtom = atom(false)
const chatViewModeAtom = atom<ChatViewMode>(ChatViewMode.Hidden)
export function ChatOverlay() {
const theme = useColorScheme()
const setChatInputHeight = useSetAtom(chatInputHeightAtom)
const setIsChatInputFocused = useSetAtom(isChatInputFocusedAtom)
const setChatViewMode = useSetAtom(chatViewModeAtom)
const store = useStore()
const conversationListContainerRef = useRef<ConversationListContainerRef>(null)
const onTextInputFocus = () => {
setChatViewMode(ChatViewMode.Peek)
}
const onConversationListScroll = () => {
if (store.get(chatViewModeAtom) !== ChatViewMode.FullChat) {
setChatViewMode(ChatViewMode.FullChat)
conversationListContainerRef?.current?.showFullChat()
}
}
return (
<ChatOverlayContainer>
<OverlayBackdrop />
<ConversationListContainer ref={conversationListContainerRef}>
<ConversationList
ListHeaderComponent={ConversationListHeader}
ListFooterComponent={ConversationListFooter}
onScrollBeginDrag={onConversationListScroll}
/>
</ConversationListContainer>
<ChatInputContainer>
<BlurView
onLayout={({ nativeEvent: { layout } }) => {
setChatInputHeight(layout.height)
}}
intensity={35}
tint={theme === "dark" ? "systemThickMaterialDark" : "systemThickMaterialLight"}
style={tw`flex flex-row w-full py-1 pl-4 pr-1 border border-stone-300 dark:border-stone-700 rounded-full overflow-hidden`}
>
<TextInput
onFocus={onTextInputFocus}
onBlur={() => {
setIsChatInputFocused(false)
}}
style={tw`flex-1`}
placeholder="Message Freya..."
/>
<Button style={tw`size-8 p-0`}>
<Button.Icon name="arrow-up" />
</Button>
</BlurView>
</ChatInputContainer>
</ChatOverlayContainer>
)
}
function ChatOverlayContainer({ children }: React.PropsWithChildren) {
const bottom = useSharedValue(0)
useKeyboardHandler({
onMove: (event) => {
"worklet"
bottom.value = event.height
},
})
return (
<Animated.View pointerEvents="box-none" style={[tw`absolute top-0 left-0 right-0`, { bottom }]}>
{children}
</Animated.View>
)
}
function ConversationListContainer({
ref,
children,
}: React.PropsWithChildren<{ ref?: React.Ref<ConversationListContainerRef> }>) {
const chatViewMode = useAtomValue(chatViewModeAtom)
const height = useSharedValue(Dimensions.get("window").height * 0.4)
const { colors, locations } = useMemo(
() =>
easeGradient({
colorStops: {
0: { color: "transparent" },
0.1: { color: "transparent" },
0.3: { color: tw.color("bg-stone-100 dark:bg-stone-950")! },
0.9: { color: tw.color("bg-stone-100 dark:bg-stone-950")! },
1: { color: tw.color("bg-stone-100 dark:bg-stone-950")! },
},
}),
[],
)
const showFullChat = useCallback(() => {
height.value = withSpring(Dimensions.get("window").height + 80)
}, [height])
useImperativeHandle(
ref,
() => ({
showFullChat,
}),
[showFullChat],
)
return (
<View pointerEvents="box-none" style={tw.style("absolute top-0 left-0 right-0 bottom-0")}>
<MaskedView
pointerEvents="box-none"
maskElement={
<Animated.View style={[tw`absolute bottom-0 right-0 left-0`, { height }]}>
<LinearGradient
locations={locations as any}
colors={colors as any}
style={tw`size-full`}
/>
</Animated.View>
}
style={tw`size-full`}
>
<View
style={tw.style("size-full", chatViewMode === ChatViewMode.Hidden ? "opacity-0" : "")}
>
{children}
</View>
</MaskedView>
</View>
)
}
function OverlayBackdrop() {
const chatViewMode = useAtomValue(chatViewModeAtom)
const bottomProgressiveBlurRef = useRef<BottomProgressiveBlurRef>(null)
useEffect(() => {
if (chatViewMode === ChatViewMode.Peek) {
bottomProgressiveBlurRef?.current?.setBlurHeight(Dimensions.get("window").height * 0.75)
}
}, [chatViewMode])
if (chatViewMode === ChatViewMode.FullChat) {
return <BlurBackground />
}
return <BottomProgressiveBlur ref={bottomProgressiveBlurRef} />
}
function BottomProgressiveBlur({ ref }: { ref?: React.Ref<BottomProgressiveBlurRef> }) {
const progressiveBlurHeight = useSharedValue(192)
const colorScheme = useColorScheme()
const { colors, locations } = useMemo(
() =>
easeGradient({
colorStops: {
0: { color: "transparent" },
0.7: { color: tw.color("bg-stone-100 dark:bg-stone-950")! },
1: { color: tw.color("bg-stone-100 dark:bg-stone-950")! },
},
}),
[],
)
const setBlurHeight = useCallback(
(height: number) => {
progressiveBlurHeight.value = withSpring(height)
},
[progressiveBlurHeight],
)
useImperativeHandle(ref, () => ({ setBlurHeight }), [setBlurHeight])
return (
<Animated.View
entering={FadeIn}
exiting={FadeOut}
style={[tw`absolute bottom-0 left-0 right-0`, { height: progressiveBlurHeight }]}
>
<MaskedView
maskElement={
<LinearGradient
locations={locations as any}
colors={colors as any}
style={tw`absolute top-0 bottom-0 left-0 right-0`}
/>
}
style={[StyleSheet.absoluteFill, tw`z-[1]`]}
>
<BlurView
intensity={65}
tint={Platform.select({
ios:
colorScheme === "dark"
? "systemUltraThinMaterialDark"
: "systemUltraThinMaterialLight",
android: "systemMaterialDark",
})}
style={StyleSheet.absoluteFill}
/>
</MaskedView>
</Animated.View>
)
}
function BlurBackground() {
const colorScheme = useColorScheme()
return (
<Animated.View entering={FadeIn} exiting={FadeOut} style={StyleSheet.absoluteFill}>
<BlurView
intensity={65}
tint={Platform.select({
ios:
colorScheme === "dark" ? "systemUltraThinMaterialDark" : "systemUltraThinMaterialLight",
android: "systemMaterialDark",
})}
style={StyleSheet.absoluteFill}
/>
</Animated.View>
)
}
function ChatInputContainer({ children }: React.PropsWithChildren) {
const keyboardHeight = useSharedValue(0)
const insets = useSafeAreaInsets()
useKeyboardHandler({
onMove: (event) => {
"worklet"
keyboardHeight.value = Math.max(event.height - insets.bottom + 8, 0)
},
})
return <View style={tw`absolute bottom-0 left-0 right-0 px-4 pb-10`}>{children}</View>
}
function ConversationListHeader() {
const safeAreaInsets = useSafeAreaInsets()
return <View style={{ height: safeAreaInsets.top }} />
}
function ConversationListFooter() {
const chatInputHeight = useAtomValue(chatInputHeightAtom)
const safeAreaInsets = useSafeAreaInsets()
return <View style={{ height: chatInputHeight + 24 + safeAreaInsets.bottom }} />
}

View File

@@ -0,0 +1,183 @@
import { AssistantMessagePayload, UserMessagePayload } from "@freya/core"
import { FlashList } from "@shopify/flash-list"
import { useQuery } from "@tanstack/react-query"
import { View, ViewStyle } from "react-native"
import tw from "twrnc"
import { SansSerifText } from "@/components/ui/sans-serif-text"
import { ConversationEntry } from "./conversations"
import { useListConversationEntriesQuery, useDefaultConversationQuery } from "./queries"
type ConversationListProps = Omit<
React.ComponentProps<typeof FlashList>,
"data" | "keyExtractor" | "renderItem" | "maintainVisibleContentPosition"
>
type PositionInGroup = "single" | "first" | "in-between" | "last"
const messageBubbleRadius = 18
const groupedMessageBubbleRadius = 6
export function ConversationList({
ListFooterComponent,
ListHeaderComponent,
onScrollBeginDrag,
}: ConversationListProps) {
const { data: conversation } = useQuery(useDefaultConversationQuery())
const { data: entries } = useQuery(useListConversationEntriesQuery(conversation?.id))
const conversationEntries = entries ?? []
return (
<FlashList
style={tw`size-full`}
maintainVisibleContentPosition={{ startRenderingFromBottom: true }}
data={conversationEntries}
keyExtractor={(item) => item.id}
renderItem={({ item, index }) => {
const previousEntryIsSameKind = conversationEntries[index - 1]?.kind === item.kind
const nextEntryIsSameKind = conversationEntries[index + 1]?.kind === item.kind
let position: PositionInGroup
if (!previousEntryIsSameKind && !nextEntryIsSameKind) {
position = "single"
} else if (!previousEntryIsSameKind) {
position = "first"
} else if (!nextEntryIsSameKind) {
position = "last"
} else {
position = "in-between"
}
return <MessageBubble entry={item} position={position} />
}}
onScrollBeginDrag={onScrollBeginDrag}
ListHeaderComponent={ListHeaderComponent}
ListFooterComponent={ListFooterComponent}
/>
)
}
function MessageBubble({
entry,
position,
}: {
entry: typeof ConversationEntry.infer
position: PositionInGroup
}) {
if (entry.kind === "user_message") {
const payload = UserMessagePayload.assert(entry.payload)
return <UserMessageBubble payload={payload} position={position} />
}
if (entry.kind === "assistant_message") {
const payload = AssistantMessagePayload.assert(entry.payload)
return <AssistantMessageBubble payload={payload} position={position} />
}
return null
}
function UserMessageBubble({
payload,
position,
}: {
payload: UserMessagePayload
position: PositionInGroup
}) {
const content = payload.parts.reduce((final, part) => {
if (part.type === "text") {
return final + part.text
}
return final
}, "")
let corners: ViewStyle
switch (position) {
case "single":
case "first":
corners = {
borderRadius: messageBubbleRadius,
borderBottomRightRadius: groupedMessageBubbleRadius,
}
break
case "in-between":
corners = {
borderRadius: messageBubbleRadius,
borderTopRightRadius: groupedMessageBubbleRadius,
borderBottomRightRadius: groupedMessageBubbleRadius,
}
break
case "last":
corners = {
borderRadius: messageBubbleRadius,
borderTopRightRadius: groupedMessageBubbleRadius,
}
break
}
return (
<View style={tw`w-full flex-row justify-end mb-4 pr-4`}>
<View
style={tw.style("bg-teal-600 px-3 py-2 overflow-hidden max-w-56", corners, {
borderCurve: "circular",
})}
>
<SansSerifText style={tw`text-stone-100`}>{content}</SansSerifText>
</View>
</View>
)
}
function AssistantMessageBubble({
payload,
position,
}: {
payload: AssistantMessagePayload
position: PositionInGroup
}) {
const content = payload.parts.reduce((final, part) => {
if (part.type === "text") {
return final + part.text
}
return final
}, "")
let corners: ViewStyle
switch (position) {
case "single":
case "first":
corners = {
borderRadius: messageBubbleRadius,
borderBottomLeftRadius: groupedMessageBubbleRadius,
}
break
case "in-between":
corners = {
borderRadius: messageBubbleRadius,
borderTopLeftRadius: groupedMessageBubbleRadius,
borderBottomLeftRadius: groupedMessageBubbleRadius,
}
break
case "last":
corners = {
borderRadius: messageBubbleRadius,
borderTopLeftRadius: groupedMessageBubbleRadius,
}
break
}
return (
<View style={tw`w-full flex-row justify-start mb-4 pl-4`}>
<View
style={tw.style(
"bg-stone-200 dark:bg-stone-800 border border-stone-300 dark:border-stone-700 px-3 py-2 overflow-hidden max-w-56",
corners,
{
borderCurve: "circular",
},
)}
>
<SansSerifText style={tw`text-stone-950 dark:text-stone-100`}>{content}</SansSerifText>
</View>
</View>
)
}

View File

@@ -1,23 +0,0 @@
import { FlashList } from "@shopify/flash-list";
import { useQuery } from "@tanstack/react-query";
import {
useListConversationEntriesQuery,
useDefaultConversationQuery,
useListConversationsQuery,
} from "./queries";
export function ConversationView() {
const { data: conversation } = useQuery(useDefaultConversationQuery());
const { data: entries } = useQuery(
useListConversationEntriesQuery(conversation?.id),
);
return (
<FlashList
data={entries ?? []}
keyExtractor={(item) => item.id}
renderItem={({ item }) => <div key={item.id}>{item.kind}</div>}
/>
);
}

View File

@@ -5,6 +5,12 @@ import {
} from "@freya/core"
import { type } from "arktype"
export const Conversation = type({
id: "string.uuid",
createdAt: "string.date.iso",
updatedAt: "string.date.iso",
})
export const ConversationEntry = type({
id: "string.uuid",
sequence: "number",

View File

@@ -3,9 +3,13 @@ import { type } from "arktype"
import { useApiClient } from "@/api/client"
import { ConversationEntry } from "./conversations"
import { Conversation, ConversationEntry } from "./conversations"
const ConversationQueryResponse = type({
const ListConversationsResponse = type({
conversations: Conversation.array(),
})
const ConversationEntriesResponse = type({
entries: ConversationEntry.array(),
})
@@ -16,14 +20,16 @@ export function useListConversationsQuery() {
queryFn: async () =>
api
.request("/conversations", { method: "GET" })
.then(([, json]) => ConversationQueryResponse.assert(json)),
.then(([, json]) => ListConversationsResponse.assert(json)),
})
}
export function useDefaultConversationQuery() {
return queryOptions({
...useListConversationsQuery(),
select: (data) => (data.entries.length === 0 ? null : data.entries[0]),
select: (data) => {
return data.conversations.length === 0 ? null : data.conversations[0]
},
})
}
@@ -35,7 +41,7 @@ export function useListConversationEntriesQuery(id?: string) {
? async () =>
api
.request(`/conversations/${id}/entries`, { method: "GET" })
.then(([, json]) => ConversationQueryResponse.assert(json).entries)
.then(([, json]) => ConversationEntriesResponse.assert(json).entries)
: skipToken,
})
}

View File

@@ -15,15 +15,29 @@ export const catalog = defineCatalog(schema, {
},
Button: {
props: z.object({
label: z.string(),
leadingIcon: z.string().nullable(),
trailingIcon: z.string().nullable(),
intent: z.enum(["primary", "secondary"]).nullable(),
}),
events: ["press"],
slots: [],
slots: ["default"],
description:
"Pressable button with a label and optional Feather icons. Icon values are Feather icon names (e.g. 'plus', 'arrow-right'). Bind on.press to trigger an action.",
example: { label: "Add item", leadingIcon: "plus", trailingIcon: null },
"Pressable button. Add ButtonLabel and optional ButtonIcon children in the default slot. Bind on.press to trigger an action.",
example: { intent: "primary" },
},
ButtonIcon: {
props: z.object({
name: z.string(),
}),
slots: [],
description: "Feather icon for use inside a Button.",
example: { name: "plus" },
},
ButtonLabel: {
props: z.object({
text: z.string(),
}),
slots: [],
description: "Text label for use inside a Button.",
example: { text: "Add item" },
},
FeedCard: {
props: z.object({

View File

@@ -17,20 +17,13 @@ export const { registry } = defineRegistry(catalog, {
View: ({ props, children }) => (
<View style={props.style ? tw`${props.style}` : undefined}>{children}</View>
),
Button: ({ props, emit }) => (
<Button
label={props.label}
leadingIcon={
props.leadingIcon ? <Button.Icon name={props.leadingIcon as ButtonIconName} /> : undefined
}
trailingIcon={
props.trailingIcon ? (
<Button.Icon name={props.trailingIcon as ButtonIconName} />
) : undefined
}
onPress={() => emit("press")}
/>
Button: ({ props, children, emit }) => (
<Button intent={props.intent ?? undefined} onPress={() => emit("press")}>
{children}
</Button>
),
ButtonIcon: ({ props }) => <Button.Icon name={props.name as ButtonIconName} />,
ButtonLabel: ({ props }) => <Button.Label>{props.text}</Button.Label>,
FeedCard: ({ props, children }) => (
<FeedCard style={props.style ? tw`${props.style}` : undefined}>{children}</FeedCard>
),

View File

@@ -0,0 +1,215 @@
import type { StyleProp, ViewStyle } from "react-native"
type RvaNoInfer<TValue> = [TValue][TValue extends unknown ? 0 : never]
type VariantValue = string | number | boolean | null | undefined
type VariantOptionKey<TOptions> = Extract<keyof TOptions, string>
type BooleanVariantInput<TOptions> =
Extract<VariantOptionKey<TOptions>, "true" | "false"> extends never ? never : boolean
type StringVariantInput<TOptions> = Exclude<VariantOptionKey<TOptions>, "true" | "false">
type VariantInput<TOptions> =
| StringVariantInput<TOptions>
| BooleanVariantInput<TOptions>
| null
| undefined
type CompoundCondition<TVariants extends RvaVariants<unknown>> = {
name: keyof TVariants
value: string
}
type NormalizedCompoundVariant<TStyle, TVariants extends RvaVariants<TStyle>> = {
conditions: CompoundCondition<TVariants>[]
style: StyleProp<TStyle>
}
export type RvaVariants<TStyle = unknown> = {
readonly [name: string]: {
readonly [value: string]: StyleProp<TStyle>
}
}
export type RvaVariantProps<TVariants extends RvaVariants<unknown>> = {
readonly [TName in keyof TVariants]?: VariantInput<TVariants[TName]>
}
type MutableRvaVariantProps<TVariants extends RvaVariants<unknown>> = {
-readonly [TName in keyof TVariants]?: VariantInput<TVariants[TName]>
}
export type RvaCompoundVariant<
TStyle,
TVariants extends RvaVariants<TStyle>,
> = RvaVariantProps<TVariants> & {
readonly style: StyleProp<TStyle>
}
export type RvaConfig<TStyle, TVariants extends RvaVariants<TStyle>> = {
readonly variants?: TVariants
readonly defaultVariants?: RvaVariantProps<TVariants>
readonly compoundVariants?: readonly RvaCompoundVariant<TStyle, TVariants>[]
}
export type RvaResolver<TStyle, TVariants extends RvaVariants<TStyle>> = (
props?: RvaVariantProps<TVariants>,
) => StyleProp<TStyle>
export type RvaProps<TResolver> = TResolver extends (props?: infer TProps) => unknown
? NonNullable<TProps>
: never
export function rva<TStyle = ViewStyle>(): <
const TVariants extends RvaVariants<TStyle> = RvaVariants<TStyle>,
>(
base: StyleProp<RvaNoInfer<TStyle>>,
config?: RvaConfig<RvaNoInfer<TStyle>, TVariants>,
) => RvaResolver<TStyle, TVariants>
export function rva<
TStyle = ViewStyle,
const TVariants extends RvaVariants<TStyle> = RvaVariants<TStyle>,
>(
base: StyleProp<RvaNoInfer<TStyle>>,
config?: RvaConfig<RvaNoInfer<TStyle>, TVariants>,
): RvaResolver<TStyle, TVariants>
export function rva<
TStyle = ViewStyle,
const TVariants extends RvaVariants<TStyle> = RvaVariants<TStyle>,
>(
base?: StyleProp<TStyle>,
config?: RvaConfig<TStyle, TVariants>,
):
| RvaResolver<TStyle, TVariants>
| (<const TTypedVariants extends RvaVariants<TStyle> = RvaVariants<TStyle>>(
base: StyleProp<TStyle>,
config?: RvaConfig<TStyle, TTypedVariants>,
) => RvaResolver<TStyle, TTypedVariants>) {
if (base === undefined && config === undefined) {
return function createTypedRva<
const TTypedVariants extends RvaVariants<TStyle> = RvaVariants<TStyle>,
>(typedBase: StyleProp<TStyle>, typedConfig: RvaConfig<TStyle, TTypedVariants> = {}) {
return createRva(typedBase, typedConfig)
}
}
return createRva(base, config ?? {})
}
function createRva<TStyle, const TVariants extends RvaVariants<TStyle> = RvaVariants<TStyle>>(
base: StyleProp<TStyle>,
config: RvaConfig<TStyle, TVariants>,
): RvaResolver<TStyle, TVariants> {
const compoundVariants = normalizeCompoundVariants(config.compoundVariants)
return function resolveRva(props: RvaVariantProps<TVariants> = {}) {
const merged = mergeVariantProps(config.defaultVariants, props)
const styles: StyleProp<TStyle>[] = [base]
const variants = config.variants
if (variants !== undefined) {
for (const name in variants) {
const value = normalizeVariantValue(merged[name])
if (value === undefined) {
continue
}
const style = variants[name]?.[value]
if (style !== undefined) {
styles.push(style)
}
}
}
for (const compound of compoundVariants) {
if (compoundMatches(compound, merged)) {
styles.push(compound.style)
}
}
return styles
}
}
function mergeVariantProps<TVariants extends RvaVariants<unknown>>(
defaultVariants: RvaVariantProps<TVariants> | undefined,
props: RvaVariantProps<TVariants>,
): RvaVariantProps<TVariants> {
const merged: MutableRvaVariantProps<TVariants> = {}
if (defaultVariants !== undefined) {
for (const name of Object.keys(defaultVariants) as (keyof TVariants)[]) {
const value = defaultVariants[name]
if (value !== undefined) {
merged[name] = value
}
}
}
for (const name of Object.keys(props) as (keyof TVariants)[]) {
const value = props[name]
if (value !== undefined) {
merged[name] = value
}
}
return merged
}
function normalizeCompoundVariants<TStyle, TVariants extends RvaVariants<TStyle>>(
compoundVariants: readonly RvaCompoundVariant<TStyle, TVariants>[] | undefined,
) {
const normalized: NormalizedCompoundVariant<TStyle, TVariants>[] = []
if (compoundVariants === undefined) {
return normalized
}
for (const compound of compoundVariants) {
const conditions: CompoundCondition<TVariants>[] = []
for (const name in compound) {
if (name === "style") {
continue
}
const variantName = name as keyof TVariants
const value = normalizeVariantValue(compound[variantName])
if (value !== undefined) {
conditions.push({ name: variantName, value })
}
}
normalized.push({ conditions, style: compound.style })
}
return normalized
}
function compoundMatches<TStyle, TVariants extends RvaVariants<TStyle>>(
compound: NormalizedCompoundVariant<TStyle, TVariants>,
props: RvaVariantProps<TVariants>,
) {
for (const condition of compound.conditions) {
if (normalizeVariantValue(props[condition.name]) !== condition.value) {
return false
}
}
return true
}
function normalizeVariantValue(value: VariantValue) {
if (value === null || value === undefined) {
return undefined
}
if (value === true) {
return "true"
}
if (value === false) {
return "false"
}
return String(value)
}