|
| 1 | +import type { EnvironmentId, GranolaNoteSummary, ThreadId } from "@t3tools/contracts"; |
| 2 | +import { useAtomValue } from "@effect/atom-react"; |
| 3 | +import { granolaNoteContextRecord } from "@t3tools/client-runtime/state/granola"; |
| 4 | +import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; |
| 5 | +import { formatComposerContextReference } from "@t3tools/shared/composerContextReferences"; |
| 6 | +import * as Cause from "effect/Cause"; |
| 7 | +import * as Option from "effect/Option"; |
| 8 | +import { AsyncResult } from "effect/reactivity"; |
| 9 | +import { useState, type ReactNode } from "react"; |
| 10 | +import { ActivityIndicator, Alert, FlatList, Pressable, View } from "react-native"; |
| 11 | +import { useSafeAreaInsets } from "react-native-safe-area-context"; |
| 12 | + |
| 13 | +import { useEnvironmentServerConfig } from "../state/entities"; |
| 14 | +import { granolaEnvironment } from "../state/granola"; |
| 15 | +import { useDebouncedValue } from "../state/queries"; |
| 16 | +import { useEnvironmentQuery } from "../state/query"; |
| 17 | +import { useAtomCommand } from "../state/use-atom-command"; |
| 18 | +import { |
| 19 | + captureComposerDraftInsertion, |
| 20 | + insertComposerDraftContext, |
| 21 | + type ComposerDraftInsertion, |
| 22 | +} from "../state/use-composer-drafts"; |
| 23 | +import { AppText as Text, AppTextInput } from "./AppText"; |
| 24 | +import { PickerSheet } from "./PickerSheet"; |
| 25 | + |
| 26 | +/** The server filters a cached list of recent meetings, so typing can settle quickly. */ |
| 27 | +const SEARCH_DEBOUNCE_MS = 250; |
| 28 | + |
| 29 | +const MEETING_DATE_FORMATTER = new Intl.DateTimeFormat(undefined, { |
| 30 | + month: "short", |
| 31 | + day: "numeric", |
| 32 | + hour: "numeric", |
| 33 | + minute: "2-digit", |
| 34 | +}); |
| 35 | + |
| 36 | +/** A note's meeting date and participants, as the secondary line under its title. */ |
| 37 | +export function granolaNoteDetail(note: { |
| 38 | + readonly meetingAt: string | null; |
| 39 | + /** Names from a note summary, or the joined names an attached record keeps. */ |
| 40 | + readonly participants: string | ReadonlyArray<string>; |
| 41 | +}): string { |
| 42 | + const meetingAt = note.meetingAt ? new Date(note.meetingAt) : null; |
| 43 | + return [ |
| 44 | + meetingAt && !Number.isNaN(meetingAt.getTime()) |
| 45 | + ? MEETING_DATE_FORMATTER.format(meetingAt) |
| 46 | + : null, |
| 47 | + (typeof note.participants === "string" |
| 48 | + ? note.participants |
| 49 | + : note.participants.join(", ") |
| 50 | + ).trim() || null, |
| 51 | + ] |
| 52 | + .filter((part) => part !== null) |
| 53 | + .join(" · "); |
| 54 | +} |
| 55 | + |
| 56 | +/** Granola's failures carry a reason; a rate limit deserves a clearer hint than its detail. */ |
| 57 | +function granolaErrorMessage(error: unknown, fallback: string): string { |
| 58 | + if (typeof error === "object" && error !== null && "reason" in error) { |
| 59 | + if (error.reason === "rate-limited") return "Granola is busy. Try again shortly."; |
| 60 | + if (error.reason === "not-connected" || error.reason === "revoked") { |
| 61 | + return "Granola is not connected. Connect it from Settings > Integrations on desktop or web."; |
| 62 | + } |
| 63 | + } |
| 64 | + return error instanceof Error && error.message.trim() ? error.message : fallback; |
| 65 | +} |
| 66 | + |
| 67 | +/** Attach inserts the note into a composer draft; link links it to the thread's tab group. */ |
| 68 | +export type GranolaNotePickerTarget = |
| 69 | + | { readonly mode?: "attach"; readonly environmentId: EnvironmentId; readonly draftKey: string } |
| 70 | + | { readonly mode: "link"; readonly environmentId: EnvironmentId; readonly threadId: ThreadId }; |
| 71 | + |
| 72 | +type OpenedGranolaNotePicker = |
| 73 | + | { |
| 74 | + readonly mode: "attach"; |
| 75 | + readonly environmentId: EnvironmentId; |
| 76 | + readonly draftKey: string; |
| 77 | + readonly insertion: ComposerDraftInsertion; |
| 78 | + } |
| 79 | + | { readonly mode: "link"; readonly environmentId: EnvironmentId; readonly threadId: ThreadId }; |
| 80 | + |
| 81 | +/** |
| 82 | + * A Granola note picker. The owner renders `sheet` somewhere that outlives composer focus: |
| 83 | + * opening the sheet blurs the editor, which can unmount a focus-dependent toolbar. |
| 84 | + */ |
| 85 | +export function useGranolaNotePicker(target: GranolaNotePickerTarget | null): { |
| 86 | + readonly open: (() => void) | undefined; |
| 87 | + readonly sheet: ReactNode; |
| 88 | +} { |
| 89 | + const [opened, setOpened] = useState<OpenedGranolaNotePicker | null>(null); |
| 90 | + const serverConfig = useEnvironmentServerConfig(target?.environmentId ?? null); |
| 91 | + const enabled = serverConfig?.settings.enableGranolaIntegration === true; |
| 92 | + const openedServerConfig = useEnvironmentServerConfig(opened?.environmentId ?? null); |
| 93 | + return { |
| 94 | + open: |
| 95 | + target && enabled |
| 96 | + ? () => |
| 97 | + setOpened( |
| 98 | + target.mode === "link" |
| 99 | + ? target |
| 100 | + : { |
| 101 | + ...target, |
| 102 | + mode: "attach", |
| 103 | + insertion: captureComposerDraftInsertion(target.draftKey), |
| 104 | + }, |
| 105 | + ) |
| 106 | + : undefined, |
| 107 | + sheet: |
| 108 | + opened && openedServerConfig?.settings.enableGranolaIntegration ? ( |
| 109 | + <GranolaNotePickerSheet {...opened} onClose={() => setOpened(null)} /> |
| 110 | + ) : null, |
| 111 | + }; |
| 112 | +} |
| 113 | + |
| 114 | +/** |
| 115 | + * Attaches a Granola note at the caret the composer had when the sheet opened, or links it to the |
| 116 | + * thread's tab group. Mobile has no Granola settings, so an unconnected environment points at |
| 117 | + * desktop or web. |
| 118 | + */ |
| 119 | +function GranolaNotePickerSheet(props: OpenedGranolaNotePicker & { readonly onClose: () => void }) { |
| 120 | + const connection = useEnvironmentQuery( |
| 121 | + granolaEnvironment.connection({ environmentId: props.environmentId, input: {} }), |
| 122 | + ); |
| 123 | + const phase = connection.data?.phase; |
| 124 | + return ( |
| 125 | + <PickerSheet |
| 126 | + title={props.mode === "link" ? "Link Granola note" : "Granola note"} |
| 127 | + onClose={props.onClose} |
| 128 | + > |
| 129 | + {phase === "connected" ? ( |
| 130 | + <GranolaNoteSearch {...props} /> |
| 131 | + ) : ( |
| 132 | + <View className="flex-1 items-center justify-center p-6"> |
| 133 | + {phase === undefined && !connection.error ? ( |
| 134 | + <ActivityIndicator /> |
| 135 | + ) : ( |
| 136 | + <Text className="text-center text-foreground-muted"> |
| 137 | + {connection.error ?? |
| 138 | + "Granola is not connected on this environment. Connect it from Settings > Integrations on desktop or web."} |
| 139 | + </Text> |
| 140 | + )} |
| 141 | + </View> |
| 142 | + )} |
| 143 | + </PickerSheet> |
| 144 | + ); |
| 145 | +} |
| 146 | + |
| 147 | +function GranolaNoteSearch(props: OpenedGranolaNotePicker & { readonly onClose: () => void }) { |
| 148 | + const [query, setQuery] = useState(""); |
| 149 | + const trimmed = query.trim(); |
| 150 | + const settled = useDebouncedValue(trimmed, SEARCH_DEBOUNCE_MS); |
| 151 | + const getNote = useAtomCommand(granolaEnvironment.getNote, { |
| 152 | + label: "granola note fetch", |
| 153 | + reportFailure: false, |
| 154 | + }); |
| 155 | + const linkThread = useAtomCommand(granolaEnvironment.linkThread, { |
| 156 | + label: "granola thread link", |
| 157 | + reportFailure: false, |
| 158 | + }); |
| 159 | + const [attaching, setAttaching] = useState<string | null>(null); |
| 160 | + |
| 161 | + const link = async (threadId: ThreadId, note: GranolaNoteSummary) => { |
| 162 | + const result = await linkThread({ |
| 163 | + environmentId: props.environmentId, |
| 164 | + input: { threadId, noteId: note.id }, |
| 165 | + }); |
| 166 | + if (result._tag === "Failure") { |
| 167 | + Alert.alert( |
| 168 | + "Could not link Granola note", |
| 169 | + granolaErrorMessage(squashAtomCommandFailure(result), "Try again."), |
| 170 | + ); |
| 171 | + return; |
| 172 | + } |
| 173 | + props.onClose(); |
| 174 | + }; |
| 175 | + |
| 176 | + const attach = async (note: GranolaNoteSummary) => { |
| 177 | + if (attaching) return; |
| 178 | + setAttaching(note.id); |
| 179 | + try { |
| 180 | + if (props.mode === "link") { |
| 181 | + await link(props.threadId, note); |
| 182 | + return; |
| 183 | + } |
| 184 | + const fetched = await getNote({ |
| 185 | + environmentId: props.environmentId, |
| 186 | + input: { id: note.id }, |
| 187 | + }); |
| 188 | + if (fetched._tag === "Failure") { |
| 189 | + Alert.alert( |
| 190 | + "Could not attach Granola note", |
| 191 | + granolaErrorMessage(squashAtomCommandFailure(fetched), "Try again."), |
| 192 | + ); |
| 193 | + return; |
| 194 | + } |
| 195 | + const record = granolaNoteContextRecord(fetched.value); |
| 196 | + if ( |
| 197 | + !insertComposerDraftContext( |
| 198 | + props.draftKey, |
| 199 | + { |
| 200 | + text: formatComposerContextReference(record), |
| 201 | + context: { version: 1, records: [record] }, |
| 202 | + }, |
| 203 | + props.insertion, |
| 204 | + ) |
| 205 | + ) { |
| 206 | + Alert.alert("Too many context items", "Remove some context from the draft and try again."); |
| 207 | + return; |
| 208 | + } |
| 209 | + props.onClose(); |
| 210 | + } finally { |
| 211 | + setAttaching(null); |
| 212 | + } |
| 213 | + }; |
| 214 | + |
| 215 | + return ( |
| 216 | + <View className="flex-1"> |
| 217 | + <View className="px-4 pb-3"> |
| 218 | + <AppTextInput |
| 219 | + accessibilityLabel="Search Granola notes" |
| 220 | + autoFocus |
| 221 | + autoCapitalize="none" |
| 222 | + autoCorrect={false} |
| 223 | + clearButtonMode="while-editing" |
| 224 | + placeholder="Search meetings or paste a Granola link" |
| 225 | + returnKeyType="search" |
| 226 | + value={query} |
| 227 | + onChangeText={setQuery} |
| 228 | + /> |
| 229 | + </View> |
| 230 | + <GranolaNoteResults |
| 231 | + environmentId={props.environmentId} |
| 232 | + query={settled} |
| 233 | + pendingInput={settled !== trimmed} |
| 234 | + attaching={attaching} |
| 235 | + onPick={(note) => void attach(note)} |
| 236 | + /> |
| 237 | + </View> |
| 238 | + ); |
| 239 | +} |
| 240 | + |
| 241 | +/** An empty query lists the last 30 days of meetings; text filters them by title or people. */ |
| 242 | +function GranolaNoteResults(props: { |
| 243 | + readonly environmentId: EnvironmentId; |
| 244 | + readonly query: string; |
| 245 | + readonly pendingInput: boolean; |
| 246 | + readonly attaching: string | null; |
| 247 | + readonly onPick: (note: GranolaNoteSummary) => void; |
| 248 | +}) { |
| 249 | + const insets = useSafeAreaInsets(); |
| 250 | + const result = useAtomValue( |
| 251 | + granolaEnvironment.notes({ |
| 252 | + environmentId: props.environmentId, |
| 253 | + input: { query: props.query }, |
| 254 | + }), |
| 255 | + ); |
| 256 | + const notes = Option.getOrNull(AsyncResult.value(result))?.notes ?? []; |
| 257 | + const pending = props.pendingInput || result.waiting; |
| 258 | + const error = |
| 259 | + result._tag === "Failure" |
| 260 | + ? granolaErrorMessage(Cause.squash(result.cause), "Could not search Granola.") |
| 261 | + : null; |
| 262 | + return ( |
| 263 | + <FlatList |
| 264 | + data={notes} |
| 265 | + keyExtractor={(note) => note.id} |
| 266 | + keyboardShouldPersistTaps="handled" |
| 267 | + contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 16) }} |
| 268 | + ListEmptyComponent={ |
| 269 | + <View className="items-center p-6"> |
| 270 | + {pending ? ( |
| 271 | + <ActivityIndicator /> |
| 272 | + ) : ( |
| 273 | + <Text |
| 274 | + selectable={error !== null} |
| 275 | + className={ |
| 276 | + error ? "text-center text-danger-foreground" : "text-center text-foreground-muted" |
| 277 | + } |
| 278 | + > |
| 279 | + {error ?? |
| 280 | + (props.query ? "No matching meetings." : "No meetings in the last 30 days.")} |
| 281 | + </Text> |
| 282 | + )} |
| 283 | + </View> |
| 284 | + } |
| 285 | + renderItem={({ item }) => { |
| 286 | + const detail = granolaNoteDetail(item); |
| 287 | + return ( |
| 288 | + <Pressable |
| 289 | + accessibilityRole="button" |
| 290 | + accessibilityLabel={item.title} |
| 291 | + disabled={props.attaching !== null} |
| 292 | + onPress={() => props.onPick(item)} |
| 293 | + className="flex-row items-center gap-3 px-4 py-3 active:bg-subtle disabled:opacity-60" |
| 294 | + > |
| 295 | + <View className="min-w-0 flex-1 gap-0.5"> |
| 296 | + <Text className="text-base font-t3-semibold text-foreground" numberOfLines={2}> |
| 297 | + {item.title} |
| 298 | + </Text> |
| 299 | + {detail ? ( |
| 300 | + <Text className="text-sm text-foreground-muted" numberOfLines={1}> |
| 301 | + {detail} |
| 302 | + </Text> |
| 303 | + ) : null} |
| 304 | + </View> |
| 305 | + {props.attaching === item.id ? <ActivityIndicator /> : null} |
| 306 | + </Pressable> |
| 307 | + ); |
| 308 | + }} |
| 309 | + /> |
| 310 | + ); |
| 311 | +} |
0 commit comments