History

Add iOS New Thread home screen widget

- Register configurable NewThread widget for iOS - Sync recent project shortcuts and deep links into draft threads - Cover widget ordering, pinning, and layout behavior

Julius Marminge committed 4 months ago

Commit 19d88071 parent 03ac1f07 files · +676 −0Browse files

Unified · Split

7 files
  1. apps/mobile/app.config.ts +26 −0
  2. apps/mobile/src/Stack.tsx +3 −0
  3. apps/mobile/src/features/threads/new-thread-widget.test.ts +111 −0
  4. apps/mobile/src/features/threads/new-thread-widget.ts +63 −0
  5. apps/mobile/src/features/threads/use-new-thread-widget-sync.ts +43 −0
  6. apps/mobile/src/widgets/NewThread.test.ts +227 −0
  7. apps/mobile/src/widgets/NewThread.tsx +203 −0
apps/mobile/app.config.ts+26−0
@@ -181,6 +181,32 @@ const config: ExpoConfig = { · 180 unmodified lines
181 description: "Shows the current state of active T3 Code agents.",181 description: "Shows the current state of active T3 Code agents.",
182 supportedFamilies: ["systemSmall", "systemMedium", "accessoryRectangular"],182 supportedFamilies: ["systemSmall", "systemMedium", "accessoryRectangular"],
183 },183 },
184 {
185 name: "NewThread",
186 displayName: "New Thread",
187 description: "Start a new T3 Code thread right from your Home Screen.",
188 supportedFamilies: ["systemSmall", "systemMedium", "systemLarge"],
189 // Per-instance options in the long-press "Edit Widget" sheet. Enum
190 // parameters are compiled into Swift at prebuild, so the dynamic
191 // project list cannot be offered as a picker — pins are typed as
192 // text and matched against the synced projects inside the widget.
193 configuration: {
194 title: "New Thread",
195 description: "Pin specific projects; the rest fills with your latest activity.",
196 parameters: {
197 pinnedProjects: {
198 title: "Pinned projects (comma-separated)",
199 type: "string",
200 default: "",
201 },
202 showRecent: {
203 title: "Fill with recent projects",
204 type: "boolean",
205 default: true,
206 },
207 },
208 },
209 },
184 ],210 ],
185 },211 },
186 ],212 ],
apps/mobile/src/Stack.tsx+3−0
@@ -40,6 +40,7 @@ import { AddProjectSourceRoute } from "./features/projects/AddProjectSourceRoute · 39 unmodified lines
40import { NewTaskDraftRouteScreen } from "./features/threads/NewTaskDraftRouteScreen";40import { NewTaskDraftRouteScreen } from "./features/threads/NewTaskDraftRouteScreen";
41import { NewTaskFlowProvider } from "./features/threads/new-task-flow-provider";41import { NewTaskFlowProvider } from "./features/threads/new-task-flow-provider";
42import { NewTaskRouteScreen } from "./features/threads/NewTaskRouteScreen";42import { NewTaskRouteScreen } from "./features/threads/NewTaskRouteScreen";
43import { useNewThreadWidgetSync } from "./features/threads/use-new-thread-widget-sync";
43import { SettingsAppearanceRouteScreen } from "./features/settings/SettingsAppearanceRouteScreen";44import { SettingsAppearanceRouteScreen } from "./features/settings/SettingsAppearanceRouteScreen";
44import { SettingsAuthRouteScreen } from "./features/settings/SettingsAuthRouteScreen";45import { SettingsAuthRouteScreen } from "./features/settings/SettingsAuthRouteScreen";
45import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen";46import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen";
@@ -256,6 +257,8 @@ function RootStackLayout(props: { · 210 unmodified lines
256 useThreadOutboxDrain();257 useThreadOutboxDrain();
257 // Presents the T3 Connect onboarding sheet after an in-session sign-in.258 // Presents the T3 Connect onboarding sheet after an in-session sign-in.
258 useConnectOnboardingNavigation();259 useConnectOnboardingNavigation();
260 // Keeps the NewThread home-screen widget's project shortcuts current.
261 useNewThreadWidgetSync();
259 // Full pathname (sheets included) for keyboard-command scoping; the262 // Full pathname (sheets included) for keyboard-command scoping; the
260 // workspace layout only reacts to the underlying non-overlay route.263 // workspace layout only reacts to the underlying non-overlay route.
261 const path = getPathFromState(props.state, navigationPathConfig);264 const path = getPathFromState(props.state, navigationPathConfig);
apps/mobile/src/features/threads/new-thread-widget.test.ts+111−0
@@ -0,0 +1,111 @@
1import { describe, expect, it } from "vite-plus/test";
2import type {
3 EnvironmentProject,
4 EnvironmentThreadShell,
5} from "@t3tools/client-runtime/state/shell";
6
7import {
8 makeNewThreadWidgetProps,
9 NEW_THREAD_WIDGET_PROJECT_SYNC_LIMIT,
10} from "./new-thread-widget";
11
12function makeProject(overrides: {
13 readonly id: string;
14 readonly environmentId?: string;
15 readonly title?: string;
16 readonly updatedAt?: string;
17}): EnvironmentProject {
18 return {
19 id: overrides.id,
20 environmentId: overrides.environmentId ?? "env-1",
21 title: overrides.title ?? overrides.id,
22 updatedAt: overrides.updatedAt ?? "2026-07-01T00:00:00.000Z",
23 } as unknown as EnvironmentProject;
24}
25
26function makeThread(overrides: {
27 readonly projectId: string;
28 readonly environmentId?: string;
29 readonly updatedAt: string;
30}): EnvironmentThreadShell {
31 return {
32 id: `thread-${overrides.projectId}`,
33 projectId: overrides.projectId,
34 environmentId: overrides.environmentId ?? "env-1",
35 updatedAt: overrides.updatedAt,
36 } as unknown as EnvironmentThreadShell;
37}
38
39describe("makeNewThreadWidgetProps", () => {
40 it("orders projects by their newest thread activity", () => {
41 const props = makeNewThreadWidgetProps(
42 [
43 makeProject({ id: "stale", updatedAt: "2026-07-06T00:00:00.000Z" }),
44 makeProject({ id: "busy", updatedAt: "2026-07-01T00:00:00.000Z" }),
45 ],
46 [makeThread({ projectId: "busy", updatedAt: "2026-07-07T00:00:00.000Z" })],
47 );
48 expect(props.projects?.map((project) => project.title)).toEqual(["busy", "stale"]);
49 });
50
51 it("falls back to the project's own updatedAt when it has no threads", () => {
52 const props = makeNewThreadWidgetProps(
53 [
54 makeProject({ id: "old", updatedAt: "2026-07-01T00:00:00.000Z" }),
55 makeProject({ id: "fresh", updatedAt: "2026-07-07T00:00:00.000Z" }),
56 ],
57 [],
58 );
59 expect(props.projects?.map((project) => project.title)).toEqual(["fresh", "old"]);
60 });
61
62 it("ignores thread activity from a same-named project in another environment", () => {
63 const props = makeNewThreadWidgetProps(
64 [
65 makeProject({ id: "proj", environmentId: "env-1", title: "one" }),
66 makeProject({
67 id: "proj",
68 environmentId: "env-2",
69 title: "two",
70 updatedAt: "2026-07-02T00:00:00.000Z",
71 }),
72 ],
73 [
74 makeThread({
75 projectId: "proj",
76 environmentId: "env-2",
77 updatedAt: "2026-07-07T00:00:00.000Z",
78 }),
79 ],
80 );
81 expect(props.projects?.map((project) => project.title)).toEqual(["two", "one"]);
82 });
83
84 it("caps the payload at the widget's sync limit", () => {
85 const props = makeNewThreadWidgetProps(
86 Array.from({ length: NEW_THREAD_WIDGET_PROJECT_SYNC_LIMIT + 5 }, (_, n) =>
87 makeProject({
88 id: `p${n}`,
89 updatedAt: `2026-06-${String(n + 1).padStart(2, "0")}T00:00:00.000Z`,
90 }),
91 ),
92 [],
93 );
94 expect(props.projects).toHaveLength(NEW_THREAD_WIDGET_PROJECT_SYNC_LIMIT);
95 expect(props.projects?.[0]?.title).toBe(`p${NEW_THREAD_WIDGET_PROJECT_SYNC_LIMIT + 4}`);
96 });
97
98 it("URL-encodes deep link parameters", () => {
99 const props = makeNewThreadWidgetProps(
100 [makeProject({ id: "p 1", environmentId: "env&1", title: "T3 & friends" })],
101 [],
102 );
103 expect(props.projects?.[0]?.deepLink).toBe(
104 "/new/draft?environmentId=env%261&projectId=p%201&title=T3%20%26%20friends",
105 );
106 });
107
108 it("returns an empty list when there are no projects", () => {
109 expect(makeNewThreadWidgetProps([], []).projects).toEqual([]);
110 });
111});
apps/mobile/src/features/threads/new-thread-widget.ts+63−0
@@ -0,0 +1,63 @@
1import type {
2 EnvironmentProject,
3 EnvironmentThreadShell,
4} from "@t3tools/client-runtime/state/shell";
5
6import type { NewThreadWidgetProps } from "../../widgets/NewThread";
7
8// Candidate pool synced to the widget. Deliberately larger than any family
9// displays (medium shows 3 rows, large 7): the "pinned projects" widget
10// configuration is per widget instance and only visible inside the widget
11// process, so the layout matches pins against this pool — a pin should still
12// resolve when its project is not among the most recent few.
13export const NEW_THREAD_WIDGET_PROJECT_SYNC_LIMIT = 20;
14
15/**
16 * Builds the home-screen widget payload: the most-recently-active projects,
17 * each with a deep link into the new-task draft composer for that project.
18 *
19 * "Recently active" means the newest thread update in the project, falling
20 * back to the project's own updatedAt for projects with no threads — so the
21 * widget surfaces where the user actually works, not what was created last.
22 */
23export function makeNewThreadWidgetProps(
24 projects: ReadonlyArray<EnvironmentProject>,
25 threads: ReadonlyArray<EnvironmentThreadShell>,
26): NewThreadWidgetProps {
27 const latestThreadActivity = new Map<string, string>();
28 for (const thread of threads) {
29 const key = projectActivityKey(thread.environmentId, thread.projectId);
30 const previous = latestThreadActivity.get(key);
31 // ISO-8601 timestamps order lexicographically.
32 if (previous === undefined || thread.updatedAt > previous) {
33 latestThreadActivity.set(key, thread.updatedAt);
34 }
35 }
36
37 const lastActivity = (project: EnvironmentProject): string => {
38 const threadActivity = latestThreadActivity.get(
39 projectActivityKey(project.environmentId, project.id),
40 );
41 return threadActivity !== undefined && threadActivity > project.updatedAt
42 ? threadActivity
43 : project.updatedAt;
44 };
45
46 const ordered = [...projects].sort((a, b) => lastActivity(b).localeCompare(lastActivity(a)));
47
48 return {
49 projects: ordered.slice(0, NEW_THREAD_WIDGET_PROJECT_SYNC_LIMIT).map((project) => ({
50 title: project.title,
51 // Matches the NewTaskSheet > NewTaskDraft linking config in Stack.tsx;
52 // the widget layout prefixes the scheme after a safety check.
53 deepLink:
54 `/new/draft?environmentId=${encodeURIComponent(String(project.environmentId))}` +
55 `&projectId=${encodeURIComponent(String(project.id))}` +
56 `&title=${encodeURIComponent(project.title)}`,
57 })),
58 };
59}
60
61function projectActivityKey(environmentId: string, projectId: string): string {
62 return `${environmentId}\u0000${projectId}`;
63}
apps/mobile/src/features/threads/use-new-thread-widget-sync.ts+43−0
@@ -0,0 +1,43 @@
1import { useEffect } from "react";
2import { Platform } from "react-native";
3
4import { useProjects, useThreadShells } from "../../state/entities";
5import NewThreadWidget from "../../widgets/NewThread";
6import { makeNewThreadWidgetProps } from "./new-thread-widget";
7
8// Last payload written to the widget timeline. Module-level (not React state)
9// so navigator remounts don't rewrite an unchanged payload: every write ends
10// in a WidgetCenter reload, and iOS throttles widgets that reload too often.
11let lastSyncedSignature: string | null = null;
12
13/**
14 * Keeps the NewThread home-screen widget's project shortcuts in sync with the
15 * workspace. Writing the snapshot also persists the widget layout to the
16 * shared app group, which is what lets the widget render at all — so this
17 * must run on every launch, not only when projects change.
18 */
19export function useNewThreadWidgetSync(): void {
20 const projects = useProjects();
21 const threads = useThreadShells();
22
23 useEffect(() => {
24 if (Platform.OS !== "ios") {
25 return;
26 }
27 const props = makeNewThreadWidgetProps(projects, threads);
28 const signature = JSON.stringify(props);
29 if (signature === lastSyncedSignature) {
30 return;
31 }
32 lastSyncedSignature = signature;
33 try {
34 NewThreadWidget.updateSnapshot(props);
35 } catch (error) {
36 // Clear the signature so the next data change retries the write.
37 lastSyncedSignature = null;
38 if (__DEV__) {
39 console.warn("[new-thread-widget] snapshot update failed", error);
40 }
41 }
42 }, [projects, threads]);
43}
apps/mobile/src/widgets/NewThread.test.ts+227−0
@@ -0,0 +1,227 @@
1import { describe, expect, it, vi } from "vite-plus/test";
2
3vi.mock("@expo/ui/swift-ui", () => ({
4 HStack: "HStack",
5 Image: "Image",
6 Link: "Link",
7 Spacer: "Spacer",
8 Text: "Text",
9 VStack: "VStack",
10}));
11
12vi.mock("@expo/ui/swift-ui/modifiers", () => ({
13 containerBackground: (color: unknown) => ({ containerBackground: color }),
14 font: (value: unknown) => value,
15 foregroundStyle: (value: unknown) => value,
16 frame: (value: unknown) => value,
17 lineLimit: (value: unknown) => value,
18 padding: (value: unknown) => value,
19 resizable: (value: unknown) => value,
20 widgetURL: (value: unknown) => ({ widgetURL: value }),
21}));
22
23vi.mock("expo-widgets", () => ({
24 createWidget: vi.fn((name: string, layout: unknown) => ({ layout, name })),
25}));
26
27import {
28 NewThread,
29 type NewThreadWidgetConfiguration,
30 type NewThreadWidgetProject,
31} from "./NewThread";
32
33function makeProject(overrides: Partial<NewThreadWidgetProject>): NewThreadWidgetProject {
34 return {
35 title: "Project",
36 deepLink: "/new/draft?environmentId=env-1&projectId=proj-1&title=Project",
37 ...overrides,
38 };
39}
40
41function makeEnvironment(overrides: {
42 readonly widgetFamily: "systemSmall" | "systemMedium" | "systemLarge";
43 readonly colorScheme?: "light" | "dark";
44 readonly configuration?: Partial<NewThreadWidgetConfiguration>;
45}) {
46 return {
47 date: new Date("2026-07-07T12:00:00.000Z"),
48 widgetFamily: overrides.widgetFamily,
49 colorScheme: overrides.colorScheme ?? "dark",
50 configuration: { pinnedProjects: "", showRecent: true, ...overrides.configuration },
51 } as never;
52}
53
54const smallEnvironment = makeEnvironment({ widgetFamily: "systemSmall" });
55const mediumEnvironment = makeEnvironment({ widgetFamily: "systemMedium" });
56
57describe("NewThread widget layout", () => {
58 it("deep links the whole small widget to the new-task sheet", () => {
59 const layout = JSON.stringify(NewThread({ projects: [] }, smallEnvironment));
60 expect(layout).toContain('"widgetURL":"t3code://new"');
61 expect(layout).toContain("New Thread");
62 });
63
64 it("renders the small call to action even when projects are present", () => {
65 const layout = JSON.stringify(
66 NewThread({ projects: [makeProject({ title: "t3code" })] }, smallEnvironment),
67 );
68 expect(layout).not.toContain("t3code://new/draft");
69 expect(layout).toContain('"widgetURL":"t3code://new"');
70 });
71
72 it("tolerates missing props and configuration (WidgetKit placeholder renders with none)", () => {
73 const layout = JSON.stringify(
74 NewThread(
75 {} as never,
76 {
77 date: new Date("2026-07-07T12:00:00.000Z"),
78 widgetFamily: "systemMedium",
79 colorScheme: "light",
80 configuration: undefined,
81 } as never,
82 ),
83 );
84 expect(layout).toContain('"widgetURL":"t3code://new"');
85 });
86
87 it("links each medium row to its project's draft composer", () => {
88 const layout = JSON.stringify(
89 NewThread(
90 {
91 projects: [
92 makeProject({ title: "t3code", deepLink: "/new/draft?projectId=a" }),
93 makeProject({ title: "marketing", deepLink: "/new/draft?projectId=b" }),
94 ],
95 },
96 mediumEnvironment,
97 ),
98 );
99 expect(layout).toContain("t3code");
100 expect(layout).toContain("marketing");
101 expect(layout).toContain('"destination":"t3code://new/draft?projectId=a"');
102 expect(layout).toContain('"destination":"t3code://new/draft?projectId=b"');
103 // Header link falls back to the plain new-task sheet.
104 expect(layout).toContain('"destination":"t3code://new"');
105 });
106
107 it("renders at most three rows on medium and seven on large", () => {
108 const projects = [1, 2, 3, 4, 5, 6, 7, 8].map((n) =>
109 makeProject({ title: `Project ${n}`, deepLink: `/new/draft?projectId=p${n}` }),
110 );
111 const medium = JSON.stringify(NewThread({ projects }, mediumEnvironment));
112 expect(medium).toContain("Project 3");
113 expect(medium).not.toContain("Project 4");
114 const large = JSON.stringify(
115 NewThread({ projects }, makeEnvironment({ widgetFamily: "systemLarge" })),
116 );
117 expect(large).toContain("Project 7");
118 expect(large).not.toContain("Project 8");
119 });
120
121 it("pins configured projects ahead of recents, in pin order", () => {
122 const layout = JSON.stringify(
123 NewThread(
124 {
125 projects: [
126 makeProject({ title: "recent" }),
127 makeProject({ title: "beta" }),
128 makeProject({ title: "alpha" }),
129 ],
130 },
131 makeEnvironment({
132 widgetFamily: "systemMedium",
133 configuration: { pinnedProjects: "Alpha, Beta" },
134 }),
135 ),
136 );
137 expect(layout.indexOf("alpha")).toBeLessThan(layout.indexOf("beta"));
138 expect(layout.indexOf("beta")).toBeLessThan(layout.indexOf("recent"));
139 // Pinned rows carry the pin glyph; the recent row keeps the folder.
140 expect(layout).toContain("pin.fill");
141 expect(layout).toContain("folder");
142 });
143
144 it("matches pins by case-insensitive prefix and skips unmatched pins", () => {
145 const layout = JSON.stringify(
146 NewThread(
147 {
148 projects: [makeProject({ title: "recent" }), makeProject({ title: "T3 Marketing Site" })],
149 },
150 makeEnvironment({
151 widgetFamily: "systemMedium",
152 configuration: { pinnedProjects: "t3 mark, no-such-project" },
153 }),
154 ),
155 );
156 expect(layout.indexOf("T3 Marketing Site")).toBeLessThan(layout.indexOf("recent"));
157 expect(layout).toContain("pin.fill");
158 });
159
160 it("pins can surface projects beyond the visible row budget", () => {
161 const projects = [1, 2, 3, 4, 5].map((n) => makeProject({ title: `Project ${n}` }));
162 const layout = JSON.stringify(
163 NewThread(
164 { projects },
165 makeEnvironment({
166 widgetFamily: "systemMedium",
167 configuration: { pinnedProjects: "Project 5" },
168 }),
169 ),
170 );
171 expect(layout).toContain("Project 5");
172 expect(layout).toContain("Project 1");
173 expect(layout).toContain("Project 2");
174 expect(layout).not.toContain("Project 3");
175 });
176
177 it("hides recents when the fill toggle is off", () => {
178 const layout = JSON.stringify(
179 NewThread(
180 { projects: [makeProject({ title: "pinned-one" }), makeProject({ title: "recent" })] },
181 makeEnvironment({
182 widgetFamily: "systemMedium",
183 configuration: { pinnedProjects: "pinned-one", showRecent: false },
184 }),
185 ),
186 );
187 expect(layout).toContain("pinned-one");
188 expect(layout).not.toContain("recent");
189 });
190
191 it("falls back to the call to action when recents are off and no pin matches", () => {
192 const layout = JSON.stringify(
193 NewThread(
194 { projects: [makeProject({ title: "recent" })] },
195 makeEnvironment({
196 widgetFamily: "systemMedium",
197 configuration: { pinnedProjects: "gone", showRecent: false },
198 }),
199 ),
200 );
201 expect(layout).toContain('"widgetURL":"t3code://new"');
202 expect(layout).not.toContain("recent");
203 });
204
205 it("drops the link but keeps the row for unsafe deep links", () => {
206 const layout = JSON.stringify(
207 NewThread(
208 { projects: [makeProject({ title: "sneaky", deepLink: "//evil.example" })] },
209 mediumEnvironment,
210 ),
211 );
212 expect(layout).toContain("sneaky");
213 expect(layout).not.toContain("evil.example");
214 });
215
216 it("adapts the container background to the color scheme", () => {
217 const dark = JSON.stringify(NewThread({ projects: [] }, smallEnvironment));
218 const light = JSON.stringify(
219 NewThread(
220 { projects: [] },
221 makeEnvironment({ widgetFamily: "systemSmall", colorScheme: "light" }),
222 ),
223 );
224 expect(dark).toContain('"containerBackground":"#0a0a0a"');
225 expect(light).toContain('"containerBackground":"#ffffff"');
226 });
227});
apps/mobile/src/widgets/NewThread.tsx+203−0
@@ -0,0 +1,203 @@
1import { HStack, Image, Link, Spacer, Text, VStack } from "@expo/ui/swift-ui";
2import type { ComponentProps, JSX } from "react";
3import {
4 containerBackground,
5 font,
6 foregroundStyle,
7 frame,
8 lineLimit,
9 padding,
10 resizable,
11 widgetURL,
12} from "@expo/ui/swift-ui/modifiers";
13import { createWidget, type WidgetEnvironment } from "expo-widgets";
14
15export interface NewThreadWidgetProject {
16 readonly title: string;
17 /** App-relative path to the prefilled draft composer, e.g. "/new/draft?environmentId=…". */
18 readonly deepLink: string;
19}
20
21export interface NewThreadWidgetProps {
22 /**
23 * Candidate projects, most recently active first. The medium/large widgets
24 * render a slice of these as one-tap shortcuts into the draft composer.
25 * More are synced than any family displays: pinned-project matching happens
26 * here in the widget (the configuration is per widget instance, so the app
27 * cannot precompute it), and a pin should resolve even when its project has
28 * fallen out of the top displayed rows.
29 * Optional because WidgetKit renders placeholder/gallery entries with no
30 * props before the app has ever written a timeline.
31 */
32 readonly projects?: ReadonlyArray<NewThreadWidgetProject>;
33}
34
35/** Mirrors the `configuration.parameters` in app.config.ts. */
36export interface NewThreadWidgetConfiguration {
37 /** Comma-separated project titles to pin ahead of recent projects. */
38 readonly pinnedProjects: string;
39 /** Whether to fill the remaining rows with recently active projects. */
40 readonly showRecent: boolean;
41}
42
43// This function is serialized into the widget extension's JS bundle, so it
44// must stay self-contained: no references to module-scope helpers, only the
45// imported view/modifier factories.
46export function NewThread(
47 props: NewThreadWidgetProps,
48 environment: WidgetEnvironment<NewThreadWidgetConfiguration>,
49): JSX.Element {
50 "widget";
51
52 // Semantic label colors adapt to whatever material the OS renders the
53 // widget on (light/dark home screen, tinted iOS 18 mode).
54 const primaryForeground = "primary";
55 const secondaryForeground = "secondary";
56 // Home-screen widgets must supply their own container background on iOS 17+;
57 // match the app's splash background per scheme.
58 const containerColor = environment.colorScheme === "dark" ? "#0a0a0a" : "#ffffff";
59
60 // Any registered scheme variant routes back to this app; taps are delivered
61 // to the widget's containing app, so the prod scheme is safe for all builds.
62 const newThreadUrl = "t3code://new";
63 const toWidgetUrl = (deepLink: string): string | null =>
64 deepLink.startsWith("/") && !deepLink.startsWith("//") ? `t3code://${deepLink.slice(1)}` : null;
65
66 // SF Symbols and the logo ignore frame/foregroundStyle applied directly to
67 // the image; size + tint them through a container the resizable image fills.
68 type SFName = NonNullable<ComponentProps<typeof Image>["systemName"]>;
69 const renderGlyph = (systemName: SFName, size: number, color: string) => (
70 <HStack modifiers={[frame({ width: size, height: size }), foregroundStyle(color)]}>
71 <Image systemName={systemName} modifiers={[resizable()]} />
72 </HStack>
73 );
74 // The 3:2 frame matches the T3 mark's aspect ratio so it never distorts.
75 const renderLogo = (height: number, color: string) => (
76 <HStack modifiers={[frame({ width: height * 1.5, height }), foregroundStyle(color)]}>
77 <Image assetName="T3Mark" modifiers={[resizable()]} />
78 </HStack>
79 );
80
81 const available = props.projects ?? [];
82 const configuration = environment.configuration;
83
84 // Pins are typed titles (see app.config.ts for why there is no picker).
85 // Match case-insensitively, exact title first and then prefix, preserving
86 // the user's pin order. Unmatched pins (typo, deleted project) are skipped.
87 const pinnedQueries = (
88 typeof configuration?.pinnedProjects === "string" ? configuration.pinnedProjects : ""
89 )
90 .split(",")
91 .map((title) => title.trim().toLowerCase())
92 .filter((title) => title.length > 0);
93 const pinned: NewThreadWidgetProject[] = [];
94 for (const query of pinnedQueries) {
95 const match =
96 available.find(
97 (project) => !pinned.includes(project) && project.title.toLowerCase() === query,
98 ) ??
99 available.find(
100 (project) => !pinned.includes(project) && project.title.toLowerCase().startsWith(query),
101 );
102 if (match) {
103 pinned.push(match);
104 }
105 }
106
107 // Pinned first, then latest activity — unless recents are configured off.
108 const rows = [...pinned];
109 if (configuration?.showRecent !== false) {
110 for (const project of available) {
111 if (!rows.includes(project)) {
112 rows.push(project);
113 }
114 }
115 }
116 const rowLimit = environment.widgetFamily === "systemLarge" ? 7 : 3;
117 const visible = rows.slice(0, rowLimit);
118
119 // The whole small widget is one tap target; the medium/large widgets add
120 // per-row links, with the root widgetURL as the fallback for untargeted areas.
121 const rootModifiers = [containerBackground(containerColor, "widget"), widgetURL(newThreadUrl)];
122
123 // Small family — and the larger families with nothing to list (no sync yet,
124 // or recents off with no pin matched) — render a single centered call to action.
125 if (environment.widgetFamily === "systemSmall" || visible.length === 0) {
126 return (
127 <VStack spacing={7} modifiers={rootModifiers}>
128 <Spacer minLength={0} />
129 {renderLogo(20, primaryForeground)}
130 <HStack spacing={5} alignment="center">
131 {renderGlyph("square.and.pencil", 12, secondaryForeground)}
132 <Text
133 modifiers={[font({ weight: "semibold", size: 13 }), foregroundStyle(primaryForeground)]}
134 >
135 New Thread
136 </Text>
137 </HStack>
138 <Spacer minLength={0} />
139 </VStack>
140 );
141 }
142
143 // Project shortcut row: tapping opens the draft composer with that project
144 // preselected. Rows whose deep link fails the safety check still render,
145 // but fall through to the root's plain new-thread tap target.
146 const renderProjectRow = (project: NewThreadWidgetProject, isPinned: boolean) => {
147 const url = toWidgetUrl(project.deepLink);
148 const row = (
149 <HStack spacing={7} alignment="center">
150 {renderGlyph(isPinned ? "pin.fill" : "folder", 11, secondaryForeground)}
151 <Text
152 modifiers={[
153 font({ weight: "semibold", size: 13 }),
154 foregroundStyle(primaryForeground),
155 lineLimit(1),
156 ]}
157 >
158 {project.title}
159 </Text>
160 <Spacer minLength={8} />
161 {renderGlyph("chevron.forward", 9, secondaryForeground)}
162 </HStack>
163 );
164 return url ? <Link destination={url}>{row}</Link> : row;
165 };
166
167 // Pinned rows always precede recents, so index < pinned.length marks them.
168 const renderRow = (index: number) => {
169 const project = visible[index];
170 return project ? renderProjectRow(project, index < pinned.length) : null;
171 };
172
173 return (
174 <VStack alignment="leading" spacing={8} modifiers={rootModifiers}>
175 <Link destination={newThreadUrl}>
176 <HStack spacing={7} alignment="center">
177 {renderLogo(15, primaryForeground)}
178 <Text
179 modifiers={[font({ weight: "bold", size: 14 }), foregroundStyle(primaryForeground)]}
180 >
181 New Thread
182 </Text>
183 <Spacer minLength={8} />
184 {renderGlyph("square.and.pencil", 14, secondaryForeground)}
185 </HStack>
186 </Link>
187 <Spacer minLength={0} modifiers={[padding({ vertical: 1 })]} />
188 {renderRow(0)}
189 {renderRow(1)}
190 {renderRow(2)}
191 {renderRow(3)}
192 {renderRow(4)}
193 {renderRow(5)}
194 {renderRow(6)}
195 <Spacer minLength={0} />
196 </VStack>
197 );
198}
199
200export default createWidget<NewThreadWidgetProps, NewThreadWidgetConfiguration>(
201 "NewThread",
202 NewThread,
203);

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t