The Coline App SDK: apps, tools, file types and surfaces that run inside Coline workspaces, and public websites with Coline Sites. TypeScript, with an in-memory test workspace. MIT.
| 6 |
| useContext, |
| 7 | useEffect, |
| 8 | useMemo, |
| 9 | useState, |
| 10 | useSyncExternalStore, |
| 11 | type AnchorHTMLAttributes, |
| 12 | type ButtonHTMLAttributes, |
| 13 | type ErrorInfo, |
| 14 | type MouseEvent, |
| 15 | type ReactElement, |
| 16 | type ReactNode, |
| 17 | } from "react"; |
| 18 | import type { ColineRecordQuery } from "../capabilities/types"; |
| 19 | import type { LiveCollectionOptions } from "../capabilities/live-collection"; |
| 20 | import type { SiteSignInProvider } from "../manifest/surfaces"; |
| 21 | import { |
| 22 | getSession, |
| 23 | liveCollection, |
| 24 | matchRoute, |
| 25 | signIn, |
| 26 | signOut, |
| 27 | site, |
| 28 | SiteError, |
| 29 | type SiteFile, |
| 30 | type SiteSession, |
| 31 | } from "./index"; |
| 32 | import type { SiteAppCollectionName, SiteAppRecord, SiteAppToolInput, SiteAppToolName, SiteAppToolOutput } from "./types"; |
| 33 |
| 34 | /** |
| 35 | * `@colineapp/sdk/site/react`: hooks and components for a site's React |
| 36 | * page (SDK 2.1). Everything runs as the visitor through |
| 37 | * `@colineapp/sdk/site`. |
| 38 | * |
| 39 | * ```tsx |
| 40 | * import { useCollection, useTool, SignInButton, Router, Routes, Route, Link } from "@colineapp/sdk/site/react"; |
| 41 | * ``` |
| 42 | * |
| 43 | * For types from the app itself, `createSiteHooks<typeof app>()` returns |
| 44 | * the same hooks typed by collection and tool name. |
| 45 | */ |
| 46 |
| 47 | // ── Session ──────────────────────────────────────────────────────────── |
| 48 |
| 49 | /** The visitor and site. `loading` until the first answer. */ |
| 50 | export function useSession(): { |
| 51 | session: SiteSession | null; |
| 52 | loading: boolean; |
| 53 | error: SiteError | null; |
| 54 | signIn: typeof signIn; |
| 55 | signOut: typeof signOut; |
| 56 | } { |
| 57 | const [state, setState] = useState<{ session: SiteSession | null; error: SiteError | null; loading: boolean }>({ |
| 58 | session: null, |
| 59 | error: null, |
| 60 | loading: true, |
| 61 | }); |
| 62 | useEffect(() => { |
| 63 | let active = true; |
| 64 | getSession() |
| 65 | .then((session) => active && setState({ session, error: null, loading: false })) |
| 66 | .catch((error: unknown) => active && setState({ session: null, error: asSiteError(error), loading: false })); |
| 67 | return () => { |
| 68 | active = false; |
| 69 | }; |
| 70 | }, []); |
| 71 | return { ...state, signIn, signOut }; |
| 72 | } |
| 73 |
| 74 | /** A plain button that starts sign-in; style it like any other button. */ |
| 75 | export function SignInButton({ |
| 76 | provider, |
| 77 | returnTo, |
| 78 | children, |
| 79 | ...props |
| 80 | }: { provider?: SiteSignInProvider; returnTo?: string; children?: ReactNode } & Omit< |
| 81 | ButtonHTMLAttributes<HTMLButtonElement>, |
| 82 | "onClick" | "type" |
| 83 | >): ReactElement { |
| 84 | const label = provider === "google" ? "Sign in with Google" : provider === "coline" ? "Sign in with Coline" : "Sign in"; |
| 85 | return createElement( |
| 86 | "button", |
| 87 | { |
| 88 | ...props, |
| 89 | type: "button", |
| 90 | onClick: () => signIn({ ...(provider ? { provider } : {}), ...(returnTo ? { returnTo } : {}) }), |
| 91 | }, |
| 92 | children ?? label, |
| 93 | ); |
| 94 | } |
| 95 |
| 96 | // ── Data ─────────────────────────────────────────────────────────────── |
| 97 |
| 98 | /** |
| 99 | * A live collection: records for this visitor, refreshed when the site's |
| 100 | * data changes, with optimistic `insert`, `update` and `delete`. |
| 101 | */ |
| 102 | export function useCollection<T extends Record<string, unknown> = Record<string, unknown>>( |
| 103 | name: string, |
| 104 | query: ColineRecordQuery<T> = {}, |
| 105 | options: LiveCollectionOptions = {}, |
| 106 | ) { |
| 107 | const key = JSON.stringify([name, query, options]); |
| 108 | // The view is rebuilt only when what it shows changes. |
| 109 | // eslint-disable-next-line react-hooks/exhaustive-deps |
| 110 | const view = useMemo(() => liveCollection<T>(name, query, options), [key]); |
| 111 | useEffect(() => { |
| 112 | void view.start(); |
| 113 | return () => view.stop(); |
| 114 | }, [view]); |
| 115 | const snapshot = useSyncExternalStore(view.subscribe, view.getSnapshot, view.getSnapshot); |
| 116 | return { |
| 117 | ...snapshot, |
| 118 | insert: view.insert, |
| 119 | update: view.update, |
| 120 | delete: view.delete, |
| 121 | refresh: view.refresh, |
| 122 | }; |
| 123 | } |
| 124 |
| 125 | /** `useCollection` that grows by `pageSize` with `loadMore()`. */ |
| 126 | export function usePaginatedCollection<T extends Record<string, unknown> = Record<string, unknown>>( |
| 127 | name: string, |
| 128 | query: Omit<ColineRecordQuery<T>, "limit" | "cursor"> = {}, |
| 129 | pageSize = 20, |
| 130 | ) { |
| 131 | const [limit, setLimit] = useState(pageSize); |
| 132 | const result = useCollection<T>(name, { ...query, limit } as ColineRecordQuery<T>); |
| 133 | const hasMore = result.records.length >= limit; |
| 134 | return { |
| 135 | ...result, |
| 136 | hasMore, |
| 137 | loadMore: useCallback(() => setLimit((current) => current + pageSize), [pageSize]), |
| 138 | }; |
| 139 | } |
| 140 |
| 141 | /** Run a site tool: `run(input)` resolves with its output. */ |
| 142 | export function useTool<TInput = unknown, TOutput = unknown>(name: string) { |
| 143 | const [state, setState] = useState<{ running: boolean; error: SiteError | null; output: TOutput | null }>({ |
| 144 | running: false, |
| 145 | error: null, |
| 146 | output: null, |
| 147 | }); |
| 148 | const run = useCallback( |
| 149 | async (input: TInput): Promise<TOutput> => { |
| 150 | setState((current) => ({ ...current, running: true, error: null })); |
| 151 | try { |
| 152 | const result = await site.tools.invoke<TOutput>(name, input); |
| 153 | setState({ running: false, error: null, output: result.output }); |
| 154 | return result.output; |
| 155 | } catch (error) { |
| 156 | const failure = asSiteError(error); |
| 157 | setState((current) => ({ ...current, running: false, error: failure })); |
| 158 | throw failure; |
| 159 | } |
| 160 | }, |
| 161 | [name], |
| 162 | ); |
| 163 | return { run, ...state }; |
| 164 | } |
| 165 |
| 166 | /** Upload files when the site accepts them. */ |
| 167 | export function useUpload() { |
| 168 | const [state, setState] = useState<{ uploading: boolean; error: SiteError | null }>({ uploading: false, error: null }); |
| 169 | const upload = useCallback(async (file: Blob, options?: { name?: string; public?: boolean }): Promise<SiteFile> => { |
| 170 | setState({ uploading: true, error: null }); |
| 171 | try { |
| 172 | const stored = await site.files.upload(file, options); |
| 173 | setState({ uploading: false, error: null }); |
| 174 | return stored; |
| 175 | } catch (error) { |
| 176 | const failure = asSiteError(error); |
| 177 | setState({ uploading: false, error: failure }); |
| 178 | throw failure; |
| 179 | } |
| 180 | }, []); |
| 181 | return { upload, ...state }; |
| 182 | } |
| 183 |
| 184 | /** |
| 185 | * The hooks above, typed from the app: collection names and record shapes |
| 186 | * from each collection's `schema`, tool names, inputs and outputs from |
| 187 | * `defineTool`. `import type app from "../app.config"` keeps the app's |
| 188 | * code out of the page. |
| 189 | */ |
| 190 | export function createSiteHooks<App>() { |
| 191 | return { |
| 192 | useCollection: <K extends SiteAppCollectionName<App>>( |
| 193 | name: K, |
| 194 | query?: ColineRecordQuery<SiteAppRecord<App, K>>, |
| 195 | options?: LiveCollectionOptions, |
| 196 | ) => useCollection<SiteAppRecord<App, K>>(name, query, options), |
| 197 | usePaginatedCollection: <K extends SiteAppCollectionName<App>>( |
| 198 | name: K, |
| 199 | query?: Omit<ColineRecordQuery<SiteAppRecord<App, K>>, "limit" | "cursor">, |
| 200 | pageSize?: number, |
| 201 | ) => usePaginatedCollection<SiteAppRecord<App, K>>(name, query, pageSize), |
| 202 | useTool: <N extends SiteAppToolName<App>>(name: N) => |
| 203 | useTool<SiteAppToolInput<App, N>, SiteAppToolOutput<App, N>>(name), |
| 204 | }; |
| 205 | } |
| 206 |
| 207 | // ── Routing ──────────────────────────────────────────────────────────── |
| 208 |
| 209 | const RouterContext = createContext<{ path: string; navigate: (to: string, options?: { replace?: boolean }) => void } | null>(null); |
| 210 | const ParamsContext = createContext<Record<string, string>>({}); |
| 211 |
| 212 | function subscribeLocation(onChange: () => void): () => void { |
| 213 | window.addEventListener("popstate", onChange); |
| 214 | window.addEventListener("coline:navigate", onChange); |
| 215 | return () => { |
| 216 | window.removeEventListener("popstate", onChange); |
| 217 | window.removeEventListener("coline:navigate", onChange); |
| 218 | }; |
| 219 | } |
| 220 |
| 221 | /** Go to a path on the site without reloading. Routes still need to be in `surfaces.site.routes`. */ |
| 222 | export function navigate(to: string, options: { replace?: boolean } = {}): void { |
| 223 | // Going where you already are (a tab clicked twice, a link to the |
| 224 | // current page) adds no history entry, so Back still goes back. |
| 225 | const target = new URL(to, window.location.href); |
| 226 | if (target.href === window.location.href) return; |
| 227 | if (options.replace) window.history.replaceState(null, "", target.href); |
| 228 | else window.history.pushState(null, "", target.href); |
| 229 | window.dispatchEvent(new Event("coline:navigate")); |
| 230 | window.scrollTo(0, 0); |
| 231 | } |
| 232 |
| 233 | /** Client-side routing for the page. Wrap the app in it once. */ |
| 234 | export function Router({ children }: { children?: ReactNode }): ReactElement { |
| 235 | const path = useSyncExternalStore( |
| 236 | subscribeLocation, |
| 237 | () => window.location.pathname, |
| 238 | () => "/", |
| 239 | ); |
| 240 | const value = useMemo(() => ({ path, navigate }), [path]); |
| 241 | return createElement(RouterContext.Provider, { value }, children); |
| 242 | } |
| 243 |
| 244 | /** Renders the first `Route` whose path matches, like a switch. */ |
| 245 | export function Routes({ children }: { children?: ReactNode }): ReactElement | null { |
| 246 | const router = useContext(RouterContext); |
| 247 | const path = router?.path ?? (typeof window === "undefined" ? "/" : window.location.pathname); |
| 248 | const routes = (Array.isArray(children) ? children : [children]).flat() as Array<ReactElement<RouteProps> | null>; |
| 249 | for (const route of routes) { |
| 250 | if (!route || typeof route !== "object" || !("props" in route)) continue; |
| 251 | const params = matchRoute(route.props.path, path); |
| 252 | if (params) return createElement(ParamsContext.Provider, { value: params }, route.props.children ?? null); |
| 253 | } |
| 254 | return null; |
| 255 | } |
| 256 |
| 257 | export interface RouteProps { |
| 258 | /** `/`, `/notes/:id`, or `*` for everything else. */ |
| 259 | path: string; |
| 260 | children?: ReactNode; |
| 261 | } |
| 262 |
| 263 | /** One route inside `Routes`. */ |
| 264 | export function Route({ children }: RouteProps): ReactElement | null { |
| 265 | return (children as ReactElement | null) ?? null; |
| 266 | } |
| 267 |
| 268 | /** A link that navigates without reloading. */ |
| 269 | export function Link({ to, onClick, ...props }: { to: string } & AnchorHTMLAttributes<HTMLAnchorElement>): ReactElement { |
| 270 | return createElement("a", { |
| 271 | ...props, |
| 272 | href: to, |
| 273 | onClick: (event: MouseEvent<HTMLAnchorElement>) => { |
| 274 | onClick?.(event); |
| 275 | if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; |
| 276 | if (props.target && props.target !== "_self") return; |
| 277 | event.preventDefault(); |
| 278 | navigate(to); |
| 279 | }, |
| 280 | }); |
| 281 | } |
| 282 |
| 283 | /** The current route's `:param` values. */ |
| 284 | export function useParams<T extends Record<string, string> = Record<string, string>>(): T { |
| 285 | return useContext(ParamsContext) as T; |
| 286 | } |
| 287 |
| 288 | /** `navigate(to)` from a component. */ |
| 289 | export function useNavigate(): typeof navigate { |
| 290 | return navigate; |
| 291 | } |
| 292 |
| 293 | /** |
| 294 | * The current path, search and hash, updated on `navigate`, `Link` and the |
| 295 | * back button. Works inside or outside `Router`, e.g. for an active nav link. |
| 296 | */ |
| 297 | export function useLocation(): { pathname: string; search: string; hash: string } { |
| 298 | const href = useSyncExternalStore( |
| 299 | subscribeLocation, |
| 300 | () => window.location.href, |
| 301 | () => "http://localhost/", |
| 302 | ); |
| 303 | return useMemo(() => { |
| 304 | const url = new URL(href); |
| 305 | return { pathname: url.pathname, search: url.search, hash: url.hash }; |
| 306 | }, [href]); |
| 307 | } |
| 308 |
| 309 | // ── Errors ───────────────────────────────────────────────────────────── |
| 310 |
| 311 | /** Catches render errors below it and shows `fallback(error, retry)`. */ |
| 312 | export class SiteErrorBoundary extends Component< |
| 313 | { fallback: (error: Error, retry: () => void) => ReactNode; children?: ReactNode }, |
| 314 | { error: Error | null } |
| 315 | > { |
| 316 | override state: { error: Error | null } = { error: null }; |
| 317 |
| 318 | static getDerivedStateFromError(error: Error) { |
| 319 | return { error }; |
| 320 | } |
| 321 |
| 322 | override componentDidCatch(error: Error, info: ErrorInfo) { |
| 323 | console.error(error, info.componentStack); |
| 324 | } |
| 325 |
| 326 | override render() { |
| 327 | if (this.state.error) return this.props.fallback(this.state.error, () => this.setState({ error: null })); |
| 328 | return this.props.children ?? null; |
| 329 | } |
| 330 | } |
| 331 |
| 332 | function asSiteError(error: unknown): SiteError { |
| 333 | if (error instanceof SiteError) return error; |
| 334 | return new SiteError("site_error", error instanceof Error ? error.message : "Something went wrong.", 0); |
| 335 | } |
| 336 |