Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

assistantCitationNavigation.ts

58 lines2.0 KB

1import { pipe } from "effect/Function";
2import type { AssistantCitation } from "@t3tools/contracts";
3import {
4 formatAssistantCitationHref,
5 parseAssistantCitationHref,
6} from "@t3tools/shared/assistantCitations";
7import * as Base64Url from "effect/encoding/Base64Url";
8import * as Result from "effect/Result";
9​
10import { randomUUID } from "./utils";
11​
12declare module "@tanstack/react-router" {
13 interface HistoryState {
14 assistantCitationActivation?: string;
15 }
17​
18const CITATION_HASH_PREFIX = "assistant-citation=";
19​
20/** Base64url keeps router hash normalization from decoding quote whitespace or source IDs. */
21export function assistantCitationHash(citation: AssistantCitation) {
22 return `${CITATION_HASH_PREFIX}${Base64Url.encode(formatAssistantCitationHref(citation))}`;
24​
25export function assistantCitationFromLocation(href: string) {
26 const hashIndex = href.indexOf("#");
27 if (hashIndex === -1) return null;
28 const hash = href.slice(hashIndex + 1);
29 if (!hash.startsWith(CITATION_HASH_PREFIX) || hash.length > 140_000) return null;
30 try {
31 return pipe(
32 hash.slice(CITATION_HASH_PREFIX.length),
33 Base64Url.decodeString,
34 Result.getOrThrow,
35 parseAssistantCitationHref,
36 );
37 } catch {
38 return null;
39 }
41​
42/** Return paths drop the quote hash so going back does not reveal its source again. */
43export function withoutAssistantCitationHash(href: string) {
44 const hashIndex = href.indexOf("#");
45 if (hashIndex === -1 || !href.startsWith(CITATION_HASH_PREFIX, hashIndex + 1)) return href;
46 return href.slice(0, hashIndex);
48​
49/** A fresh activation lets the same link reveal its source again after dismissal. */
50export function assistantCitationNavigation(citation: AssistantCitation) {
51 return {
52 to: "/$environmentId/$threadId" as const,
53 params: { environmentId: citation.environmentId, threadId: citation.threadId },
54 hash: assistantCitationHash(citation),
55 resetScroll: false,
56 state: { assistantCitationActivation: randomUUID() },
57 };