Skip to content

Commit cb4d538

Browse files
feat(notion): attach pages as composer context (#140)
* feat(notion): attach pages as composer context * fix(notion): use monochrome Notion logo for page attachments
1 parent bd4331a commit cb4d538

52 files changed

Lines changed: 2423 additions & 21 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/mobile/src/components/ComposerAttachmentButton.tsx‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ const GITHUB_ISSUE_ACTION: MenuAction = {
1313
title: "GitHub issue",
1414
image: "smallcircle.filled.circle",
1515
};
16+
const NOTION_ACTION: MenuAction = { id: "notion", title: "Notion page", image: "doc.text" };
1617
const SLACK_ACTION: MenuAction = { id: "slack", title: "Slack message", image: "number" };
1718
const REPOSITORY_ACTION: MenuAction = {
1819
id: "repository",
@@ -30,6 +31,7 @@ export function ComposerAttachmentButton(props: {
3031
/** Omit to hide the GitHub issue action. See `useGitHubIssuePicker`. */
3132
readonly onPickGitHubIssue?: () => void;
3233
/** Omit to hide the Slack action. See `useSlackMessagePicker`. */
34+
readonly onPickNotionPage?: () => void;
3335
readonly onPickSlackMessage?: () => void;
3436
/** Omit to hide the repository action. See `useRepositoryPicker`. */
3537
readonly onPickRepository?: () => void;
@@ -40,6 +42,7 @@ export function ComposerAttachmentButton(props: {
4042
...(props.supportsFiles ? [FILES_ACTION] : []),
4143
...(props.onPickLinearIssue ? [LINEAR_ACTION] : []),
4244
...(props.onPickGitHubIssue ? [GITHUB_ISSUE_ACTION] : []),
45+
...(props.onPickNotionPage ? [NOTION_ACTION] : []),
4346
...(props.onPickSlackMessage ? [SLACK_ACTION] : []),
4447
...(props.onPickRepository ? [REPOSITORY_ACTION] : []),
4548
];
@@ -82,6 +85,8 @@ export function ComposerAttachmentButton(props: {
8285
props.onPickLinearIssue?.();
8386
} else if (nativeEvent.event === "github-issue") {
8487
props.onPickGitHubIssue?.();
88+
} else if (nativeEvent.event === "notion") {
89+
props.onPickNotionPage?.();
8590
} else if (nativeEvent.event === "slack") {
8691
props.onPickSlackMessage?.();
8792
} else if (nativeEvent.event === "repository") {

‎apps/mobile/src/components/ComposerContextSheet.tsx‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -403,6 +403,32 @@ export function ComposerContextSheet(props: {
403403
</Text>
404404
</View>
405405
) : null}
406+
{record.kind === "notion-page" ? (
407+
<View className="gap-3">
408+
<View className="gap-1">
409+
<Text selectable className="text-lg font-t3-semibold text-foreground">
410+
{record.title}
411+
</Text>
412+
</View>
413+
{/^https?:\/\//i.test(record.url) ? (
414+
<Pressable
415+
accessibilityRole="link"
416+
onPress={() => {
417+
void tryOpenExternalUrl(record.url, "markdown-link").then((opened) => {
418+
if (!opened) Alert.alert("Could not open Notion", "Try again later.");
419+
});
420+
}}
421+
className="rounded-xl bg-subtle p-4"
422+
>
423+
<Text className="text-foreground">Open in Notion</Text>
424+
</Pressable>
425+
) : null}
426+
{/* Plain text like the other captured context here: exactly what the agent received. */}
427+
<Text selectable className="text-sm text-foreground">
428+
{record.markdown}
429+
</Text>
430+
</View>
431+
) : null}
406432
{record.kind === "slack-thread" ? (
407433
<View className="gap-3">
408434
<View className="gap-1">
Lines changed: 246 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,246 @@
1+
import type { EnvironmentId, NotionPageSummary } from "@t3tools/contracts";
2+
import { useAtomValue } from "@effect/atom-react";
3+
import { notionPageContextRecord } from "@t3tools/client-runtime/state/notion";
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/unstable/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 { relativeTime } from "../lib/time";
14+
import { notionEnvironment } from "../state/notion";
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+
/** Notion allows about 20 searches a minute, so typing settles longer before it queries. */
27+
const SEARCH_DEBOUNCE_MS = 400;
28+
29+
/** Notion's failures carry a reason; a rate limit deserves a clearer hint than its detail. */
30+
function notionErrorMessage(error: unknown, fallback: string): string {
31+
if (typeof error === "object" && error !== null && "reason" in error) {
32+
if (error.reason === "rate-limited") return "Notion is busy. Try again shortly.";
33+
if (error.reason === "not-connected" || error.reason === "revoked") {
34+
return "Notion is not connected. Connect it from Settings > Integrations on desktop or web.";
35+
}
36+
if (error.reason === "not-found") return "Share that page with the Notion connection.";
37+
}
38+
return error instanceof Error && error.message.trim() ? error.message : fallback;
39+
}
40+
41+
export interface NotionPagePickerTarget {
42+
readonly environmentId: EnvironmentId;
43+
readonly draftKey: string;
44+
}
45+
46+
type OpenedNotionPagePicker = NotionPagePickerTarget & {
47+
readonly insertion: ComposerDraftInsertion;
48+
};
49+
50+
/**
51+
* A Notion page picker. The owner renders `sheet` somewhere that outlives composer focus:
52+
* opening the sheet blurs the editor, which can unmount a focus-dependent toolbar.
53+
*/
54+
export function useNotionPagePicker(target: NotionPagePickerTarget | null): {
55+
readonly open: () => void;
56+
readonly sheet: ReactNode;
57+
} {
58+
const [opened, setOpened] = useState<OpenedNotionPagePicker | null>(null);
59+
return {
60+
open: () => {
61+
if (target) {
62+
setOpened({ ...target, insertion: captureComposerDraftInsertion(target.draftKey) });
63+
}
64+
},
65+
sheet: opened ? <NotionPagePickerSheet {...opened} onClose={() => setOpened(null)} /> : null,
66+
};
67+
}
68+
69+
/**
70+
* Attaches a Notion page at the caret the composer had when the sheet opened. Mobile has no
71+
* Notion settings, so an unconnected environment points at desktop or web.
72+
*/
73+
function NotionPagePickerSheet(props: OpenedNotionPagePicker & { readonly onClose: () => void }) {
74+
const connection = useEnvironmentQuery(
75+
notionEnvironment.connection({ environmentId: props.environmentId, input: {} }),
76+
);
77+
const phase = connection.data?.phase;
78+
return (
79+
<PickerSheet title="Notion page" onClose={props.onClose}>
80+
{phase === "connected" ? (
81+
<NotionPageSearch {...props} />
82+
) : (
83+
<View className="flex-1 items-center justify-center p-6">
84+
{phase === undefined && !connection.error ? (
85+
<ActivityIndicator />
86+
) : (
87+
<Text className="text-center text-foreground-muted">
88+
{connection.error ??
89+
"Notion is not connected on this environment. Connect it from Settings > Integrations on desktop or web."}
90+
</Text>
91+
)}
92+
</View>
93+
)}
94+
</PickerSheet>
95+
);
96+
}
97+
98+
function NotionPageSearch(props: OpenedNotionPagePicker & { readonly onClose: () => void }) {
99+
const [query, setQuery] = useState("");
100+
const trimmed = query.trim();
101+
const settled = useDebouncedValue(trimmed, SEARCH_DEBOUNCE_MS);
102+
const getPage = useAtomCommand(notionEnvironment.getPage, {
103+
label: "notion page fetch",
104+
reportFailure: false,
105+
});
106+
const [attaching, setAttaching] = useState<string | null>(null);
107+
108+
const attach = async (page: NotionPageSummary) => {
109+
if (attaching) return;
110+
setAttaching(page.url);
111+
try {
112+
const fetched = await getPage({
113+
environmentId: props.environmentId,
114+
input: { id: page.id },
115+
});
116+
if (fetched._tag === "Failure") {
117+
Alert.alert(
118+
"Could not attach Notion page",
119+
notionErrorMessage(squashAtomCommandFailure(fetched), "Try again."),
120+
);
121+
return;
122+
}
123+
const record = notionPageContextRecord(fetched.value);
124+
if (
125+
!insertComposerDraftContext(
126+
props.draftKey,
127+
{
128+
text: formatComposerContextReference(record),
129+
context: { version: 1, records: [record] },
130+
},
131+
props.insertion,
132+
)
133+
) {
134+
Alert.alert("Too many context items", "Remove some context from the draft and try again.");
135+
return;
136+
}
137+
props.onClose();
138+
} finally {
139+
setAttaching(null);
140+
}
141+
};
142+
143+
return (
144+
<View className="flex-1">
145+
<View className="px-4 pb-3">
146+
<AppTextInput
147+
accessibilityLabel="Search Notion pages"
148+
autoFocus
149+
autoCapitalize="none"
150+
autoCorrect={false}
151+
clearButtonMode="while-editing"
152+
placeholder="Search Notion"
153+
returnKeyType="search"
154+
value={query}
155+
onChangeText={setQuery}
156+
/>
157+
</View>
158+
{settled ? (
159+
<NotionPageResults
160+
environmentId={props.environmentId}
161+
query={settled}
162+
pendingInput={settled !== trimmed}
163+
attaching={attaching}
164+
onPick={(page) => void attach(page)}
165+
/>
166+
) : (
167+
<View className="items-center p-6">
168+
{trimmed ? (
169+
<ActivityIndicator />
170+
) : (
171+
<Text className="text-center text-foreground-muted">
172+
Search by page title or paste a Notion link.
173+
</Text>
174+
)}
175+
</View>
176+
)}
177+
</View>
178+
);
179+
}
180+
181+
/** Mounted only for a settled, non-empty query, so an empty box never spends a search. */
182+
function NotionPageResults(props: {
183+
readonly environmentId: EnvironmentId;
184+
readonly query: string;
185+
readonly pendingInput: boolean;
186+
readonly attaching: string | null;
187+
readonly onPick: (page: NotionPageSummary) => void;
188+
}) {
189+
const insets = useSafeAreaInsets();
190+
const result = useAtomValue(
191+
notionEnvironment.pages({
192+
environmentId: props.environmentId,
193+
input: { query: props.query },
194+
}),
195+
);
196+
const pages = Option.getOrNull(AsyncResult.value(result))?.pages ?? [];
197+
const pending = props.pendingInput || result.waiting;
198+
const error =
199+
result._tag === "Failure"
200+
? notionErrorMessage(Cause.squash(result.cause), "Could not search Notion.")
201+
: null;
202+
return (
203+
<FlatList
204+
data={pages}
205+
keyExtractor={(page) => page.url}
206+
keyboardShouldPersistTaps="handled"
207+
contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 16) }}
208+
ListEmptyComponent={
209+
<View className="items-center p-6">
210+
{pending ? (
211+
<ActivityIndicator />
212+
) : (
213+
<Text
214+
selectable={error !== null}
215+
className={
216+
error ? "text-center text-danger-foreground" : "text-center text-foreground-muted"
217+
}
218+
>
219+
{error ?? "No matching pages."}
220+
</Text>
221+
)}
222+
</View>
223+
}
224+
renderItem={({ item }) => (
225+
<Pressable
226+
accessibilityRole="button"
227+
accessibilityLabel={item.title}
228+
disabled={props.attaching !== null}
229+
onPress={() => props.onPick(item)}
230+
className="flex-row items-center gap-3 px-4 py-3 active:bg-subtle disabled:opacity-60"
231+
>
232+
<View className="min-w-0 flex-1 gap-0.5">
233+
<Text className="text-sm text-foreground-muted" numberOfLines={1}>
234+
<Text className="text-sm font-t3-semibold text-foreground">{item.title}</Text>
235+
{` · ${relativeTime(item.updatedAt)}`}
236+
</Text>
237+
<Text className="text-base text-foreground" numberOfLines={2}>
238+
{item.url}
239+
</Text>
240+
</View>
241+
{props.attaching === item.url ? <ActivityIndicator /> : null}
242+
</Pressable>
243+
)}
244+
/>
245+
);
246+
}

‎apps/mobile/src/features/threads/NewTaskDraftScreen.tsx‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ import {
5959
takeStartFromGitHubIssue,
6060
useGitHubIssuePicker,
6161
} from "../../components/GitHubIssuePickerSheet";
62+
import { useNotionPagePicker } from "../../components/NotionPagePickerSheet";
6263
import { useSlackMessagePicker } from "../../components/SlackMessagePickerSheet";
6364
import { useRepositoryPicker } from "../../components/RepositoryPickerSheet";
6465
import { ControlPillMenu } from "../../components/ControlPillMenu";
@@ -991,6 +992,11 @@ export function NewTaskDraftScreen(props: {
991992
? { environmentId: flow.selectedEnvironmentId, draftKey: flow.draftKey }
992993
: null,
993994
);
995+
const notionPagePicker = useNotionPagePicker(
996+
flow.draftKey && flow.selectedEnvironmentId
997+
? { environmentId: flow.selectedEnvironmentId, draftKey: flow.draftKey }
998+
: null,
999+
);
9941000
const slackMessagePicker = useSlackMessagePicker(
9951001
flow.draftKey && flow.selectedEnvironmentId
9961002
? { environmentId: flow.selectedEnvironmentId, draftKey: flow.draftKey }
@@ -1829,6 +1835,11 @@ export function NewTaskDraftScreen(props: {
18291835
onPickGitHubIssue={
18301836
flow.draftKey && selectedProject ? gitHubIssuePicker.open : undefined
18311837
}
1838+
onPickNotionPage={
1839+
flow.draftKey && flow.selectedEnvironmentId
1840+
? notionPagePicker.open
1841+
: undefined
1842+
}
18321843
onPickSlackMessage={
18331844
flow.draftKey && flow.selectedEnvironmentId
18341845
? slackMessagePicker.open
@@ -1920,6 +1931,7 @@ export function NewTaskDraftScreen(props: {
19201931
{gitHubIssuePicker.sheet}
19211932
{startFromGitHubIssuePicker.sheet}
19221933
{slackMessagePicker.sheet}
1934+
{notionPagePicker.sheet}
19231935
{startFromPullRequestPicker.sheet}
19241936
{repositoryPicker.sheet}
19251937
</View>

‎apps/mobile/src/features/threads/ThreadComposer.tsx‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ import { AppText as Text } from "../../components/AppText";
6666
import { ComposerAttachmentButton } from "../../components/ComposerAttachmentButton";
6767
import { useLinearIssuePicker } from "../../components/LinearIssuePickerSheet";
6868
import { useGitHubIssuePicker } from "../../components/GitHubIssuePickerSheet";
69+
import { useNotionPagePicker } from "../../components/NotionPagePickerSheet";
6970
import { useSlackMessagePicker } from "../../components/SlackMessagePickerSheet";
7071
import { useRepositoryPicker } from "../../components/RepositoryPickerSheet";
7172
import {
@@ -341,6 +342,10 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
341342
environmentId: props.environmentId,
342343
draftKey: composerOwnerKey,
343344
});
345+
const notionPagePicker = useNotionPagePicker({
346+
environmentId: props.environmentId,
347+
draftKey: composerOwnerKey,
348+
});
344349
const slackMessagePicker = useSlackMessagePicker({
345350
environmentId: props.environmentId,
346351
draftKey: composerOwnerKey,
@@ -744,6 +749,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
744749
onPickFiles={props.onPickDraftFiles}
745750
onPickLinearIssue={linearIssuePicker.open}
746751
onPickGitHubIssue={workspaceCwd ? gitHubIssuePicker.open : undefined}
752+
onPickNotionPage={notionPagePicker.open}
747753
onPickSlackMessage={slackMessagePicker.open}
748754
onPickRepository={repositoryPicker.open}
749755
/>
@@ -999,6 +1005,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
9991005
onPickFiles={props.onPickDraftFiles}
10001006
onPickLinearIssue={linearIssuePicker.open}
10011007
onPickGitHubIssue={workspaceCwd ? gitHubIssuePicker.open : undefined}
1008+
onPickNotionPage={notionPagePicker.open}
10021009
onPickSlackMessage={slackMessagePicker.open}
10031010
onPickRepository={repositoryPicker.open}
10041011
/>
@@ -1053,6 +1060,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
10531060
{linearIssuePicker.sheet}
10541061
{gitHubIssuePicker.sheet}
10551062
{slackMessagePicker.sheet}
1063+
{notionPagePicker.sheet}
10561064
{repositoryPicker.sheet}
10571065
</Animated.View>
10581066
);

‎apps/mobile/src/state/notion.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import { createNotionEnvironmentAtoms } from "@t3tools/client-runtime/state/notion";
2+
import { connectionAtomRuntime } from "../connection/runtime";
3+
export const notionEnvironment = createNotionEnvironmentAtoms(connectionAtomRuntime);

0 commit comments

Comments
 (0)