import { lazy, Suspense, useCallback, useEffect, useReducer, useRef, useState } from "react"; import { ContentSwapLayer } from "@chopin/editor/content-swap"; import { documentsPath, parseChildDocumentPath, parseDocumentPath, } from "@chopin/protocol/document-url"; import * as Api from "./api"; import { readChannelRecovery, rememberChannel } from "./channel-recovery"; import { childCloseAction, childHistoryState } from "./child-history"; import { documentRouteIdentity, transitionDocumentRoute } from "./document-route-swap"; import { newestDocument } from "./document-actions"; import { motionContract } from "./motion-contract"; import { motionImmediately } from "./motion-input"; import { NavigationShell, useNavigationDocument } from "./navigation-shell"; import type { ComponentType, ReactNode } from "react"; import type { DocumentRouteIdentity, DocumentRouteIdentitySource, DocumentRouteSwap as DocumentRouteSwapState, } from "./document-route-swap"; import type { WorkspaceSurface } from "./workspace-model"; let DocumentWorkspaceHost = lazy(() => import("./document-workspace-host")); export type HostedWorkspaceProps = { room: string; handle: string; label: string; slug: string; updatedAt: string; descriptionRevision: number; description?: string; repository: Api.Repository; canEdit: boolean; canManage: boolean; archivedAt?: string; agent?: boolean; userId: string; onMetadataChanged?: ( metadata: Pick< Api.Channel, | "archivedAt" | "description" | "descriptionRevision" | "slug" | "title" | "updatedAt" >, ) => void; surface?: WorkspaceSurface; }; export type HostedRoute = | DocumentRouteIdentitySource | { page: "repositories" } | { page: "repository"; owner: string; repository: string } | { page: "missing" }; type DocumentRoute = DocumentRouteIdentitySource; type ChannelSource = Extract; type DocumentSource = DocumentRoute; type DocumentRouteRequest = { immediately: boolean; key: DocumentRouteIdentity; routeKey: DocumentRouteIdentity; source: DocumentSource; }; type DocumentRouteResolution = { canonicalPath: string; channel: Api.Channel; routeKey: DocumentRouteIdentity; }; type DocumentRouteLayer = DocumentRouteSwapState< DocumentRouteRequest, DocumentRouteResolution >["current"]; function keyedDocumentRoute( route: DocumentRoute, immediately: boolean, alias?: DocumentRouteIdentity, ): DocumentRouteRequest { let routeKey = documentRouteIdentity(route); let key = alias ?? (route.page === "child" ? documentRouteIdentity({ owner: route.owner, page: "document", repository: route.repository, slug: route.parentSlug, }) : documentRouteIdentity(route)); return { immediately, key, routeKey, source: route, }; } function decoded(value: string): string | undefined { try { return decodeURIComponent(value); } catch { return undefined; } } export function hostedRoute(pathname: string): HostedRoute { if (pathname === "/" || pathname === "") return { page: "repositories" }; let child = parseChildDocumentPath(pathname); if (child) return { page: "child", ...child }; let document = parseDocumentPath(pathname); if (document?.slug) { return { page: "document", owner: document.owner, repository: document.repository, slug: document.slug, }; } if (document) return { page: "repository", ...document }; let repository = /^\/repositories\/([^/]+)\/([^/]+)\/?$/.exec(pathname); if (repository) { let owner = decoded(repository[1]!); let name = decoded(repository[2]!); if (owner && name) return { page: "repository", owner, repository: name }; } let channel = /^\/channels\/([0-9a-f-]{36})\/?$/i.exec(pathname); if (channel) return { page: "channel", id: channel[1]!.toLowerCase() }; return { page: "missing" }; } export function retryableChannelFailure(error: unknown): boolean { return !(error instanceof Api.ApiError) || error.status === 408 || error.status === 429 || error.status >= 500; } function Loading({ label = "Loading" }: { label?: string }) { return (
{label}
); } function repositoryHref(repository: { owner: string; name: string }): string { return documentsPath(repository.owner, repository.name); } function canonicalize(pathname: string): void { if (location.pathname === pathname) return; history.replaceState(history.state, "", `${pathname}${location.search}${location.hash}`); } function Failure( { channel, error, onRetry, repository, }: { channel?: { title?: string; slug?: string }; error: unknown; onRetry?: () => void; repository?: Pick; }, ) { let message = error instanceof Error ? error.message : "Something went wrong"; return (

Cannot open Chopin

{message}

{channel && (
{channel.title &&

{channel.title}

} {channel.slug && (

{channel.slug}

)} {repository && (

{repository.fullName}

)}
)}
{onRetry && ( )} {repository && ( View {repository.fullName} channels )} Back to repositories
); } export function HostedLogin() { let href = githubLoginHref(location.pathname, location.search, location.hash); return (

chopin

Plan together, in the context of the code.

A shared document, a visible conversation, and an agent that can read the repository without owning the decision.

Open your workspace

Sign in with GitHub to choose a repository and its planning channels.

Continue with GitHub
); } export function githubLoginHref(pathname: string, search = "", hash = ""): string { let parameters = new URLSearchParams({ return_to: `${pathname}${search}${hash}` }); return `/auth/github?${parameters}`; } function ChannelWorkspace( { agent, onReady, source, user }: { agent: boolean; onReady?: (key: DocumentRouteIdentity, resolution?: DocumentRouteResolution) => void; source: ChannelSource; user: Api.User; }, ) { type LoadedWorkspace = { detail: Api.ChannelDetail; Workspace: ComponentType; }; let [loaded, setLoaded] = useState(); let [error, setError] = useState(); let [retry, setRetry] = useState(0); let { channel: navigationChannel } = useNavigationDocument(); let routeKey = documentRouteIdentity(source); let recovery = readChannelRecovery(user.id, source.id); useEffect(() => { let active = true; let controller = new AbortController(); setLoaded(undefined); setError(undefined); let prepared = import("./document-loader").then(module => module.prepareDocumentLoad({ id: source.id }, controller.signal) ).then(({ detail, pathname }) => ({ canonicalPath: pathname, detail })); prepared = prepared.then(resolved => { if (active) { rememberChannel(user.id, resolved.detail.channel, resolved.detail.repository); } return resolved; }); let workspace = import("./room-workspace").then(module => ({ Workspace: module.RoomWorkspace, })); Promise.all([prepared, workspace]).then(([resolved, selected]) => { if (active) { setLoaded({ detail: resolved.detail, ...selected }); onReady?.(routeKey, { canonicalPath: resolved.canonicalPath, channel: resolved.detail.channel, routeKey, }); } }, reason => { if (active) { setError(reason); onReady?.(routeKey); } }); return () => { active = false; controller.abort(); }; }, [onReady, retry, routeKey, source, user.id]); if (error) { return ( { setError(undefined); setRetry(value => value + 1); } : undefined} repository={recovery?.repository} /> ); } if (!loaded) return ; let { detail } = loaded; let channel = navigationChannel?.id === detail.channel.id ? newestDocument(detail.channel, navigationChannel) : detail.channel; let props: HostedWorkspaceProps = { agent, archivedAt: channel.archivedAt, canEdit: !channel.archivedAt && (detail.canEdit || detail.canManage), canManage: detail.canManage, description: channel.description, descriptionRevision: channel.descriptionRevision, handle: user.login, label: channel.title, slug: channel.slug, updatedAt: channel.updatedAt, repository: detail.repository, room: detail.channel.id, userId: user.id, }; let Document = loaded.Workspace; return ; } function DocumentRouteSwap( { agent, onCanonicalPath, onChildClose, onParentRestored, route, user, }: { agent: boolean; onCanonicalPath: (pathname: string) => void; onChildClose: (parentPath: string) => void; onParentRestored: (parentId: string) => void; route: DocumentRoute; user: Api.User; }, ) { let aliases = useRef(new Map()); let routeKey = documentRouteIdentity(route); let requested = keyedDocumentRoute(route, motionImmediately(), aliases.current.get(routeKey)); let [state, dispatch] = useReducer( transitionDocumentRoute, { current: requested }, ); let requestedRoute = useRef({ key: requested.key, routeKey: requested.routeKey }); requestedRoute.current = { key: requested.key, routeKey: requested.routeKey }; let presentedRequest = state.pending ?? state.current; if (requested.key !== presentedRequest.key || requested.routeKey !== presentedRequest.routeKey) { dispatch({ route: requested, type: "requested" }); } let layers = [state.previous, state.current, state.pending].filter( (layer): layer is DocumentRouteLayer => layer !== undefined, ); let motion = motionContract("content-swap"); let ready = useCallback(( key: DocumentRouteIdentity, resolution?: DocumentRouteResolution, ) => { if (resolution) aliases.current.set(resolution.routeKey, key); dispatch({ key, resolution, type: "ready" }); }, []); let metadataPath = useCallback(( key: DocumentRouteIdentity, metadataRouteKey: DocumentRouteIdentity, pathname: string, ) => { let authority = requestedRoute.current; if (key !== authority.key || metadataRouteKey !== authority.routeKey) return; let canonicalRoute = hostedRoute(pathname); if (canonicalRoute.page === "document" || canonicalRoute.page === "child") { aliases.current.set(documentRouteIdentity(canonicalRoute), key); } onCanonicalPath(pathname); }, [onCanonicalPath]); let { onDocumentLoaded } = useNavigationDocument(); let published = useRef(undefined); useEffect(() => { let resolution = state.current.resolution; if (!resolution || published.current === resolution) return; published.current = resolution; onCanonicalPath(resolution.canonicalPath); void onDocumentLoaded(resolution.channel, resolution.routeKey); }, [onCanonicalPath, onDocumentLoaded, state.current.key, state.current.resolution]); return (
{layers.map(layer => { let source = layer.source; return ( dispatch({ key: layer.key, type: "closed" }) : undefined} > {source.page === "document" || source.page === "child" ? ( }> ) : ( )} ); })}
); } export function HostedApp( { agent, user }: { agent: boolean; user: Api.User }, ) { let [route, setRoute] = useState(() => hostedRoute(location.pathname)); let hostedRouteRef = useRef(route); hostedRouteRef.current = route; let childOpener = useRef(undefined); let navigate = useCallback((destination: string, options: { replace?: boolean } = {}) => { let target = new URL(destination, location.href); if (target.origin !== location.origin) { location.assign(target.href); return; } let next = `${target.pathname}${target.search}${target.hash}`; let current = `${location.pathname}${location.search}${location.hash}`; if (next === current) return; let nextRoute = hostedRoute(target.pathname); if (options.replace) history.replaceState(history.state, "", next); else { let currentRoute = hostedRouteRef.current; let siblingChild = nextRoute.page === "child" && currentRoute.page === "child" && nextRoute.owner.toLocaleLowerCase() === currentRoute.owner.toLocaleLowerCase() && nextRoute.repository.toLocaleLowerCase() === currentRoute.repository.toLocaleLowerCase() && nextRoute.parentSlug === currentRoute.parentSlug; let inAppChild = nextRoute.page === "child" && currentRoute.page === "document" && nextRoute.owner.toLocaleLowerCase() === currentRoute.owner.toLocaleLowerCase() && nextRoute.repository.toLocaleLowerCase() === currentRoute.repository.toLocaleLowerCase() && nextRoute.parentSlug === currentRoute.slug; if (siblingChild || inAppChild) { let active = document.activeElement; childOpener.current = active instanceof HTMLElement ? active : undefined; } if (siblingChild) history.replaceState(history.state, "", next); else if (inAppChild) { history.pushState( childHistoryState(history.state, current), "", next, ); } else history.pushState(null, "", next); } setRoute(nextRoute); }, []); let canonicalPath = useCallback((pathname: string) => { if (location.pathname === pathname) return; history.replaceState( history.state, "", `${pathname}${location.search}${location.hash}`, ); setRoute(hostedRoute(pathname)); }, []); let closeChild = useCallback((parentPath: string) => { let action = childCloseAction(history.state, parentPath); if (action.type === "back") history.back(); else navigate(action.destination, { replace: true }); }, [navigate]); let restoreParentFocus = useCallback((parentId: string) => { let target = childOpener.current; childOpener.current = undefined; requestAnimationFrame(() => { if (target?.isConnected) target.focus({ preventScroll: true }); else { document.querySelector( `[data-workspace-room="${CSS.escape(parentId)}"] [data-document-view="plan"] h2`, )?.focus({ preventScroll: true }); } }); }, []); useEffect(() => { let changed = () => setRoute(hostedRoute(location.pathname)); window.addEventListener("popstate", changed); return () => window.removeEventListener("popstate", changed); }, []); if (route.page === "missing") { return ; } let workspace: ReactNode; switch (route.page) { case "repositories": case "repository": break; case "document": case "child": case "channel": workspace = ( ); break; } return ( {workspace} ); } export { Failure as HostedFailure, Loading as HostedLoading };