@devries-cameron20 / t3code-1 / commits / 6ad58a8485
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

feat(mobile): add the Issues tab and issue screens (#37040)

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>

Julius Marminge committed Nov 16, 2026 at 22:00 UTC 6ad58a84857803e3c47be4d1e8d49871dcf4dd5b
73 files changed +3291 -723
apps/mobile/assets/icons/issue.png
Binary files /dev/null and b/apps/mobile/assets/icons/issue.png differ
apps/mobile/assets/icons/issue@2x.png
Binary files /dev/null and b/apps/mobile/assets/icons/issue@2x.png differ
apps/mobile/assets/icons/issue@3x.png
Binary files /dev/null and b/apps/mobile/assets/icons/issue@3x.png differ
apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt
+3 -1
@@ -126,7 +126,7 @@ class T3WorkspaceNavigationView(
126 private val onTabSelected by EventDispatcher()
127 private val onNewThread by EventDispatcher()
128 private val onOverlayChange by EventDispatcher()
129 - var tabs by mutableStateOf(listOf("threads", "pullRequests", "usage", "settings"))
129 + var tabs by mutableStateOf(listOf("threads", "pullRequests", "issues", "usage", "settings"))
130 var selectedTab by mutableStateOf("threads")
131 var rail by mutableStateOf(false)
132 var floating by mutableStateOf(false)
@@ -415,6 +415,7 @@ class T3WorkspaceNavigationView(
415 private fun tabTitle(tab: String) = when (tab) {
416 "threads" -> "Chats"
417 "pullRequests" -> "Pulls"
418 + "issues" -> "Issues"
419 "usage" -> "Usage"
420 else -> "Settings"
421 }
@@ -427,6 +428,7 @@ class T3WorkspaceNavigationView(
428 when (tab) {
429 "threads" -> R.drawable.t3_chats
430 "pullRequests" -> R.drawable.t3_pull_requests
431 + "issues" -> R.drawable.t3_issues
432 "usage" -> R.drawable.t3_usage
433 else -> R.drawable.t3_settings
434 }
apps/mobile/modules/t3-native-controls/android/src/main/res/drawable/t3_issues.xml new
+3
@@ -0,0 +1,3 @@
1 +<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
2 + <path android:fillColor="#000000" android:fillType="evenOdd" android:pathData="M12,2a10,10 0 1,0 0,20a10,10 0 1,0 0,-20ZM12,4a8,8 0 1,1 0,16a8,8 0 1,1 0,-16ZM12,10a2,2 0 1,0 0,4a2,2 0 1,0 0,-4Z" />
3 +</vector>
apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue.png
Binary files /dev/null and b/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue.png differ
apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue@2x.png
Binary files /dev/null and b/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue@2x.png differ
apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue@3x.png
Binary files /dev/null and b/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue@3x.png differ
apps/mobile/modules/t3-native-controls/ios/T3NativeControls.podspec
+1 -1
@@ -15,6 +15,6 @@ Pod::Spec.new do |s|
15 s.pod_target_xcconfig = {
16 'DEFINES_MODULE' => 'YES',
17 }
18 - s.resource_bundles = { 'T3NativeControlIcons' => ['Resources/Icons/pull-request*.png'] }
18 + s.resource_bundles = { 'T3NativeControlIcons' => ['Resources/Icons/pull-request*.png', 'Resources/Icons/issue*.png'] }
19 s.source_files = '**/*.{h,m,mm,swift,hpp,cpp}'
20 end
apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift
+4 -3
@@ -40,7 +40,7 @@ final class T3SidebarTabBarView: ExpoView, UITabBarDelegate {
40 private let composeButton = UIButton(type: .system)
41 private lazy var tabBarTrailing = tabBar.trailingAnchor.constraint(equalTo: trailingAnchor)
42 private var itemsByTab: [String: UITabBarItem] = [:]
43 - var tabs = ["threads", "pullRequests", "usage", "settings"] {
43 + var tabs = ["threads", "pullRequests", "issues", "usage", "settings"] {
44 didSet { if tabs != oldValue { updateItems() } }
45 }
46 var selectedTab = "threads" { didSet { updateSelection() } }
@@ -109,10 +109,11 @@ final class T3SidebarTabBarView: ExpoView, UITabBarDelegate {
109 private func prepareItems() {
110 let iconBundle = Bundle(for: Self.self).url(forResource: "T3NativeControlIcons", withExtension: "bundle").flatMap(Bundle.init(url:))
111 let pullRequestIcon = UIImage(named: "pull-request", in: iconBundle, compatibleWith: nil)?.withRenderingMode(.alwaysTemplate)
112 - let labels = ["threads": "Chats", "pullRequests": "PRs", "usage": "Usage", "settings": "Settings"]
112 + let labels = ["threads": "Chats", "pullRequests": "PRs", "issues": "Issues", "usage": "Usage", "settings": "Settings"]
113 + let issueIcon = UIImage(named: "issue", in: iconBundle, compatibleWith: nil)?.withRenderingMode(.alwaysTemplate)
114 let symbols = ["threads": "text.bubble", "usage": "chart.bar.xaxis", "settings": "gearshape"]
115 for (tab, label) in labels {
115 - let icon = tab == "pullRequests" ? pullRequestIcon : UIImage(systemName: symbols[tab] ?? "circle")
116 + let icon = tab == "pullRequests" ? pullRequestIcon : tab == "issues" ? issueIcon : UIImage(systemName: symbols[tab] ?? "circle")
117 let item = UITabBarItem(title: nil, image: tabIcon(icon), tag: 0)
118 item.accessibilityLabel = label
119 item.accessibilityIdentifier = "workspace-tab-\(tab)"
apps/mobile/src/Stack.tsx
+21
@@ -37,6 +37,10 @@ import { PullRequestReviewersScreen } from "./features/pull-requests/PullRequest
37 import { PullRequestLabelsScreen } from "./features/pull-requests/PullRequestLabelsScreen";
38 import { PullRequestEditScreen } from "./features/pull-requests/PullRequestEditScreen";
39 import { PullRequestFilterSearchScreen } from "./features/pull-requests/PullRequestFilterSearchScreen";
40 +import { IssueAssigneesScreen } from "./features/issues/IssueAssigneesScreen";
41 +import { IssueEditScreen } from "./features/issues/IssueEditScreen";
42 +import { IssueLabelsScreen } from "./features/issues/IssueLabelsScreen";
43 +import { IssueRouteScreen } from "./features/issues/IssueRouteScreen";
44 import {
45 RenderErrorBoundary,
46 RenderFailureView,
@@ -552,6 +556,23 @@ const RootStackConfig = createWorkspaceStackNavigator({
556 screen: PullRequestEditScreen,
557 options: sheetRoute({ detent: 0.75, androidFit: true }),
558 }),
559 + Issue: createNativeStackScreen({
560 + screen: IssueRouteScreen,
561 + linking: "issues/:environmentId/:projectId/:tracker/:scope/:issueKey",
562 + options: pageRoute({ duoMinimize: "never" }),
563 + }),
564 + IssueEdit: createNativeStackScreen({
565 + screen: IssueEditScreen,
566 + options: sheetRoute({ detent: 0.75, androidFit: true }),
567 + }),
568 + IssueLabels: createNativeStackScreen({
569 + screen: IssueLabelsScreen,
570 + options: SEARCH_SHEET_ROUTE,
571 + }),
572 + IssueAssignees: createNativeStackScreen({
573 + screen: IssueAssigneesScreen,
574 + options: SEARCH_SHEET_ROUTE,
575 + }),
576 Thread: createNativeStackScreen({
577 screen: ThreadRouteScreen,
578 linking: { path: "threads/:environmentId?/:threadId?", alias: ["new/draft"] },
apps/mobile/src/components/ComposerSurface.tsx new
+283
@@ -0,0 +1,283 @@
1 +import { useState, type ReactNode } from "react";
2 +import { I18nManager, Platform, type ViewStyle } from "react-native";
3 +import Animated, {
4 + FadeIn,
5 + type LayoutAnimationFunction,
6 + ReduceMotion,
7 + useAnimatedStyle,
8 + useDerivedValue,
9 + useSharedValue,
10 + withTiming,
11 +} from "react-native-reanimated";
12 +
13 +import { useSafeAreaInsets } from "react-native-safe-area-context";
14 +
15 +import { useAdaptiveWorkspaceLayout } from "../features/layout/AdaptiveWorkspaceLayout";
16 +import { useSidebarWorkspaceTabs } from "../features/layout/workspace/useSystemWorkspaceTabBar";
17 +import { useAndroidFloatingTabs } from "../features/settings/appearance/AppearancePreferencesProvider";
18 +import { compactEditorInsets } from "../features/threads/compactEditorInsets";
19 +import {
20 + useDeviceType,
21 + useDuoBottomBarInset,
22 + useNativeLayoutMetrics,
23 +} from "../native/native-layout-metrics";
24 +import type { ScaledTextRole } from "../features/settings/appearance/useScaledTextRole";
25 +import { MOBILE_TYPOGRAPHY } from "../lib/typography";
26 +import { useUniwindTheme } from "../lib/useUniwindTheme";
27 +import { GlassSurface } from "./ui/GlassSurface";
28 +
29 +const COLLAPSED_EDITOR_DEFAULT_INSET = 6;
30 +// iOS puts line-height slack above glyphs. DM Sans's lowercase midline is
31 +// descender (0.31em) + half x-height (0.504em) above the line bottom.
32 +const LOWERCASE_MIDLINE_EM = 0.562;
33 +
34 +function lowercaseMidline(text: ScaledTextRole): number {
35 + return text.lineHeight - LOWERCASE_MIDLINE_EM * text.fontSize;
36 +}
37 +
38 +function collapsedEditorInset(text: ScaledTextRole): number {
39 + const shift = lowercaseMidline(text) - lowercaseMidline(MOBILE_TYPOGRAPHY.body);
40 + return Math.max(0, Math.round(COLLAPSED_EDITOR_DEFAULT_INSET - shift));
41 +}
42 +
43 +const EXPANDED_EDITOR_INSET = 14;
44 +// Room under the expanded editor for the toolbar row.
45 +const EXPANDED_EDITOR_BOTTOM = 52;
46 +
47 +export function useCompactComposerEditor(text: ScaledTextRole, value: string, animate: boolean) {
48 + const [contentSize, setContentSize] = useState({ width: 0, height: 0 });
49 + const [compactWidth, setCompactWidth] = useState(0);
50 + const contentHeight = contentSize.height;
51 + const rowWidth = useSharedValue(0);
52 + const editorX = useSharedValue(0);
53 + const editorWidth = useSharedValue(0);
54 + const inset =
55 + Platform.OS === "android" ? COLLAPSED_EDITOR_DEFAULT_INSET : collapsedEditorInset(text);
56 + const minimum = Math.max(INLINE_EDITOR_HEIGHT, Math.ceil(text.lineHeight) + 2 * inset);
57 + const height = Math.max(
58 + minimum,
59 + Math.min(text.lineHeight * 4 + 2 * inset, contentHeight + 2 * inset),
60 + );
61 + // A line that fits the expanded editor may still overflow its compact slot.
62 + // Compare its measured width too so widening cannot trigger a collapse loop.
63 + const isExpanded =
64 + value.length > 0 &&
65 + (contentHeight > text.lineHeight * 1.5 ||
66 + (compactWidth > 0 && contentSize.width > compactWidth));
67 + const compactRowHeight = Math.max(44, minimum);
68 + const compactBottom = (compactRowHeight - minimum) / 2;
69 + const isRTL = I18nManager.isRTL;
70 + const expandedRowHeight = height + EXPANDED_EDITOR_BOTTOM;
71 + const expansion = useDerivedValue(() => {
72 + const target = isExpanded ? 1 : 0;
73 + return animate
74 + ? withTiming(target, {
75 + duration: COMPOSER_TRANSITION_DURATION_MS,
76 + reduceMotion: ReduceMotion.System,
77 + })
78 + : target;
79 + });
80 + const editorStyle = useAnimatedStyle(() => {
81 + const compactInsets = compactEditorInsets({
82 + slotX: editorX.value,
83 + slotWidth: editorWidth.value,
84 + rowWidth: rowWidth.value,
85 + isRTL,
86 + });
87 + const progress = expansion.value;
88 + // Hanging from the row top lets the text ride the growing edge and ignore the stale
89 + // height measured while it still wrapped in the compact slot. Layout props only:
90 + // Reanimated applies transforms frames ahead of layout, which tore the text from its frame.
91 + return {
92 + position: "absolute",
93 + overflow: "hidden",
94 + // The compact slot is unknown until its first layout, so the editor would draw over the + button.
95 + opacity: isExpanded || editorWidth.value > 0 ? 1 : 0,
96 + height,
97 + top: compactBottom * (1 - progress),
98 + left: compactInsets.left + (EXPANDED_EDITOR_INSET - compactInsets.left) * progress,
99 + // Snapping the far edge keeps the line from rewrapping while the near edge moves.
100 + right: isExpanded ? EXPANDED_EDITOR_INSET : compactInsets.right,
101 + };
102 + });
103 + const containerStyle = useAnimatedStyle(() => ({
104 + height: compactRowHeight + (expandedRowHeight - compactRowHeight) * expansion.value,
105 + }));
106 + return {
107 + isExpanded,
108 + containerStyle,
109 + // The expanded toolbar takes the row the text is leaving; reveal it once the text has lifted.
110 + // An entering animation hides it from its first frame, which a shared-value opacity cannot.
111 + toolbarControlsEntering:
112 + animate && isExpanded
113 + ? FadeIn.delay(COMPOSER_TRANSITION_DURATION_MS / 2)
114 + .duration(COMPOSER_TRANSITION_DURATION_MS / 2)
115 + .reduceMotion(ReduceMotion.System)
116 + : undefined,
117 + editorStyle,
118 + onRowLayout: (event: { nativeEvent: { layout: { width: number } } }) => {
119 + rowWidth.set(event.nativeEvent.layout.width);
120 + },
121 + onEditorLayout: (event: { nativeEvent: { layout: { x: number; width: number } } }) => {
122 + // The expanded toolbar gives this slot to the model control. Keep the
123 + // compact geometry for the return transition, rather than recording zero.
124 + if (!isExpanded) {
125 + editorX.set(event.nativeEvent.layout.x);
126 + editorWidth.set(event.nativeEvent.layout.width);
127 + setCompactWidth(Math.max(0, event.nativeEvent.layout.width - 8));
128 + }
129 + },
130 + editorProps: {
131 + singleLineCentered: !isExpanded,
132 + scrollEnabled: Platform.OS === "android" || contentHeight >= text.lineHeight * 4,
133 + contentInsetVertical: inset,
134 + onContentSizeChange: (size: { width: number; height: number }) => {
135 + setContentSize(size);
136 + },
137 + style: { flex: 1 },
138 + },
139 + };
140 +}
141 +
142 +export const COMPOSER_TRANSITION_DURATION_MS = 220;
143 +// Side panes animate dock width; nested horizontal transitions would make the surface trail the toolbar.
144 +const composerHeightTransition: LayoutAnimationFunction = (values) => {
145 + "worklet";
146 + const timing = {
147 + duration: COMPOSER_TRANSITION_DURATION_MS,
148 + reduceMotion: ReduceMotion.System,
149 + };
150 + return {
151 + initialValues: {
152 + originX: values.targetOriginX,
153 + originY: values.currentOriginY,
154 + width: values.targetWidth,
155 + height: values.currentHeight,
156 + },
157 + animations: {
158 + originX: values.targetOriginX,
159 + originY: withTiming(values.targetOriginY, timing),
160 + width: values.targetWidth,
161 + height: withTiming(values.targetHeight, timing),
162 + },
163 + };
164 +};
165 +const COMPOSER_LAYOUT_TRANSITION = Platform.OS === "android" ? undefined : composerHeightTransition;
166 +// Share of the one-row composer the draft keeps; a long model name truncates first.
167 +export const INLINE_EDITOR_MIN_WIDTH = "40%";
168 +const INLINE_EDITOR_HEIGHT = 36;
169 +
170 +const AnimatedGlassSurface = Animated.createAnimatedComponent(GlassSurface);
171 +
172 +export function ComposerSurface(props: {
173 + readonly children: ReactNode;
174 + readonly style: ViewStyle;
175 + readonly animateLayout?: boolean;
176 +}) {
177 + const colors = useUniwindTheme();
178 + const targetBorderRadius =
179 + typeof props.style.borderRadius === "number" ? props.style.borderRadius : 0;
180 + const shouldAnimate = props.animateLayout !== false && Platform.OS !== "android";
181 + const animatedBorderRadius = useDerivedValue(() =>
182 + shouldAnimate
183 + ? withTiming(targetBorderRadius, {
184 + duration: COMPOSER_TRANSITION_DURATION_MS,
185 + reduceMotion: ReduceMotion.System,
186 + })
187 + : targetBorderRadius,
188 + );
189 + const borderCurve = props.style.borderCurve;
190 + const animatedShapeStyle = useAnimatedStyle(() => ({
191 + borderRadius: animatedBorderRadius.value,
192 + ...(borderCurve ? { borderCurve } : {}),
193 + }));
194 + const layoutTransition = shouldAnimate ? COMPOSER_LAYOUT_TRANSITION : undefined;
195 +
196 + // Animate every native frame or glass and content jump to final height inside the clip.
197 + return (
198 + <Animated.View
199 + className={
200 + Platform.OS === "android" ? undefined : "shadow-[0_6px_28px] shadow-adaptive-black-a15-a35"
201 + }
202 + layout={layoutTransition}
203 + style={[
204 + animatedShapeStyle,
205 + {
206 + overflow: "hidden",
207 + },
208 + ]}
209 + >
210 + <AnimatedGlassSurface
211 + chrome="none"
212 + fallbackColor={colors["--color-composer-surface"]}
213 + fallbackClassName="border border-composer-border"
214 + glassEffectStyle="regular"
215 + pointerEvents="none"
216 + tintColor="transparent"
217 + layout={layoutTransition}
218 + style={[{ position: "absolute", inset: 0 }, animatedShapeStyle]}
219 + >
220 + {null}
221 + </AnimatedGlassSurface>
222 + <Animated.View
223 + collapsable={false}
224 + layout={layoutTransition}
225 + style={[props.style, animatedShapeStyle]}
226 + >
227 + {props.children}
228 + </Animated.View>
229 + </Animated.View>
230 + );
231 +}
232 +
233 +/** Space below the composer pill, inside the bottom inset it is given. */
234 +export const COMPOSER_BOTTOM_GUTTER = 6;
235 +
236 +/** Control size and pill shape: larger beside a sidebar tab picker and on iPad. */
237 +export function useComposerChrome() {
238 + const { layout } = useAdaptiveWorkspaceLayout();
239 + const floatingSidebarComposer = useAndroidFloatingTabs() && layout.usesSplitView;
240 + const sidebarWorkspaceTabs = useSidebarWorkspaceTabs();
241 + const deviceType = useDeviceType();
242 + const usesLargeControls = sidebarWorkspaceTabs === "picker" || deviceType === "pad";
243 + return {
244 + usesLargeControls,
245 + controlSize: usesLargeControls ? ("large" as const) : ("regular" as const),
246 + borderRadius: usesLargeControls ? 31 : 27,
247 + paddingVertical: usesLargeControls ? 9 : floatingSidebarComposer ? 6 : 2,
248 + };
249 +}
250 +
251 +/**
252 + * The inset below a composer pinned to the bottom of a page. Fixed while the keyboard animates:
253 + * changing it at keyboardDidHide makes the composer land low, then jump back above the safe area.
254 + */
255 +export function useComposerBottomInset() {
256 + const insets = useSafeAreaInsets();
257 + const windowMetrics = useNativeLayoutMetrics();
258 + const { layout } = useAdaptiveWorkspaceLayout();
259 + const bottomBarInset = useDuoBottomBarInset();
260 + const hasSidebarTabBar = useSidebarWorkspaceTabs() === "picker";
261 + // A pushed screen temporarily inherits the outgoing tab bar's safe area.
262 + // Use the window edge so hiding that bar cannot move the composer mid-push.
263 + const bottomSafeArea =
264 + Platform.OS === "ios" ? (windowMetrics?.safeArea.bottom ?? insets.bottom) : insets.bottom;
265 + // The pill already adds its own gutter; iPad and Duo align its edge with the native bar.
266 + const alignedBottomInset =
267 + bottomBarInset ??
268 + (Platform.OS === "ios" && Platform.isPad
269 + ? Math.max(bottomSafeArea, 12) - (layout.usesSplitView ? 5 : 0)
270 + : undefined);
271 + // The Duo's floating sidebar pill ends three points below the composer's usual gutter.
272 + return Math.max(
273 + 0,
274 + (alignedBottomInset !== undefined
275 + ? alignedBottomInset - COMPOSER_BOTTOM_GUTTER
276 + : Math.max(bottomSafeArea, 12)) - (hasSidebarTabBar ? 3 : 0),
277 + );
278 +}
279 +
280 +/** The editor's text style: the composer's scaled role in the theme's foreground color. */
281 +export function useComposerTextStyle(text: ScaledTextRole) {
282 + return { ...text, color: useUniwindTheme()["--color-foreground"] };
283 +}
apps/mobile/src/components/ui/AppSymbol.android.tsx
+3
@@ -150,6 +150,7 @@ const ANDROID_ICON_BY_SF_SYMBOL = {
150 "git.pull-request.closed": IconGitPullRequestClosed,
151 "git.pull-request.draft": IconGitPullRequestDraft,
152 "git.commit": IconGitCommit,
153 + "git.issue": IconCircleDot,
154 "arrow.branch": IconGitBranch,
155 "arrow.left": IconArrowLeft,
156 "arrow.right": IconArrowRight,
@@ -304,6 +305,7 @@ const ANDROID_ICON_BY_SF_SYMBOL = {
305 | "git.pull-request.closed"
306 | "git.pull-request.draft"
307 | "git.commit"
308 + | "git.issue"
309 | "file.diff"
310 | "robot",
311 Icon
@@ -315,6 +317,7 @@ const SF_ICON_LOOKUP: Partial<
317 | "git.pull-request.closed"
318 | "git.pull-request.draft"
319 | "git.commit"
320 + | "git.issue"
321 | "file.diff"
322 | "robot",
323 Icon
apps/mobile/src/components/ui/AppSymbol.tsx
+2
@@ -4,6 +4,7 @@ import IconGitCommit from "@tabler/icons-react-native/IconGitCommit";
4 import IconGitPullRequestClosed from "@tabler/icons-react-native/IconGitPullRequestClosed";
5 import IconGitPullRequestDraft from "@tabler/icons-react-native/IconGitPullRequestDraft";
6 import type { SFSymbol } from "expo-symbols";
7 +import IconCircleDot from "@tabler/icons-react-native/IconCircleDot";
8 import IconGitPullRequest from "@tabler/icons-react-native/IconGitPullRequest";
9 import IconFileDiff from "@tabler/icons-react-native/IconFileDiff";
10 import IconRobot from "@tabler/icons-react-native/IconRobot";
@@ -23,6 +24,7 @@ const CUSTOM_ICONS = {
24 "git.pull-request.closed": IconGitPullRequestClosed,
25 "git.pull-request.draft": IconGitPullRequestDraft,
26 "git.commit": IconGitCommit,
27 + "git.issue": IconCircleDot,
28 robot: IconRobot,
29 };
30
apps/mobile/src/features/issues/IssueAssigneesScreen.tsx new
+99
@@ -0,0 +1,99 @@
1 +import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
2 +import { useAtom } from "@effect/atom-react";
3 +import {
4 + issueAssigneeHeld,
5 + issueAssigneesAfterPicks,
6 + issuePicksFor,
7 + issueWriteAfterPicks,
8 + noIssuePicks,
9 +} from "@t3tools/client-runtime/issue-selection";
10 +import { isSelected, toggleSelection } from "@t3tools/client-runtime/pull-request-selection";
11 +import type { IssueAssigneeCandidate } from "@t3tools/contracts";
12 +import { useEffect, useState } from "react";
13 +
14 +import * as Dialog from "../../components/ui/Dialog";
15 +import { issueEnvironment } from "../../state/issues";
16 +import { useEnvironmentQuery } from "../../state/query";
17 +import { useAtomCommand } from "../../state/use-atom-command";
18 +import { PullRequestAvatar } from "../pull-requests/PullRequestPresentation";
19 +import { IssueCandidatesSheet } from "./IssueCandidatesSheet";
20 +import { issueParamsKey, issueTarget, type IssueParams } from "./issueParams";
21 +import { issueAssigneePicksFamily } from "./issuePicks";
22 +import { issueCommandError, useIssueAccess } from "./issuePresentation";
23 +
24 +export function IssueAssigneesScreen({ route }: StaticScreenProps<IssueParams>) {
25 + const navigation = useNavigation();
26 + const target = issueTarget(route.params);
27 + const detail = useEnvironmentQuery(issueEnvironment.detail(target)).data;
28 + const access = useIssueAccess(route.params, detail);
29 + const result = useEnvironmentQuery(issueEnvironment.candidates(target));
30 + const update = useAtomCommand(issueEnvironment.update, { reportFailure: false });
31 + const [query, setQuery] = useState("");
32 + const [picks, setPicks] = useAtom(issueAssigneePicksFamily(issueParamsKey(route.params)));
33 + // Picks against an older read are dropped when the sheet opens, and kept across a read while open.
34 + const [openedWith] = useState(detail);
35 + const current = detail
36 + ? issuePicksFor(picks, detail, detail !== openedWith)
37 + : noIssuePicks<IssueAssigneeCandidate>();
38 + const draft = current.draft;
39 + const allowed = access?.assignees === true;
40 + const held = (candidate: IssueAssigneeCandidate) =>
41 + detail ? issueAssigneeHeld(detail, candidate) : false;
42 + const needle = query.trim().toLowerCase();
43 + const candidates = (result.data?.assignees ?? []).filter((candidate) =>
44 + `${candidate.login} ${candidate.name ?? ""}`.toLowerCase().includes(needle),
45 + );
46 + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- picks are sent when the sheet leaves the navigation stack, however it is dismissed
47 + useEffect(
48 + () =>
49 + navigation.addListener("beforeRemove", () => {
50 + if (!detail) return;
51 + const assignees = issueWriteAfterPicks(
52 + issueAssigneesAfterPicks(detail, draft),
53 + detail.assignees.map((actor) => actor.login),
54 + current.written,
55 + );
56 + if (assignees === null) return;
57 + setPicks({ ...current, written: assignees });
58 + void update({ ...target, input: { ...target.input, assignees } }).then((response) => {
59 + const failure = issueCommandError(response);
60 + if (failure === null) return;
61 + setPicks(noIssuePicks());
62 + Dialog.alert("Couldn't change assignees", failure);
63 + });
64 + }),
65 + [navigation, detail, draft, current, setPicks, update, target],
66 + );
67 + return (
68 + <IssueCandidatesSheet
69 + title="Assignees"
70 + noun="people"
71 + query={query}
72 + onQueryChange={setQuery}
73 + candidates={candidates.map((candidate) => ({
74 + key: candidate.id,
75 + title: candidate.login,
76 + ...(candidate.name ? { subtitle: candidate.name } : {}),
77 + leading: <PullRequestAvatar actor={candidate} size={24} />,
78 + // Sent when the sheet closes; a failure puts the tracker's answer back.
79 + selected: isSelected(draft, candidate.id, held(candidate)),
80 + }))}
81 + allowed={allowed}
82 + notice={
83 + detail && !allowed
84 + ? (access?.blocked ?? "Changing assignees needs triage access on this tracker.")
85 + : null
86 + }
87 + pending={result.isPending && !result.data}
88 + loadError={result.data ? null : result.error}
89 + onRetry={result.refresh}
90 + truncated={result.data?.truncated === true}
91 + onToggle={(id) => {
92 + const candidate = candidates.find((entry) => entry.id === id);
93 + if (candidate) {
94 + setPicks({ ...current, draft: toggleSelection(draft, id, candidate, held(candidate)) });
95 + }
96 + }}
97 + />
98 + );
99 +}
apps/mobile/src/features/issues/IssueCandidatesSheet.tsx new
+115
@@ -0,0 +1,115 @@
1 +import { LegendList } from "@legendapp/list/react-native";
2 +import type { ReactNode } from "react";
3 +import { Platform, View } from "react-native";
4 +
5 +import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
6 +import { AppText as Text } from "../../components/ui/AppText";
7 +import { Button } from "../../components/ui/Button";
8 +import { EmptyState } from "../../components/ui/EmptyState";
9 +import { SelectionRow } from "../../components/ui/SelectionRow";
10 +import { NativeScrollView } from "../../native/NativeScrollViewMarker";
11 +import { PullRequestSearchSheet } from "../pull-requests/PullRequestSearchSheet";
12 +
13 +interface Candidate {
14 + readonly key: string;
15 + readonly title: string;
16 + readonly subtitle?: string;
17 + readonly leading: ReactNode;
18 + readonly selected: boolean;
19 +}
20 +
21 +/** The searchable checklist behind the label and assignee pickers. */
22 +export function IssueCandidatesSheet(props: {
23 + readonly title: string;
24 + readonly noun: "labels" | "people";
25 + readonly query: string;
26 + readonly onQueryChange: (query: string) => void;
27 + readonly candidates: ReadonlyArray<Candidate>;
28 + readonly allowed: boolean;
29 + readonly notice: string | null;
30 + readonly pending: boolean;
31 + readonly loadError: string | null;
32 + readonly onRetry: () => void;
33 + readonly truncated: boolean;
34 + readonly onToggle: (key: string) => void;
35 +}) {
36 + const searching = props.query.trim().length > 0;
37 + return (
38 + <PullRequestSearchSheet
39 + title={props.title}
40 + placeholder={`Search ${props.noun}`}
41 + closeAccessibilityLabel={`Close ${props.title.toLowerCase()}`}
42 + clearAccessibilityLabel="Clear search"
43 + query={props.query}
44 + onQueryChange={props.onQueryChange}
45 + >
46 + {({ paddingBottom }) => (
47 + <LegendList
48 + renderScrollComponent={NativeScrollView}
49 + data={props.candidates}
50 + keyExtractor={(candidate) => candidate.key}
51 + extraData={props.candidates}
52 + estimatedItemSize={64}
53 + recycleItems
54 + className="flex-1"
55 + contentInsetAdjustmentBehavior="automatic"
56 + automaticallyAdjustKeyboardInsets={Platform.OS === "ios"}
57 + keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}
58 + keyboardShouldPersistTaps="handled"
59 + showsVerticalScrollIndicator={false}
60 + contentContainerStyle={{ paddingHorizontal: 16, paddingTop: 16, paddingBottom }}
61 + ListHeaderComponent={
62 + props.notice ? (
63 + <Text className="pb-3 text-xs text-foreground-muted">{props.notice}</Text>
64 + ) : undefined
65 + }
66 + renderItem={({ item, index }) => (
67 + <SelectionRow
68 + title={item.title}
69 + {...(item.subtitle ? { subtitle: item.subtitle } : {})}
70 + role="checkbox"
71 + selected={item.selected}
72 + disabled={!props.allowed}
73 + isFirst={index === 0}
74 + isLast={index === props.candidates.length - 1}
75 + leading={item.leading}
76 + onPress={() => props.onToggle(item.key)}
77 + />
78 + )}
79 + ListEmptyComponent={
80 + props.pending ? (
81 + <AppActivityIndicator className="my-8" />
82 + ) : (
83 + <View>
84 + <EmptyState
85 + title={
86 + props.loadError
87 + ? `Couldn't load ${props.noun}`
88 + : searching
89 + ? `No matching ${props.noun}`
90 + : props.noun === "labels"
91 + ? "This tracker has no labels"
92 + : "Nobody can be assigned here"
93 + }
94 + detail={
95 + props.loadError ??
96 + (searching ? "Try another name." : "Add them on the tracker to use them here.")
97 + }
98 + variant="plain"
99 + />
100 + {props.loadError ? <Button label="Retry" onPress={props.onRetry} /> : null}
101 + </View>
102 + )
103 + }
104 + ListFooterComponent={
105 + props.truncated ? (
106 + <Text className="py-4 text-xs text-foreground-muted">
107 + More {props.noun} exist than are listed here.
108 + </Text>
109 + ) : undefined
110 + }
111 + />
112 + )}
113 + </PullRequestSearchSheet>
114 + );
115 +}
apps/mobile/src/features/issues/IssueCommentComposer.tsx new
+263
@@ -0,0 +1,263 @@
1 +import { useRef, useState } from "react";
2 +import { Platform, View } from "react-native";
3 +import Animated from "react-native-reanimated";
4 +
5 +import {
6 + ComposerEditor,
7 + type ComposerEditorHandle,
8 + type ComposerEditorSelection,
9 +} from "../../components/ComposerEditor";
10 +import {
11 + COMPOSER_BOTTOM_GUTTER,
12 + ComposerSurface,
13 + INLINE_EDITOR_MIN_WIDTH,
14 + useCompactComposerEditor,
15 + useComposerChrome,
16 + useComposerTextStyle,
17 +} from "../../components/ComposerSurface";
18 +import { ComposerActionButton, ComposerToolbarRow } from "../../components/ComposerToolbar";
19 +import { AppText as Text } from "../../components/ui/AppText";
20 +import { useComposerTextRole } from "../settings/appearance/useScaledTextRole";
21 +import {
22 + ComposerDictationCancelAction,
23 + ComposerDictationDraftContent,
24 + ComposerDictationError,
25 + ComposerDictationPrimaryAction,
26 + ComposerDictationStartAction,
27 + ComposerDictationStatus,
28 + ComposerDictationToolbar,
29 +} from "../voice-input/ComposerDictationControl";
30 +import { useVoiceInputController } from "../voice-input/useVoiceInputController";
31 +import { resolveVoiceComposerPresentation } from "../voice-input/voiceInputPresentation";
32 +
33 +// The thread composer's editor starts after its attachment button; this keeps the same text inset.
34 +const EDITOR_LEADING_INSET = 14;
35 +
36 +/**
37 + * The comment box at the foot of an issue, in the thread composer's chrome: one row that grows
38 + * with the draft, dictation, and a round send button. `blocked` replaces the editor with the reason.
39 + */
40 +export function IssueCommentComposer(props: {
41 + /** Names this draft to dictation, so a recording started here lands here. */
42 + readonly ownerKey: string;
43 + readonly label: string;
44 + readonly blocked: string | null;
45 + readonly posting: boolean;
46 + readonly bottomInset: number;
47 + readonly contentMaxWidth?: number;
48 + /** Resolves true once the comment is posted, which clears the draft. */
49 + readonly onSubmit: (body: string) => Promise<boolean>;
50 + readonly onHeightChange: (height: number) => void;
51 + readonly onFocusChange: (focused: boolean) => void;
52 +}) {
53 + const editorRef = useRef<ComposerEditorHandle>(null);
54 + const [draft, setDraft] = useState("");
55 + // Read by dictation and by send after an await, when the render's `draft` may be stale.
56 + const latestDraft = useRef(draft);
57 + const changeDraft = (text: string) => {
58 + latestDraft.current = text;
59 + setDraft(text);
60 + };
61 + const [selection, setSelection] = useState<ComposerEditorSelection>({ start: 0, end: 0 });
62 + const bodyText = useComposerTextRole();
63 + const textStyle = useComposerTextStyle(bodyText);
64 + const chrome = useComposerChrome();
65 + const [focused, setFocused] = useState(false);
66 + // Animate only while typing, as the thread composer does; a restored draft lands in place.
67 + const compactEditor = useCompactComposerEditor(bodyText, draft, Platform.OS === "ios" && focused);
68 + const voiceInput = useVoiceInputController({
69 + ownerKey: props.ownerKey,
70 + label: props.label,
71 + readDraftMessage: () => latestDraft.current,
72 + selection,
73 + disabled: props.blocked !== null,
74 + onChangeDraftMessage: changeDraft,
75 + onChangeSelection: setSelection,
76 + });
77 + const voicePresentation = resolveVoiceComposerPresentation(
78 + voiceInput.state,
79 + voiceInput.elapsedSeconds,
80 + );
81 + const dictating = voicePresentation.statusKind === "active";
82 + const locked = props.posting || voiceInput.blocksSubmission;
83 + const canSend = props.blocked === null && !locked && draft.trim().length > 0;
84 +
85 + const sending = useRef(false);
86 + const flushAndSubmit = async () => {
87 + await editorRef.current?.flushPendingInput();
88 + const submitted = latestDraft.current;
89 + if (submitted.trim().length === 0) return;
90 + if ((await props.onSubmit(submitted)) && latestDraft.current === submitted) changeDraft("");
91 + };
92 + const send = () => {
93 + if (!canSend || sending.current) return Promise.resolve();
94 + sending.current = true;
95 + // `finally` on the promise: the React Compiler does not compile a `try` without a `catch`.
96 + return flushAndSubmit().finally(() => {
97 + sending.current = false;
98 + });
99 + };
100 + const sendButton = (
101 + <ComposerActionButton
102 + size={chrome.controlSize}
103 + accessibilityLabel={props.posting ? "Posting comment" : "Post comment"}
104 + icon="arrow.up"
105 + variant="primary"
106 + disabled={!canSend}
107 + onPress={() => void send()}
108 + />
109 + );
110 +
111 + return (
112 + <Animated.View
113 + onLayout={(event) => props.onHeightChange(event.nativeEvent.layout.height)}
114 + className={Platform.OS === "android" ? "bg-screen px-[12px]" : "px-[12px]"}
115 + style={{ paddingTop: 6, paddingBottom: props.bottomInset + COMPOSER_BOTTOM_GUTTER }}
116 + >
117 + <View
118 + className={
119 + Platform.OS === "android"
120 + ? "hidden"
121 + : "absolute inset-0 bg-linear-to-b from-screen/0 via-screen/60 to-screen/90"
122 + }
123 + pointerEvents="none"
124 + />
125 + <View className="w-full self-center" style={{ maxWidth: props.contentMaxWidth }}>
126 + <ComposerSurface
127 + animateLayout={false}
128 + style={{
129 + borderRadius: chrome.borderRadius,
130 + borderCurve: "circular",
131 + overflow: "hidden",
132 + paddingVertical: chrome.paddingVertical,
133 + }}
134 + >
135 + <ComposerDictationError
136 + error={voiceInput.state.phase === "error" ? voiceInput.state.error : null}
137 + onDismiss={voiceInput.cancel}
138 + />
139 + {props.blocked !== null ? (
140 + <View className="h-[44px] flex-row items-center">
141 + <Text
142 + className="min-w-0 flex-1 text-base text-foreground-muted"
143 + style={{ paddingLeft: EDITOR_LEADING_INSET }}
144 + numberOfLines={1}
145 + ellipsizeMode="tail"
146 + >
147 + {props.blocked}
148 + </Text>
149 + {sendButton}
150 + </View>
151 + ) : (
152 + <>
153 + <View onLayout={compactEditor.onRowLayout}>
154 + <ComposerDictationDraftContent
155 + className="flex-row items-end"
156 + compact
157 + hidden={dictating}
158 + >
159 + <View style={{ width: EDITOR_LEADING_INSET - 8 }} />
160 + <Animated.View
161 + className="min-w-0 flex-1"
162 + onLayout={compactEditor.onEditorLayout}
163 + style={[
164 + { minWidth: compactEditor.isExpanded ? 0 : INLINE_EDITOR_MIN_WIDTH },
165 + compactEditor.containerStyle,
166 + compactEditor.isExpanded ? { flex: 0, width: 0 } : undefined,
167 + ]}
168 + />
169 + {/* TalkBack orders siblings by position; outside this row the editor reads after Send. */}
170 + <Animated.View
171 + style={[compactEditor.editorStyle, dictating ? { display: "none" } : undefined]}
172 + >
173 + <ComposerEditor
174 + ref={editorRef}
175 + multiline
176 + value={draft}
177 + readOnly={locked}
178 + selection={selection}
179 + onChangeText={(text) => {
180 + if (!locked) changeDraft(text);
181 + }}
182 + onSelectionChange={setSelection}
183 + placeholder="Leave a comment"
184 + onFocus={() => {
185 + setFocused(true);
186 + props.onFocusChange(true);
187 + }}
188 + onBlur={() => {
189 + setFocused(false);
190 + props.onFocusChange(false);
191 + }}
192 + onSubmit={() => void send()}
193 + submitTitle="Comment"
194 + {...compactEditor.editorProps}
195 + textStyle={textStyle}
196 + />
197 + </Animated.View>
198 + <View
199 + className="min-w-0 shrink flex-row items-center"
200 + style={
201 + compactEditor.isExpanded ? { flex: 1, justifyContent: "flex-end" } : undefined
202 + }
203 + >
204 + <ComposerDictationStartAction
205 + size={chrome.controlSize}
206 + state={voiceInput.state}
207 + isAvailable={voiceInput.isAvailable}
208 + disabled={locked}
209 + onStart={voiceInput.start}
210 + onCancel={voiceInput.cancel}
211 + />
212 + {sendButton}
213 + </View>
214 + </ComposerDictationDraftContent>
215 + </View>
216 + <Animated.View
217 + accessibilityElementsHidden={!dictating}
218 + collapsable={false}
219 + importantForAccessibility={dictating ? "auto" : "no-hide-descendants"}
220 + pointerEvents={dictating ? "auto" : "none"}
221 + style={{ position: "absolute", bottom: chrome.paddingVertical, left: 0, right: 0 }}
222 + >
223 + <ComposerDictationToolbar showsDictation={dictating} visible={dictating}>
224 + <ComposerToolbarRow
225 + paddingBottom={0}
226 + paddingHorizontal={0}
227 + paddingTop={0}
228 + style={{ gap: 0 }}
229 + >
230 + <ComposerDictationCancelAction
231 + size={chrome.controlSize}
232 + presentation={voicePresentation}
233 + onCancel={voiceInput.cancel}
234 + />
235 + <ComposerDictationStatus
236 + audioLevels={voiceInput.audioLevels}
237 + elapsedSeconds={voiceInput.elapsedSeconds}
238 + phase={voiceInput.state.phase}
239 + presentation={voicePresentation}
240 + />
241 + <View className="shrink-0 flex-row items-center">
242 + <ComposerDictationPrimaryAction
243 + size={chrome.controlSize}
244 + state={voiceInput.state}
245 + presentation={voicePresentation}
246 + isAvailable={voiceInput.isAvailable}
247 + disabled={locked}
248 + onStart={voiceInput.start}
249 + onConfirm={voiceInput.stop}
250 + onCancel={voiceInput.cancel}
251 + />
252 + {voicePresentation.showsSend ? sendButton : null}
253 + </View>
254 + </ComposerToolbarRow>
255 + </ComposerDictationToolbar>
256 + </Animated.View>
257 + </>
258 + )}
259 + </ComposerSurface>
260 + </View>
261 + </Animated.View>
262 + );
263 +}
apps/mobile/src/features/issues/IssueEditScreen.tsx new
+99
@@ -0,0 +1,99 @@
1 +import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
2 +import { useRef, useState } from "react";
3 +
4 +import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/AppText";
5 +import { Button } from "../../components/ui/Button";
6 +import { issueEnvironment } from "../../state/issues";
7 +import { useEnvironmentQuery } from "../../state/query";
8 +import { useAtomCommand } from "../../state/use-atom-command";
9 +import { PullRequestSheetContent } from "../pull-requests/PullRequestSheetContent";
10 +import { issueTarget, type IssueParams } from "./issueParams";
11 +import { issueCommandError, useIssueAccess } from "./issuePresentation";
12 +
13 +type IssueEditParams = IssueParams & { readonly field: "title" | "body" };
14 +
15 +export function IssueEditScreen({ route }: StaticScreenProps<IssueEditParams>) {
16 + const params = route.params;
17 + const navigation = useNavigation();
18 + const target = issueTarget(params);
19 + const detailQuery = useEnvironmentQuery(issueEnvironment.detail(target));
20 + const detail = detailQuery.data;
21 + const access = useIssueAccess(params, detail);
22 + const update = useAtomCommand(issueEnvironment.update, { reportFailure: false });
23 + const isTitle = params.field === "title";
24 + const original = detail ? (isTitle ? detail.title : detail.body) : null;
25 + const [draft, setDraft] = useState<string | null>(null);
26 + const value = draft ?? original ?? "";
27 + const [busy, setBusy] = useState(false);
28 + const [error, setError] = useState<string | null>(null);
29 + const inFlight = useRef(false);
30 + const allowed = access?.edit === true;
31 + const unchanged = draft === null || draft === original;
32 + const invalid = isTitle && value.trim().length === 0;
33 + const save = async () => {
34 + if (!allowed || unchanged || invalid || inFlight.current) return;
35 + inFlight.current = true;
36 + setBusy(true);
37 + setError(null);
38 + const failure = issueCommandError(
39 + await update({
40 + ...target,
41 + input: { ...target.input, ...(isTitle ? { title: value.trim() } : { body: value }) },
42 + }),
43 + );
44 + inFlight.current = false;
45 + setBusy(false);
46 + if (failure !== null) {
47 + setError(failure);
48 + return;
49 + }
50 + navigation.goBack();
51 + };
52 + return (
53 + <PullRequestSheetContent
54 + busy={busy}
55 + title={isTitle ? "Edit title" : "Edit description"}
56 + subtitle={`${detail?.displayKey ?? params.issueKey} · ${params.scope}`}
57 + footer={
58 + <Button
59 + fullWidth
60 + tone="contrast"
61 + label={busy ? "Saving…" : "Save"}
62 + loading={busy}
63 + disabled={!allowed || unchanged || invalid || original === null}
64 + onPress={() => void save()}
65 + />
66 + }
67 + >
68 + <TextInput
69 + multiline={!isTitle}
70 + editable={!busy && original !== null}
71 + autoFocus
72 + accessibilityLabel={isTitle ? "Issue title" : "Issue description"}
73 + placeholder={isTitle ? "Title" : "Write in Markdown…"}
74 + placeholderTextColorClassName="accent-foreground-muted"
75 + maxLength={isTitle ? 1024 : 65536}
76 + value={value}
77 + onChangeText={setDraft}
78 + returnKeyType={isTitle ? "done" : undefined}
79 + onSubmitEditing={isTitle ? () => void save() : undefined}
80 + className={
81 + isTitle
82 + ? "min-h-12 rounded-[20px] bg-grouped-card px-4 text-base text-foreground"
83 + : "min-h-48 rounded-[20px] bg-grouped-card p-4 text-base text-foreground"
84 + }
85 + style={isTitle ? undefined : { textAlignVertical: "top" }}
86 + />
87 + {detail && !allowed ? (
88 + <Text className="text-xs text-foreground-muted">
89 + {access?.blocked ?? "You can't edit this issue."}
90 + </Text>
91 + ) : null}
92 + {error || detailQuery.error ? (
93 + <Text selectable className="text-sm text-danger-foreground">
94 + {error ?? detailQuery.error}
95 + </Text>
96 + ) : null}
97 + </PullRequestSheetContent>
98 + );
99 +}
apps/mobile/src/features/issues/IssueLabelsScreen.tsx new
+99
@@ -0,0 +1,99 @@
1 +import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
2 +import { useAtom } from "@effect/atom-react";
3 +import {
4 + issueLabelsAfterPicks,
5 + issuePicksFor,
6 + issueWriteAfterPicks,
7 + noIssuePicks,
8 +} from "@t3tools/client-runtime/issue-selection";
9 +import { isSelected, toggleSelection } from "@t3tools/client-runtime/pull-request-selection";
10 +import type { IssueLabelCandidate } from "@t3tools/contracts";
11 +import { useEffect, useState } from "react";
12 +
13 +import * as Dialog from "../../components/ui/Dialog";
14 +import { issueEnvironment } from "../../state/issues";
15 +import { useEnvironmentQuery } from "../../state/query";
16 +import { useAtomCommand } from "../../state/use-atom-command";
17 +import { PullRequestLabelDot } from "../pull-requests/PullRequestLabelDot";
18 +import { pullRequestLabelColor } from "../pull-requests/pullRequestList";
19 +import { IssueCandidatesSheet } from "./IssueCandidatesSheet";
20 +import { issueParamsKey, issueTarget, type IssueParams } from "./issueParams";
21 +import { issueLabelPicksFamily } from "./issuePicks";
22 +import { issueCommandError, useIssueAccess } from "./issuePresentation";
23 +
24 +export function IssueLabelsScreen({ route }: StaticScreenProps<IssueParams>) {
25 + const navigation = useNavigation();
26 + const target = issueTarget(route.params);
27 + const detail = useEnvironmentQuery(issueEnvironment.detail(target)).data;
28 + const access = useIssueAccess(route.params, detail);
29 + const result = useEnvironmentQuery(issueEnvironment.candidates(target));
30 + const update = useAtomCommand(issueEnvironment.update, { reportFailure: false });
31 + const [query, setQuery] = useState("");
32 + const [picks, setPicks] = useAtom(issueLabelPicksFamily(issueParamsKey(route.params)));
33 + // Picks against an older read are dropped when the sheet opens, and kept across a read while open.
34 + const [openedWith] = useState(detail);
35 + const current = detail
36 + ? issuePicksFor(picks, detail, detail !== openedWith)
37 + : noIssuePicks<IssueLabelCandidate>();
38 + const draft = current.draft;
39 + const allowed = access?.labels === true;
40 + const applied = new Set(detail?.labels.map((label) => label.name));
41 + const needle = query.trim().toLowerCase();
42 + // Host order, not applied-first: re-sorting on toggle would move the row out from under a tap.
43 + const candidates = (result.data?.labels ?? []).filter((label) =>
44 + `${label.name} ${label.description ?? ""}`.toLowerCase().includes(needle),
45 + );
46 + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- picks are sent when the sheet leaves the navigation stack, however it is dismissed
47 + useEffect(
48 + () =>
49 + navigation.addListener("beforeRemove", () => {
50 + if (!detail) return;
51 + const labels = issueWriteAfterPicks(
52 + issueLabelsAfterPicks(detail, draft),
53 + detail.labels.map((label) => label.name),
54 + current.written,
55 + );
56 + if (labels === null) return;
57 + setPicks({ ...current, written: labels });
58 + void update({ ...target, input: { ...target.input, labels } }).then((response) => {
59 + const failure = issueCommandError(response);
60 + if (failure === null) return;
61 + setPicks(noIssuePicks());
62 + Dialog.alert("Couldn't change labels", failure);
63 + });
64 + }),
65 + [navigation, detail, draft, current, setPicks, update, target],
66 + );
67 + return (
68 + <IssueCandidatesSheet
69 + title="Labels"
70 + noun="labels"
71 + query={query}
72 + onQueryChange={setQuery}
73 + candidates={candidates.map((label) => ({
74 + key: label.name,
75 + title: label.name,
76 + ...(label.description ? { subtitle: label.description } : {}),
77 + leading: <PullRequestLabelDot color={pullRequestLabelColor(label.color)} />,
78 + // Sent when the sheet closes; a failure puts the tracker's answer back.
79 + selected: isSelected(draft, label.name, applied.has(label.name)),
80 + }))}
81 + allowed={allowed}
82 + notice={
83 + detail && !allowed
84 + ? (access?.blocked ?? "Changing labels needs triage access on this tracker.")
85 + : null
86 + }
87 + pending={result.isPending && !result.data}
88 + loadError={result.data ? null : result.error}
89 + onRetry={result.refresh}
90 + truncated={result.data?.truncated === true}
91 + onToggle={(name) => {
92 + const label = candidates.find((entry) => entry.name === name);
93 + if (label) {
94 + setPicks({ ...current, draft: toggleSelection(draft, name, label, applied.has(name)) });
95 + }
96 + }}
97 + />
98 + );
99 +}
apps/mobile/src/features/issues/IssueListRow.tsx new
+102
@@ -0,0 +1,102 @@
1 +import type { EnvironmentIssueEntry } from "@t3tools/client-runtime/issue-list";
2 +import { memo } from "react";
3 +import { Pressable, View } from "react-native";
4 +
5 +import { RelativeTime } from "../../components/RelativeTime";
6 +import { SymbolView } from "../../components/ui/AppSymbol";
7 +import { AppText as Text } from "../../components/ui/AppText";
8 +import { cn } from "../../lib/cn";
9 +import { ListRowLabel } from "../pull-requests/PullRequestListRow";
10 +import { PullRequestAvatar } from "../pull-requests/PullRequestPresentation";
11 +import {
12 + selectedThreadRowColors,
13 + THREAD_LIST_V2_SIDEBAR_ROW_CONTAINER_STYLE,
14 + THREAD_LIST_V2_SIDEBAR_ROW_STYLE,
15 +} from "../threads/thread-list-v2-row-appearance";
16 +import { issueStatus } from "./issuePresentation";
17 +
18 +export const IssueListRow = memo(function IssueListRow(props: {
19 + readonly item: EnvironmentIssueEntry;
20 + readonly onSelect: (item: EnvironmentIssueEntry) => void;
21 + readonly selected: boolean;
22 + readonly sidebar: boolean;
23 +}) {
24 + const { item } = props;
25 + const foreground = props.selected
26 + ? selectedThreadRowColors.foregroundClassName
27 + : props.sidebar
28 + ? "text-drawer-foreground"
29 + : "text-foreground";
30 + const muted = props.selected
31 + ? selectedThreadRowColors.mutedForegroundClassName
32 + : props.sidebar
33 + ? "text-drawer-foreground-muted"
34 + : "text-foreground-muted";
35 + const status = issueStatus(item.state);
36 + return (
37 + <View style={props.sidebar ? THREAD_LIST_V2_SIDEBAR_ROW_CONTAINER_STYLE : undefined}>
38 + <Pressable
39 + accessibilityRole="button"
40 + accessibilityState={{ selected: props.selected }}
41 + accessibilityLabel={`Issue ${item.displayKey}, ${item.title}, ${status.label}, by ${item.author?.login ?? "unknown author"}${item.labels.length ? `, ${item.labels.map((label) => label.name).join(", ")}` : ""}${item.commentCount ? `, ${item.commentCount} comments` : ""}`}
42 + onPress={() => props.onSelect(item)}
43 + style={props.sidebar ? THREAD_LIST_V2_SIDEBAR_ROW_STYLE : undefined}
44 + className={cn(
45 + "flex-row gap-3 overflow-hidden",
46 + !props.sidebar && "px-4 active:bg-row-hover",
47 + props.sidebar && "bg-drawer",
48 + props.sidebar && !props.selected && "active:bg-thread-hover",
49 + props.selected && "bg-thread-selected",
50 + )}
51 + >
52 + <View className={cn("self-start", props.sidebar ? "pt-0.5" : "pt-2.5")}>
53 + <SymbolView name={status.icon} size={20} tintColorClassName={status.tint} />
54 + </View>
55 + <View
56 + className={cn(
57 + "min-w-0 flex-1 gap-1",
58 + !props.sidebar && "border-b border-border-subtle py-2.5",
59 + )}
60 + >
61 + <View className="flex-row items-center gap-1.5">
62 + <PullRequestAvatar actor={item.author} size={16} />
63 + <Text className={cn("min-w-0 flex-1 text-xs", muted)} numberOfLines={1}>
64 + {/* A Linear key already names its team; a git host's number needs the repository. */}
65 + {item.displayKey.startsWith(`${item.scope}-`)
66 + ? item.displayKey
67 + : `${item.scope} ${item.displayKey}`}
68 + </Text>
69 + <Text className={cn("text-2xs tabular-nums", muted)}>
70 + <RelativeTime timestamp={item.updatedAt} />
71 + </Text>
72 + </View>
73 + <Text
74 + className={cn("text-base leading-5 font-t3-medium", foreground)}
75 + numberOfLines={2}
76 + ellipsizeMode="tail"
77 + >
78 + {item.title}
79 + </Text>
80 + {item.labels.length > 0 || item.commentCount > 0 ? (
81 + <View className="flex-row items-center gap-1.5">
82 + <View className="min-w-0 flex-1 flex-row items-center gap-1">
83 + {item.labels.slice(0, 2).map((label) => (
84 + <ListRowLabel key={label.name} label={label} textClassName={muted} />
85 + ))}
86 + {item.labels.length > 2 ? (
87 + <Text className={cn("shrink-0 text-2xs", muted)}>+{item.labels.length - 2}</Text>
88 + ) : null}
89 + </View>
90 + {item.commentCount > 0 ? (
91 + <View className="shrink-0 flex-row items-center gap-1">
92 + <SymbolView name="bubble.left" size={12} tintColorClassName="accent-icon-muted" />
93 + <Text className={cn("text-2xs tabular-nums", muted)}>{item.commentCount}</Text>
94 + </View>
95 + ) : null}
96 + </View>
97 + ) : null}
98 + </View>
99 + </Pressable>
100 + </View>
101 + );
102 +});
apps/mobile/src/features/issues/IssueRouteScreen.tsx new
+685
@@ -0,0 +1,685 @@
1 +import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
2 +import {
3 + issueCloseReasonLabel,
4 + issueEventSentence,
5 +} from "@t3tools/client-runtime/issue-presentation";
6 +import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
7 +import { prependIssueComments } from "@t3tools/client-runtime/state/issues";
8 +import type {
9 + IssueComment,
10 + IssueDetail,
11 + IssueEvent,
12 + IssueLinkedPullRequest,
13 + IssueReaction,
14 + IssueState,
15 + IssueSummary,
16 +} from "@t3tools/contracts";
17 +import { AsyncResult } from "effect/reactivity";
18 +import { useState } from "react";
19 +import { Linking, Platform, Pressable, Share, View } from "react-native";
20 +import { KeyboardStickyView } from "react-native-keyboard-controller";
21 +
22 +import { RelativeTime } from "../../components/RelativeTime";
23 +import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
24 +import { AppBar } from "../../components/ui/AppBar";
25 +import { SymbolView } from "../../components/ui/AppSymbol";
26 +import { AppText as Text } from "../../components/ui/AppText";
27 +import { Button } from "../../components/ui/Button";
28 +import { Chip } from "../../components/ui/Chip";
29 +import { EmptyState } from "../../components/ui/EmptyState";
30 +import { Menu } from "../../components/ui/Menu";
31 +import { RefreshControl } from "../../components/ui/RefreshControl";
32 +import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
33 +import { useComposerBottomInset } from "../../components/ComposerSurface";
34 +import { ANDROID_READING_MAX_WIDTH, CHAT_CONTENT_MAX_WIDTH } from "../../lib/layout";
35 +import { relativeTime } from "../../lib/time";
36 +import { deriveBottomControlInsets, type NativeLayoutMetrics } from "../../lib/reserved-regions";
37 +import { NativeLayoutObserver } from "../../native/NativeLayoutObserver";
38 +import { useNativeWorkspaceColumnsSupported } from "../../native/NativeWorkspaceColumns";
39 +import { useDeviceType, useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
40 +import { NativeScrollView } from "../../native/NativeScrollViewMarker";
41 +import { issueEnvironment } from "../../state/issues";
42 +import { useEnvironmentQuery } from "../../state/query";
43 +import { useAtomCommand } from "../../state/use-atom-command";
44 +import { usePullToRefresh } from "../../state/use-pull-to-refresh";
45 +import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
46 +import { useAndroidWorkspaceBack } from "../layout/workspace/useAndroidWorkspaceNavigation";
47 +import { PullRequestDescription } from "../pull-requests/PullRequestDescription";
48 +import {
49 + PullRequestMarkdown,
50 + PullRequestMarkdownRepository,
51 +} from "../pull-requests/PullRequestMarkdown";
52 +import { PullRequestAvatar } from "../pull-requests/PullRequestPresentation";
53 +import { ReactionPills } from "../pull-requests/PullRequestReactions";
54 +import { PullRequestSectionHeading } from "../pull-requests/PullRequestSectionHeading";
55 +import { pullRequestStatus } from "../pull-requests/pullRequestStatus";
56 +import { usePullRequestConnected } from "../pull-requests/usePullRequestConnected";
57 +import { IssueCommentComposer } from "./IssueCommentComposer";
58 +import { issueIdentity, issueParamsKey, issueTarget, type IssueParams } from "./issueParams";
59 +import {
60 + IssueLabelPill,
61 + issueCommandError,
62 + issueStatus,
63 + useIssueAccess,
64 +} from "./issuePresentation";
65 +
66 +type IssueAccess = NonNullable<ReturnType<typeof useIssueAccess>>;
67 +
68 +function IssueReactions(props: {
69 + readonly params: IssueParams;
70 + readonly reactions: ReadonlyArray<IssueReaction>;
71 + readonly canReact: boolean;
72 + /** Absent reacts to the issue itself. */
73 + readonly subjectId?: string;
74 +}) {
75 + const target = issueTarget(props.params);
76 + const react = useAtomCommand(issueEnvironment.react, { reportFailure: false });
77 + if (props.reactions.length === 0 && !props.canReact) return null;
78 + return (
79 + <View className="flex-row flex-wrap items-center gap-1.5">
80 + <ReactionPills
81 + reactions={props.reactions}
82 + canReact={props.canReact}
83 + onReact={async (content, reacted) =>
84 + !AsyncResult.isFailure(
85 + await react({
86 + ...target,
87 + input: {
88 + ...target.input,
89 + ...(props.subjectId === undefined ? {} : { subjectId: props.subjectId }),
90 + content,
91 + reacted,
92 + },
93 + }),
94 + )
95 + }
96 + />
97 + </View>
98 + );
99 +}
100 +
101 +function IssueStateControl(props: {
102 + readonly state: IssueState;
103 + readonly detail: IssueDetail | null;
104 + readonly states: ReadonlyArray<IssueState>;
105 + readonly busy: boolean;
106 + readonly onMove: (state: string, closeReason?: string) => void;
107 +}) {
108 + const status = issueStatus(props.state);
109 + const reasons = props.detail?.capabilities.closeReasons ?? [];
110 + const moves = props.states.flatMap(
111 + (
112 + state,
113 + ): ReadonlyArray<{
114 + readonly id: string;
115 + readonly state: string;
116 + readonly reason?: string;
117 + readonly title: string;
118 + }> =>
119 + state.category === "closed" && reasons.length > 0
120 + ? reasons.map((reason) => ({
121 + // No NUL separator: it ends the native string, and UIKit drops a duplicate id.
122 + id: `${state.name}:${reason}`,
123 + state: state.name,
124 + reason,
125 + title: `${state.name === "closed" ? "Close" : state.name} as ${issueCloseReasonLabel(reason).toLowerCase()}`,
126 + }))
127 + : [
128 + {
129 + id: state.name,
130 + state: state.name,
131 + title:
132 + state.category === "open" && state.name === "open"
133 + ? "Reopen"
134 + : state.name === "closed"
135 + ? "Close"
136 + : `Move to ${state.name}`,
137 + },
138 + ],
139 + );
140 + const trigger = (
141 + <Pressable
142 + accessibilityRole={moves.length ? "button" : undefined}
143 + accessibilityLabel={`Issue state, ${status.label}`}
144 + disabled={!moves.length || props.busy}
145 + className="min-h-8 flex-row items-center gap-1.5 active:opacity-70"
146 + >
147 + <SymbolView name={status.icon} size={14} tintColorClassName={status.tint} />
148 + <Text className={`text-xs font-t3-medium ${status.text}`}>{status.label}</Text>
149 + {moves.length ? (
150 + <SymbolView name="chevron.down" size={9} tintColorClassName="accent-icon-muted" />
151 + ) : null}
152 + </Pressable>
153 + );
154 + if (!moves.length) return trigger;
155 + return (
156 + // As wide as the trigger: iOS anchors the menu to this view, not to the text inside it.
157 + <View className="self-start">
158 + <Menu
159 + title="Issue state"
160 + actions={moves.map((move) => ({ id: move.id, title: move.title }))}
161 + onPressAction={({ nativeEvent }) => {
162 + const move = moves.find((candidate) => candidate.id === nativeEvent.event);
163 + if (move) props.onMove(move.state, move.reason);
164 + }}
165 + >
166 + {trigger}
167 + </Menu>
168 + </View>
169 + );
170 +}
171 +
172 +function IssueIdentity(props: {
173 + readonly issue: IssueSummary;
174 + readonly detail: IssueDetail | null;
175 + readonly access: IssueAccess | null;
176 + readonly busy: boolean;
177 + readonly onMove: (state: string, closeReason?: string) => void;
178 + readonly onEditLabels: () => void;
179 + readonly onEditAssignees: () => void;
180 +}) {
181 + const { issue, access } = props;
182 + const canLabel = access?.labels === true;
183 + const canAssign = access?.assignees === true;
184 + return (
185 + <View className="gap-3">
186 + <IssueStateControl
187 + state={issue.state}
188 + detail={props.detail}
189 + states={access?.states ?? []}
190 + busy={props.busy}
191 + onMove={props.onMove}
192 + />
193 + <Text selectable className="text-xl font-t3-bold leading-7">
194 + {issue.title}
195 + </Text>
196 + <View className="flex-row items-center gap-2">
197 + <PullRequestAvatar actor={issue.author} size={20} />
198 + <Text className="min-w-0 flex-1 text-xs font-t3-medium" numberOfLines={1}>
199 + {issue.author?.login ?? "Unknown author"}
200 + </Text>
201 + <Text className="shrink text-right text-2xs text-foreground-muted" numberOfLines={1}>
202 + {issue.closedAt ? (
203 + <>
204 + Closed <RelativeTime timestamp={issue.closedAt} /> ago
205 + </>
206 + ) : (
207 + <>
208 + Opened <RelativeTime timestamp={issue.createdAt} /> ago
209 + </>
210 + )}
211 + </Text>
212 + </View>
213 + {issue.labels.length || canLabel ? (
214 + <View className="flex-row flex-wrap gap-2">
215 + {issue.labels.map((label) => (
216 + <IssueLabelPill key={label.name} label={label} />
217 + ))}
218 + {canLabel ? (
219 + <Chip
220 + label={issue.labels.length ? "Edit" : "Add labels"}
221 + icon="tag"
222 + size="small"
223 + accessibilityLabel="Edit labels"
224 + onPress={props.onEditLabels}
225 + />
226 + ) : null}
227 + </View>
228 + ) : null}
229 + <View className="flex-row flex-wrap items-center gap-2">
230 + <Text className="text-xs text-foreground-muted">Assignees</Text>
231 + {issue.assignees.length === 0 ? (
232 + <Text className="text-xs text-foreground-muted">none</Text>
233 + ) : null}
234 + {issue.assignees.map((actor) => (
235 + <View key={actor.login} className="flex-row items-center gap-1.5">
236 + <PullRequestAvatar actor={actor} size={18} />
237 + <Text className="text-xs font-t3-medium">{actor.login}</Text>
238 + </View>
239 + ))}
240 + {canAssign ? (
241 + <Chip
242 + label={issue.assignees.length ? "Edit" : "Assign"}
243 + icon="person.badge.plus"
244 + size="small"
245 + accessibilityLabel="Edit assignees"
246 + onPress={props.onEditAssignees}
247 + />
248 + ) : null}
249 + </View>
250 + </View>
251 + );
252 +}
253 +
254 +function LinkedPullRequests(props: {
255 + readonly params: IssueParams;
256 + readonly links: ReadonlyArray<IssueLinkedPullRequest>;
257 +}) {
258 + const navigation = useNavigation();
259 + // Only a git host's tracker shares its host with the change request it links.
260 + const sameHost = sourceControlClients.find(props.params.tracker) !== undefined;
261 + return (
262 + <View className="gap-2">
263 + <PullRequestSectionHeading>Linked pull requests</PullRequestSectionHeading>
264 + {props.links.map((link) => {
265 + const status = pullRequestStatus(link);
266 + return (
267 + <Pressable
268 + key={`${link.repository}#${link.number}`}
269 + accessibilityRole="button"
270 + accessibilityLabel={`${status.label} pull request ${link.number}, ${link.title}`}
271 + onPress={() =>
272 + sameHost
273 + ? navigation.dispatch(
274 + StackActions.push("PullRequest", {
275 + environmentId: props.params.environmentId,
276 + projectId: props.params.projectId,
277 + repository: link.repository,
278 + number: link.number,
279 + ...(props.params.host ? { host: props.params.host } : {}),
280 + }),
281 + )
282 + : void Linking.openURL(link.url)
283 + }
284 + className="flex-row items-center gap-2 rounded-2xl bg-grouped-card p-3 active:opacity-70"
285 + >
286 + <SymbolView name={status.icon} size={15} tintColorClassName={status.tint} />
287 + <View className="min-w-0 flex-1">
288 + <Text className="text-sm" numberOfLines={2}>
289 + {link.title}
290 + </Text>
291 + <Text className="font-mono text-2xs text-foreground-muted" numberOfLines={1}>
292 + {link.repository}#{link.number}
293 + {link.closesIssue ? " · closes" : ""}
294 + </Text>
295 + </View>
296 + <SymbolView name="chevron.right" size={12} tintColorClassName="accent-icon-muted" />
297 + </Pressable>
298 + );
299 + })}
300 + </View>
301 + );
302 +}
303 +
304 +function IssueCommentCard(props: {
305 + readonly params: IssueParams;
306 + readonly comment: IssueComment;
307 + readonly canReact: boolean;
308 +}) {
309 + const { comment } = props;
310 + return (
311 + <View className="gap-3 rounded-2xl bg-grouped-card p-3">
312 + <View className="flex-row items-center gap-2">
313 + <PullRequestAvatar actor={comment.author} size={22} />
314 + <Text className="min-w-0 flex-1 text-sm font-t3-medium" numberOfLines={1}>
315 + {comment.author?.login ?? "Unknown author"}
316 + </Text>
317 + <Text className="text-2xs text-foreground-tertiary">{relativeTime(comment.createdAt)}</Text>
318 + </View>
319 + <PullRequestMarkdown markdown={comment.body} />
320 + {comment.reactions !== undefined ? (
321 + <IssueReactions
322 + params={props.params}
323 + reactions={comment.reactions}
324 + canReact={props.canReact}
325 + subjectId={comment.id}
326 + />
327 + ) : null}
328 + </View>
329 + );
330 +}
331 +
332 +function IssueEventRow({ event }: { readonly event: IssueEvent }) {
333 + return (
334 + <View className="flex-row items-center gap-2 px-1">
335 + <PullRequestAvatar actor={event.actor} size={18} />
336 + <Text className="min-w-0 flex-1 text-xs text-foreground-muted">
337 + <Text className="text-xs font-t3-medium">{event.actor?.login ?? "Someone"}</Text>{" "}
338 + {issueEventSentence(event)}
339 + </Text>
340 + <Text className="text-2xs text-foreground-tertiary">{relativeTime(event.createdAt)}</Text>
341 + </View>
342 + );
343 +}
344 +
345 +function IssueLoadingBody() {
346 + return (
347 + <View className="gap-5" accessibilityLabel="Loading issue" accessibilityState={{ busy: true }}>
348 + <View className="gap-3">
349 + <PullRequestSectionHeading>Description</PullRequestSectionHeading>
350 + <View className="gap-3 py-1">
351 + <View className="h-4 w-full rounded bg-subtle-strong" />
352 + <View className="h-4 w-full rounded bg-subtle-strong" />
353 + <View className="h-4 w-3/4 rounded bg-subtle-strong" />
354 + </View>
355 + </View>
356 + <View className="gap-3">
357 + <PullRequestSectionHeading>Activity</PullRequestSectionHeading>
358 + <View className="h-20 rounded-2xl bg-subtle-strong" />
359 + <View className="h-20 rounded-2xl bg-subtle-strong" />
360 + </View>
361 + </View>
362 + );
363 +}
364 +
365 +// Selecting another issue reuses this route, so the draft, older comments and errors are keyed.
366 +export function IssueRouteScreen({ route }: StaticScreenProps<IssueParams>) {
367 + return <IssueRoute key={issueParamsKey(route.params)} params={route.params} />;
368 +}
369 +
370 +function IssueRoute({ params }: { readonly params: IssueParams }) {
371 + const identity = issueIdentity(params);
372 + const target = issueTarget(params);
373 + const navigation = useNavigation();
374 + const returnToList = useAndroidWorkspaceBack();
375 + const { layout } = useAdaptiveWorkspaceLayout();
376 + const composerBottomInset = useComposerBottomInset();
377 + const deviceType = useDeviceType();
378 + // The thread screen's composer host: the same metrics, so the same reserved regions and insets.
379 + const usesNativeWorkspaceColumns = useNativeWorkspaceColumnsSupported();
380 + const [screenMetrics, setScreenMetrics] = useState<NativeLayoutMetrics | null>(null);
381 + const columnMetrics = useNativeColumnLayoutMetrics();
382 + const controlInsets = deriveBottomControlInsets(
383 + usesNativeWorkspaceColumns ? columnMetrics : screenMetrics,
384 + );
385 + const [composerFocused, setComposerFocused] = useState(false);
386 + const connected = usePullRequestConnected(params.environmentId);
387 + const detailAtom = issueEnvironment.detail(target);
388 + const detailQuery = useEnvironmentQuery(detailAtom);
389 + const pullRefresh = usePullToRefresh(detailAtom);
390 + const detail = detailQuery.data;
391 + const issue: IssueSummary | null = detail ?? params.initialSummary ?? null;
392 + const access = useIssueAccess(params, detail);
393 +
394 + const loadComments = useAtomCommand(issueEnvironment.comments, { reportFailure: false });
395 + const postComment = useAtomCommand(issueEnvironment.comment, { reportFailure: false });
396 + const setState = useAtomCommand(issueEnvironment.setState, { reportFailure: false });
397 + const [older, setOlder] = useState<{
398 + readonly seed: string | null;
399 + readonly comments: ReadonlyArray<IssueComment>;
400 + readonly cursor: string | null;
401 + } | null>(null);
402 + const [busy, setBusy] = useState<"older" | "comment" | "state" | null>(null);
403 + const [error, setError] = useState<string | null>(null);
404 + const [composerHeight, setComposerHeight] = useState(0);
405 +
406 + // Older pages are tied to the cursor the detail was read with; a refreshed detail starts over.
407 + const olderComments = detail && older?.seed === detail.commentsCursor ? older.comments : [];
408 + const nextCursor = !detail
409 + ? null
410 + : older?.seed === detail.commentsCursor
411 + ? older.cursor
412 + : detail.commentsCursor;
413 + const timeline = detail
414 + ? [
415 + ...prependIssueComments(detail.comments, olderComments).map((comment) => ({
416 + key: `c:${comment.id}`,
417 + at: comment.createdAt,
418 + content: (
419 + <IssueCommentCard params={params} comment={comment} canReact={access?.react === true} />
420 + ),
421 + })),
422 + ...detail.events.map((event) => ({
423 + key: `e:${event.id}`,
424 + at: event.createdAt,
425 + content: <IssueEventRow event={event} />,
426 + })),
427 + ].sort((left, right) => Date.parse(left.at) - Date.parse(right.at))
428 + : [];
429 +
430 + const run = async (
431 + kind: NonNullable<typeof busy>,
432 + command: () => Promise<AsyncResult.AsyncResult<unknown, unknown>>,
433 + ) => {
434 + if (busy !== null) return false;
435 + setBusy(kind);
436 + setError(null);
437 + const failure = issueCommandError(await command());
438 + setBusy(null);
439 + setError(failure);
440 + return failure === null;
441 + };
442 + const loadOlder = async () => {
443 + if (!detail || nextCursor === null || busy !== null) return;
444 + setBusy("older");
445 + setError(null);
446 + const result = await loadComments({
447 + ...target,
448 + input: { ...target.input, cursor: nextCursor },
449 + });
450 + setBusy(null);
451 + if (AsyncResult.isFailure(result)) {
452 + setError("Older comments could not be read.");
453 + return;
454 + }
455 + setOlder({
456 + seed: detail.commentsCursor,
457 + comments: prependIssueComments(olderComments, result.value.comments),
458 + cursor: result.value.nextCursor,
459 + });
460 + };
461 + const submitComment = (body: string) =>
462 + access?.comment === true
463 + ? run("comment", () => postComment({ ...target, input: { ...target.input, body } }))
464 + : Promise.resolve(false);
465 + const moveTo = (state: string, closeReason?: string) =>
466 + void run("state", () =>
467 + setState({
468 + ...target,
469 + input: { ...target.input, state, ...(closeReason === undefined ? {} : { closeReason }) },
470 + }),
471 + );
472 +
473 + const showComposer = detail?.capabilities.comment === true;
474 + const commentBlocked =
475 + access?.comment === true ? null : (access?.blocked ?? "You cannot comment here.");
476 + const contentMaxWidth =
477 + Platform.OS === "android"
478 + ? ANDROID_READING_MAX_WIDTH
479 + : layout.usesSplitView
480 + ? CHAT_CONTENT_MAX_WIDTH
481 + : undefined;
482 + const url = issue?.url;
483 + return (
484 + <PullRequestMarkdownRepository
485 + params={{
486 + environmentId: params.environmentId,
487 + projectId: params.projectId,
488 + repository: params.scope,
489 + number: 0,
490 + }}
491 + changeRequest={detail ? { provider: detail.tracker, url: detail.url } : null}
492 + >
493 + <View className="flex-1 bg-screen">
494 + <AppBar
495 + title={issue?.displayKey ?? params.issueKey}
496 + subtitle={connected ? params.scope : `${params.scope} · Offline`}
497 + onBack={layout.usesSplitView ? undefined : returnToList}
498 + menus={[
499 + {
500 + title: "Issue actions",
501 + icon: "ellipsis",
502 + items: [
503 + ...(access?.edit
504 + ? [
505 + {
506 + id: "edit-title",
507 + title: "Edit title",
508 + icon: "pencil",
509 + onPress: () =>
510 + navigation.navigate("IssueEdit", { ...identity, field: "title" }),
511 + },
512 + {
513 + id: "edit-description",
514 + title: "Edit description",
515 + icon: "doc.text",
516 + onPress: () =>
517 + navigation.navigate("IssueEdit", { ...identity, field: "body" }),
518 + },
519 + ]
520 + : []),
521 + ...(url
522 + ? [
523 + {
524 + id: "open-on-host",
525 + title: "Open on the tracker",
526 + icon: "arrow.up.right",
527 + onPress: () => void Linking.openURL(url),
528 + },
529 + {
530 + id: "copy-link",
531 + title: "Copy link",
532 + icon: "link",
533 + onPress: () => copyTextWithHaptic(url, { target: "issue link" }),
534 + },
535 + {
536 + id: "share",
537 + title: "Share…",
538 + icon: "square.and.arrow.up",
539 + onPress: () =>
540 + // Android ignores `url`; iOS shows a `message` URL as plain text.
541 + void Share.share(
542 + Platform.OS === "ios" ? { url } : { message: url },
543 + ).catch(() => undefined),
544 + },
545 + ]
546 + : []),
547 + ],
548 + },
549 + ]}
550 + />
551 + {!usesNativeWorkspaceColumns ? <NativeLayoutObserver onChange={setScreenMetrics} /> : null}
552 + {/* Not a bare marker: Android wraps a refreshable scroll view, which the marker rejects. */}
553 + <NativeScrollView
554 + className="flex-1"
555 + contentInsetAdjustmentBehavior="automatic"
556 + keyboardShouldPersistTaps="handled"
557 + keyboardDismissMode="interactive"
558 + refreshControl={
559 + <RefreshControl
560 + refreshing={pullRefresh.refreshing}
561 + onRefresh={() => pullRefresh.onRefresh()}
562 + />
563 + }
564 + contentContainerStyle={{
565 + paddingHorizontal: 16,
566 + paddingTop: 8,
567 + paddingBottom: showComposer ? composerHeight + 16 : 24,
568 + }}
569 + >
570 + {!issue ? (
571 + detailQuery.error && !detailQuery.isPending ? (
572 + <EmptyState
573 + title="Couldn't load this issue"
574 + detail={detailQuery.error}
575 + variant="plain"
576 + />
577 + ) : (
578 + <AppActivityIndicator className="my-12" colorClassName="accent-icon" />
579 + )
580 + ) : (
581 + <View className="gap-5">
582 + <IssueIdentity
583 + issue={issue}
584 + detail={detail}
585 + access={access}
586 + busy={busy === "state"}
587 + onMove={moveTo}
588 + onEditLabels={() => navigation.navigate("IssueLabels", identity)}
589 + onEditAssignees={() => navigation.navigate("IssueAssignees", identity)}
590 + />
591 + {error || (detail && detailQuery.error) ? (
592 + <Text selectable className="text-sm text-danger-foreground">
593 + {error ?? detailQuery.error}
594 + </Text>
595 + ) : null}
596 + {!detail ? (
597 + detailQuery.error && !detailQuery.isPending ? (
598 + <EmptyState
599 + title="Couldn't load this issue"
600 + detail={detailQuery.error}
601 + variant="plain"
602 + />
603 + ) : (
604 + <IssueLoadingBody />
605 + )
606 + ) : (
607 + <>
608 + <PullRequestDescription
609 + markdown={detail.body}
610 + footer={
611 + detail.reactions !== undefined ? (
612 + <IssueReactions
613 + params={params}
614 + reactions={detail.reactions}
615 + canReact={access?.react === true}
616 + />
617 + ) : undefined
618 + }
619 + />
620 + {detail.linkedPullRequests.length > 0 ? (
621 + <LinkedPullRequests params={params} links={detail.linkedPullRequests} />
622 + ) : null}
623 + <View className="gap-3">
624 + <PullRequestSectionHeading>
625 + Activity
626 + {detail.commentCount > 0
627 + ? ` · ${detail.commentCount} ${detail.commentCount === 1 ? "comment" : "comments"}`
628 + : ""}
629 + </PullRequestSectionHeading>
630 + {nextCursor !== null ? (
631 + <Button
632 + label={busy === "older" ? "Loading…" : "Load older comments"}
633 + disabled={busy !== null}
634 + onPress={() => void loadOlder()}
635 + />
636 + ) : null}
637 + {timeline.length === 0 ? (
638 + <Text className="text-sm text-foreground-muted">
639 + Nothing has happened here yet.
640 + </Text>
641 + ) : null}
642 + {timeline.map((item) => (
643 + <View key={item.key}>{item.content}</View>
644 + ))}
645 + </View>
646 + </>
647 + )}
648 + </View>
649 + )}
650 + </NativeScrollView>
651 + {showComposer ? (
652 + <KeyboardStickyView
653 + // On the unfolded Duo the sidebar's search shares the keyboard; follow it only for ours.
654 + enabled={deviceType !== "duo-unfolded" || composerFocused}
655 + pointerEvents="box-none"
656 + style={{ position: "absolute", bottom: 0, left: 0, right: 0, top: 0 }}
657 + offset={{ closed: 0, opened: composerBottomInset }}
658 + >
659 + <View
660 + pointerEvents="box-none"
661 + style={{
662 + position: "absolute",
663 + bottom: controlInsets.bottom,
664 + left: controlInsets.left,
665 + right: controlInsets.right,
666 + }}
667 + >
668 + <IssueCommentComposer
669 + ownerKey={`issue-comment:${issueParamsKey(params)}`}
670 + label={issue?.displayKey ?? params.issueKey}
671 + blocked={commentBlocked}
672 + posting={busy === "comment"}
673 + bottomInset={composerBottomInset}
674 + contentMaxWidth={contentMaxWidth}
675 + onSubmit={submitComment}
676 + onHeightChange={setComposerHeight}
677 + onFocusChange={setComposerFocused}
678 + />
679 + </View>
680 + </KeyboardStickyView>
681 + ) : null}
682 + </View>
683 + </PullRequestMarkdownRepository>
684 + );
685 +}
apps/mobile/src/features/issues/IssuesScreen.tsx new
+388
@@ -0,0 +1,388 @@
1 +import { useAtomValue } from "@effect/atom-react";
2 +import { LegendList, type LegendListRef } from "@legendapp/list/react-native";
3 +import {
4 + continueIssuePage,
5 + groupIssues,
6 + holdIssuePages,
7 + type EnvironmentIssueEntry,
8 + type HeldIssuePage,
9 +} from "@t3tools/client-runtime/issue-list";
10 +import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
11 +import type {
12 + EnvironmentId,
13 + IssueInvolvement,
14 + IssueListInput,
15 + IssueListState,
16 +} from "@t3tools/contracts";
17 +import { AsyncResult } from "effect/reactivity";
18 +import { use, useRef, useState, type ReactNode } from "react";
19 +import { Keyboard, Platform, ScrollView, View } from "react-native";
20 +import { useSafeAreaInsets } from "react-native-safe-area-context";
21 +
22 +import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
23 +import { AppText as Text } from "../../components/ui/AppText";
24 +import { Button } from "../../components/ui/Button";
25 +import { EmptyState } from "../../components/ui/EmptyState";
26 +import { usePaneRole } from "../../components/ui/Pane";
27 +import { RefreshControl } from "../../components/ui/RefreshControl";
28 +import { useContentTopInset } from "../../components/ui/useBarInset";
29 +import { NativeScrollView } from "../../native/NativeScrollViewMarker";
30 +import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
31 +import { NativePrimaryColumnContext } from "../../native/v5-workspace-context";
32 +import { useProjects } from "../../state/entities";
33 +import { issueEnvironment, useIssueList } from "../../state/issues";
34 +import { useDebouncedValue } from "../../state/queries";
35 +import { environmentServerConfigsAtom } from "../../state/server";
36 +import { useAtomCommand } from "../../state/use-atom-command";
37 +import { useWorkspaceState } from "../../state/workspace";
38 +import { ListFilterMenu } from "../layout/workspace/ListFilterMenu";
39 +import { useSearchScrollRestoration } from "../layout/workspace/useSearchScrollRestoration";
40 +import { useSelectWorkspaceDetail } from "../layout/workspace/useSelectWorkspaceDetail";
41 +import { useWorkspaceTabs } from "../layout/workspace/WorkspaceTabsContext";
42 +import { issueParamsKey } from "./issueParams";
43 +import { IssueListRow } from "./IssueListRow";
44 +import type { PullRequestFilterMenu } from "../pull-requests/PullRequestListFilters";
45 +
46 +const DEFAULT_ISSUE_LIST_INPUT = { state: "open", involvement: "all", limit: 50 } as const;
47 +const STATES = {
48 + open: "Open",
49 + closed: "Closed",
50 + all: "All states",
51 +} as const satisfies Record<IssueListState, string>;
52 +const INVOLVEMENT = {
53 + all: "Everyone",
54 + assigned: "Assigned to you",
55 + authored: "Opened by you",
56 + mentioned: "Mentioning you",
57 +} as const satisfies Record<IssueInvolvement, string>;
58 +// A 12dp inset keeps 16dp chips concentric with Android's 28dp ScreenContent corner.
59 +const FILTER_ROW_STYLE =
60 + Platform.OS === "android"
61 + ? { paddingHorizontal: 12, paddingTop: 12, paddingBottom: 8, gap: 8 }
62 + : { paddingHorizontal: 16, paddingTop: 2, paddingBottom: 10, gap: 8 };
63 +
64 +function choices<Value extends string>(
65 + options: Readonly<Record<Value, string>>,
66 + selected: Value,
67 + /** Prefixes the ids, for a menu that holds more than one set of choices. */
68 + field?: string,
69 +) {
70 + return (Object.entries(options) as Array<[Value, string]>).map(([id, title]) => ({
71 + id: field ? `${field}:${id}` : id,
72 + title,
73 + state: id === selected ? ("on" as const) : ("off" as const),
74 + }));
75 +}
76 +
77 +const rowKey = (item: EnvironmentIssueEntry) =>
78 + issueParamsKey({
79 + environmentId: item.environmentId,
80 + projectId: item.projectId,
81 + host: item.host,
82 + scope: item.scope,
83 + issueKey: item.key,
84 + });
85 +
86 +export function IssuesScreen(
87 + props: {
88 + readonly sidebar?: boolean;
89 + readonly selectedIssueKey?: string | null;
90 + /** Places the list under a header of the caller's (the Android toolbar). */
91 + readonly renderFrame?: (filters: PullRequestFilterMenu | null, list: ReactNode) => ReactNode;
92 + } = {},
93 +) {
94 + const primaryColumn = use(NativePrimaryColumnContext);
95 + const workspace = useWorkspaceTabs()!;
96 + const { environments } = useWorkspaceState();
97 + const configs = useAtomValue(environmentServerConfigsAtom);
98 + const projects = useProjects();
99 + const insets = useSafeAreaInsets();
100 + const contentTopInset = useContentTopInset();
101 + // UIKit insets the list by its column's safe area, which this context can report as 0.
102 + const columnSafeBottom = useNativeColumnLayoutMetrics()?.safeArea.bottom;
103 + const bottomSafeArea =
104 + Platform.OS === "ios" ? (columnSafeBottom ?? insets.bottom) : insets.bottom;
105 + const listRef = useRef<LegendListRef>(null);
106 + const tab = workspace.state.tabs.issues;
107 + const [initialScrollOffset] = useState(() => workspace.getScrollOffset("issues"));
108 + useSearchScrollRestoration(tab.searchMode, () => {
109 + void listRef.current?.scrollToOffset({
110 + offset: tab.scrollOffset - contentTopInset,
111 + animated: false,
112 + });
113 + });
114 + const debouncedQuery = useDebouncedValue(tab.query.trim(), 300);
115 + const query = tab.searchMode === "resting" ? "" : debouncedQuery;
116 + const [state, setState] = useState<IssueListState>("open");
117 + const [involvement, setInvolvement] = useState<IssueInvolvement>("all");
118 + const listInput: IssueListInput = {
119 + ...DEFAULT_ISSUE_LIST_INPUT,
120 + state,
121 + involvement,
122 + ...(query ? { query } : {}),
123 + };
124 + const capable = environments.filter(
125 + (environment) =>
126 + configs.get(environment.environmentId)?.environment.capabilities.issues === true,
127 + );
128 + const connected = capable.filter((environment) => environment.connectionState === "connected");
129 + const targets = connected
130 + .map((environment) => ({ environmentId: environment.environmentId, input: listInput }))
131 + .sort((left, right) => left.environmentId.localeCompare(right.environmentId));
132 + const list = useIssueList(targets);
133 +
134 + const [pages, setPages] = useState<ReadonlyMap<EnvironmentId, HeldIssuePage>>(new Map());
135 + const held = holdIssuePages(list.answers, pages);
136 + const loadPage = useAtomCommand(issueEnvironment.listPage, { reportFailure: false });
137 + const [loadingMore, setLoadingMore] = useState(false);
138 + const loading = useRef(false);
139 + const continuable = [...held].filter(([, page]) => Object.keys(page.nextCursors).length > 0);
140 + const moreFailure = [...held.values()].find((page) => page.moreFailure)?.moreFailure ?? null;
141 + const loadMore = async (retry = false) => {
142 + if (loading.current || (moreFailure !== null && !retry)) return;
143 + loading.current = true;
144 + setLoadingMore(true);
145 + const loaded = await Promise.all(
146 + continuable.map(async ([environmentId, page]) => {
147 + const result = await loadPage({
148 + environmentId,
149 + input: { ...listInput, cursors: page.nextCursors },
150 + });
151 + const failure = AsyncResult.isFailure(result) ? squashAtomCommandFailure(result) : null;
152 + return [
153 + environmentId,
154 + continueIssuePage(
155 + page,
156 + AsyncResult.isFailure(result)
157 + ? { failure: failure instanceof Error ? failure.message : "The next page failed." }
158 + : result.value,
159 + ),
160 + ] as const;
161 + }),
162 + );
163 + loading.current = false;
164 + setLoadingMore(false);
165 + setPages(new Map([...held, ...loaded]));
166 + };
167 +
168 + const groups = groupIssues(held, query, projects);
169 + const entries = groups
170 + .flatMap((group) => group.rows)
171 + .sort((left, right) => Date.parse(right.updatedAt) - Date.parse(left.updatedAt));
172 + const notices = groups.flatMap((group) => [
173 + ...(group.tracker.configured
174 + ? []
175 + : [`${group.tracker.host}: ${group.tracker.detail ?? "This tracker cannot be read."}`]),
176 + ...group.errors.map((error) => `${error.projectTitle}: ${error.message}`),
177 + ]);
178 +
179 + const paneRole = usePaneRole();
180 + const sidebar = props.sidebar === true || (primaryColumn !== null && paneRole === "sidebar");
181 + const selectedKey = props.selectedIssueKey ?? primaryColumn?.selectedIssueKey;
182 + const selectDetail = useSelectWorkspaceDetail();
183 + const selectIssue = (item: EnvironmentIssueEntry) => {
184 + Keyboard.dismiss();
185 + selectDetail({
186 + name: "Issue",
187 + params: {
188 + environmentId: String(item.environmentId),
189 + projectId: String(item.projectId),
190 + tracker: item.tracker,
191 + host: item.host,
192 + scope: item.scope,
193 + issueKey: item.key,
194 + initialSummary: item,
195 + },
196 + });
197 + };
198 + const scrollToTop = () =>
199 + void listRef.current?.scrollToOffset({ offset: -contentTopInset, animated: false });
200 +
201 + // The Android header's filter button opens every filter, as the pull request list's does.
202 + const headerMenu: PullRequestFilterMenu | null =
203 + Platform.OS === "android"
204 + ? {
205 + actions: [
206 + { id: "state", title: "State", subactions: choices(STATES, state, "state") },
207 + {
208 + id: "involvement",
209 + title: "Involvement",
210 + subactions: choices(INVOLVEMENT, involvement, "involvement"),
211 + },
212 + {
213 + id: "reset",
214 + title: "Reset filters",
215 + attributes: { disabled: state === "open" && involvement === "all" },
216 + },
217 + ],
218 + onSelect: (id) => {
219 + const [field, value] = id.split(":");
220 + if (field === "state") setState(value as IssueListState);
221 + if (field === "involvement") setInvolvement(value as IssueInvolvement);
222 + if (field === "reset") {
223 + setState("open");
224 + setInvolvement("all");
225 + }
226 + },
227 + customized: state !== "open" || involvement !== "all",
228 + }
229 + : null;
230 +
231 + const content = (
232 + <View className={sidebar ? "flex-1 bg-drawer" : "flex-1 bg-screen"}>
233 + <LegendList
234 + ref={listRef}
235 + data={entries}
236 + extraData={selectedKey}
237 + keyExtractor={rowKey}
238 + estimatedItemSize={84}
239 + drawDistance={1_000}
240 + onEndReached={() => void loadMore()}
241 + onEndReachedThreshold={0.5}
242 + refreshControl={
243 + <RefreshControl
244 + refreshing={list.isPending && list.answers.length > 0}
245 + onRefresh={list.refresh}
246 + // The list already accounts for the navigation header in its content inset.
247 + progressViewOffset={Platform.OS === "ios" ? 60 : undefined}
248 + />
249 + }
250 + alwaysBounceVertical
251 + showsVerticalScrollIndicator={Platform.OS !== "android"}
252 + recycleItems
253 + renderScrollComponent={Platform.OS === "ios" ? NativeScrollView : undefined}
254 + contentInsetAdjustmentBehavior="never"
255 + contentInset={Platform.OS === "ios" ? { top: contentTopInset } : undefined}
256 + initialScrollOffset={
257 + initialScrollOffset > 0 ? initialScrollOffset - contentTopInset : undefined
258 + }
259 + contentContainerStyle={{
260 + paddingBottom: Math.max(bottomSafeArea, workspace.bottomClearance),
261 + }}
262 + onScroll={(event) => {
263 + workspace.recordScrollOffset(
264 + "issues",
265 + Math.max(0, event.nativeEvent.contentOffset.y + contentTopInset),
266 + );
267 + }}
268 + keyboardDismissMode="on-drag"
269 + keyboardShouldPersistTaps="handled"
270 + renderItem={({ item }) => (
271 + <IssueListRow
272 + item={item}
273 + onSelect={selectIssue}
274 + selected={selectedKey === rowKey(item)}
275 + sidebar={sidebar}
276 + />
277 + )}
278 + // Lifted above the rows so an iOS filter menu's dismissal morph is not covered.
279 + ListHeaderComponentStyle={{ zIndex: 1 }}
280 + ListHeaderComponent={
281 + <>
282 + <ScrollView
283 + horizontal
284 + showsHorizontalScrollIndicator={false}
285 + style={{ overflow: "visible" }}
286 + contentContainerStyle={
287 + sidebar && Platform.OS === "android"
288 + ? { ...FILTER_ROW_STYLE, paddingHorizontal: 20 }
289 + : FILTER_ROW_STYLE
290 + }
291 + >
292 + <ListFilterMenu
293 + label={STATES[state]}
294 + active={state !== "open"}
295 + accessibilityLabel="Filter by state"
296 + actions={choices(STATES, state)}
297 + onSelect={(id) => {
298 + setState(id as IssueListState);
299 + scrollToTop();
300 + }}
301 + />
302 + <ListFilterMenu
303 + label={INVOLVEMENT[involvement]}
304 + active={involvement !== "all"}
305 + accessibilityLabel="Filter by involvement"
306 + actions={choices(INVOLVEMENT, involvement)}
307 + onSelect={(id) => {
308 + setInvolvement(id as IssueInvolvement);
309 + scrollToTop();
310 + }}
311 + />
312 + </ScrollView>
313 + {notices.map((notice) => (
314 + <Text key={notice} selectable className="px-4 py-1.5 text-sm text-foreground-muted">
315 + {notice}
316 + </Text>
317 + ))}
318 + </>
319 + }
320 + ListFooterComponent={
321 + loadingMore ? (
322 + <View className="items-center py-5">
323 + <AppActivityIndicator
324 + colorClassName="accent-icon"
325 + accessibilityLabel="Loading more issues"
326 + />
327 + </View>
328 + ) : moreFailure ? (
329 + <View className="items-center gap-2 px-8 py-4">
330 + <Text className="text-xs text-foreground-muted">{moreFailure}</Text>
331 + <Button
332 + label="Try again"
333 + accessibilityLabel="Retry loading more issues"
334 + onPress={() => void loadMore(true)}
335 + />
336 + </View>
337 + ) : continuable.length > 0 ? (
338 + // A filtered page can be too short to scroll, which leaves nothing to reach the end of.
339 + <View className="items-center py-4">
340 + <Button
341 + label="Load more"
342 + accessibilityLabel="Load more issues"
343 + onPress={() => void loadMore()}
344 + />
345 + </View>
346 + ) : undefined
347 + }
348 + ListEmptyComponent={
349 + list.isPending && list.answers.length === 0 ? (
350 + <View className="items-center py-12">
351 + <AppActivityIndicator colorClassName="accent-icon" />
352 + </View>
353 + ) : (
354 + <View className="px-8 py-12">
355 + <EmptyState
356 + title={
357 + list.error
358 + ? "Couldn't load issues"
359 + : connected.length > 0
360 + ? query
361 + ? "No results"
362 + : "No matching issues"
363 + : capable.length > 0
364 + ? "Environment offline"
365 + : environments.length > 0
366 + ? "Issues unavailable"
367 + : "Connect an environment"
368 + }
369 + detail={
370 + list.error ??
371 + (connected.length > 0
372 + ? "Issues from your environments' projects appear here."
373 + : capable.length > 0
374 + ? "Reconnect to load issues."
375 + : environments.length > 0
376 + ? "Update the environment's T3 Code server to browse issues."
377 + : "Add an environment in Settings to browse its issues.")
378 + }
379 + variant="plain"
380 + />
381 + </View>
382 + )
383 + }
384 + />
385 + </View>
386 + );
387 + return props.renderFrame ? props.renderFrame(headerMenu, content) : content;
388 +}
apps/mobile/src/features/issues/issueParams.ts new
+78
@@ -0,0 +1,78 @@
1 +import type { NavigationState } from "@react-navigation/native";
2 +import {
3 + EnvironmentId,
4 + IssueTrackerKind,
5 + ProjectId,
6 + type IssueListEntry,
7 + type IssueRef,
8 +} from "@t3tools/contracts";
9 +
10 +/** Route params that name one issue. Plain strings, so a link can carry them. */
11 +export type IssueParams = {
12 + readonly environmentId: string;
13 + readonly projectId: string;
14 + readonly tracker: string;
15 + readonly host?: string;
16 + readonly scope: string;
17 + readonly issueKey: string;
18 + /** The list row the issue was opened from, shown until its detail arrives. */
19 + readonly initialSummary?: IssueListEntry;
20 +};
21 +
22 +export function issueTarget(params: IssueParams) {
23 + const input: IssueRef = {
24 + projectId: ProjectId.make(params.projectId),
25 + tracker: IssueTrackerKind.make(params.tracker),
26 + ...(params.host ? { host: params.host } : {}),
27 + scope: params.scope,
28 + key: params.issueKey,
29 + };
30 + return { environmentId: EnvironmentId.make(params.environmentId), input };
31 +}
32 +
33 +/** The params without the list row, for the screens an issue opens. */
34 +export function issueIdentity({ initialSummary: _, ...identity }: IssueParams) {
35 + return identity;
36 +}
37 +
38 +/** The identity the Issues tab remembers and the list marks as selected. */
39 +export function issueParamsKey(
40 + params: Pick<IssueParams, "environmentId" | "projectId" | "host" | "scope" | "issueKey">,
41 +) {
42 + return [
43 + params.environmentId,
44 + params.projectId,
45 + (params.host ?? "").toLowerCase(),
46 + params.scope.toLowerCase(),
47 + params.issueKey,
48 + ].join("\u0000");
49 +}
50 +
51 +/** The selected issue's key from a route's params, when they name one. */
52 +export function selectedIssueKeyOf(params: object | undefined) {
53 + const value = params as Partial<Record<keyof IssueParams, unknown>> | undefined;
54 + return typeof value?.environmentId === "string" &&
55 + typeof value.projectId === "string" &&
56 + typeof value.scope === "string" &&
57 + typeof value.issueKey === "string"
58 + ? issueParamsKey({
59 + environmentId: value.environmentId,
60 + projectId: value.projectId,
61 + scope: value.scope,
62 + issueKey: value.issueKey,
63 + ...(typeof value.host === "string" ? { host: value.host } : {}),
64 + })
65 + : null;
66 +}
67 +
68 +/** The issue the detail pane shows, for marking its row in the Android sidebar. */
69 +export function selectedIssueKey(state: Pick<NavigationState, "routes" | "index">) {
70 + for (let index = state.index; index >= 0; index--) {
71 + const route = state.routes[index];
72 + if (!route) continue;
73 + if (route.name === "Home" || !route.name.startsWith("Issue")) return null;
74 + const key = selectedIssueKeyOf(route.params);
75 + if (key !== null || route.name === "Issue") return key;
76 + }
77 + return null;
78 +}
apps/mobile/src/features/issues/issuePicks.ts new
+15
@@ -0,0 +1,15 @@
1 +import { noIssuePicks } from "@t3tools/client-runtime/issue-selection";
2 +import type { IssueAssigneeCandidate, IssueLabelCandidate } from "@t3tools/contracts";
3 +import { Atom } from "effect/reactivity";
4 +
5 +// Outside the sheets: a sheet is gone before its write lands, and one reopened in between must
6 +// build on those picks rather than on the issue as it was last read.
7 +const IDLE_TTL_MS = 60_000;
8 +
9 +export const issueLabelPicksFamily = Atom.family((_issueKey: string) =>
10 + Atom.make(noIssuePicks<IssueLabelCandidate>()).pipe(Atom.setIdleTTL(IDLE_TTL_MS)),
11 +);
12 +
13 +export const issueAssigneePicksFamily = Atom.family((_issueKey: string) =>
14 + Atom.make(noIssuePicks<IssueAssigneeCandidate>()).pipe(Atom.setIdleTTL(IDLE_TTL_MS)),
15 +);
apps/mobile/src/features/issues/issuePresentation.tsx new
+90
@@ -0,0 +1,90 @@
1 +import { useAtomValue } from "@effect/atom-react";
2 +import { issueStateLabel, issueWriteAccess } from "@t3tools/client-runtime/issue-presentation";
3 +import {
4 + isAtomCommandInterrupted,
5 + squashAtomCommandFailure,
6 +} from "@t3tools/client-runtime/state/runtime";
7 +import type { IssueDetail, IssueLabel, IssueState } from "@t3tools/contracts";
8 +import { AsyncResult } from "effect/reactivity";
9 +import { View } from "react-native";
10 +
11 +import type { AppSymbolName } from "../../components/ui/AppSymbol";
12 +import { AppText as Text } from "../../components/ui/AppText";
13 +import { issueEnvironment } from "../../state/issues";
14 +import { ENVIRONMENT_REQUEST_INTERRUPTED } from "../../state/query";
15 +import { pullRequestLabelColor } from "../pull-requests/pullRequestList";
16 +import { usePullRequestConnected } from "../pull-requests/usePullRequestConnected";
17 +import { issueTarget, type IssueParams } from "./issueParams";
18 +
19 +// Open and completed wear the pull request colors for open and merged; not planned is grey,
20 +// because work that stopped must not look like work that finished.
21 +export function issueStatus(state: IssueState): {
22 + readonly label: string;
23 + readonly icon: AppSymbolName;
24 + readonly tint: string;
25 + readonly text: string;
26 +} {
27 + const label = issueStateLabel(state);
28 + if (state.category === "open")
29 + return {
30 + label,
31 + icon: "git.issue",
32 + tint: "accent-adaptive-emerald-600-400",
33 + text: "text-adaptive-emerald-600-400",
34 + };
35 + if (state.closeReason === "not-planned")
36 + return {
37 + label,
38 + icon: "slash.circle",
39 + tint: "accent-icon-muted",
40 + text: "text-foreground-muted",
41 + };
42 + return {
43 + label,
44 + icon: "checkmark.circle",
45 + tint: "accent-adaptive-violet-600-400",
46 + text: "text-adaptive-violet-600-400",
47 + };
48 +}
49 +
50 +/** What this device may do to the issue, and the first thing in the way when it may not. */
51 +export function useIssueAccess(params: IssueParams, detail: IssueDetail | null | undefined) {
52 + const connected = usePullRequestConnected(params.environmentId);
53 + const canWrite = useAtomValue(
54 + issueEnvironment.update.permissionAtom(issueTarget(params).environmentId),
55 + );
56 + if (!detail) return null;
57 + const access = issueWriteAccess(detail, connected && canWrite);
58 + return {
59 + ...access,
60 + blocked: connected
61 + ? canWrite
62 + ? access.blocked
63 + : "This device isn't allowed to change source control on this environment."
64 + : "Reconnect to make changes.",
65 + };
66 +}
67 +
68 +export function issueCommandError(result: AsyncResult.AsyncResult<unknown, unknown>) {
69 + if (!AsyncResult.isFailure(result)) return null;
70 + if (isAtomCommandInterrupted(result)) return ENVIRONMENT_REQUEST_INTERRUPTED;
71 + const cause = squashAtomCommandFailure(result);
72 + return cause instanceof Error ? cause.message : "The tracker refused it.";
73 +}
74 +
75 +export function IssueLabelPill({ label }: { readonly label: IssueLabel }) {
76 + const color = pullRequestLabelColor(label.color);
77 + return (
78 + <View
79 + className="max-w-full flex-row items-center gap-1.5 rounded-2xl bg-grouped-card px-3 py-1"
80 + style={color ? { backgroundColor: `${color}20` } : undefined}
81 + >
82 + {color ? (
83 + <View style={{ width: 6, height: 6, borderRadius: 3, backgroundColor: color }} />
84 + ) : null}
85 + <Text textRole="caption" className="shrink text-foreground-muted" numberOfLines={1}>
86 + {label.name}
87 + </Text>
88 + </View>
89 + );
90 +}
apps/mobile/src/features/layout/WorkspaceEmptyDetail.tsx
+10 -5
@@ -14,6 +14,7 @@ export function WorkspaceEmptyDetail(props: {
14 readonly onAddConnection?: () => void;
15 }) {
16 const pullRequests = props.tab === "pullRequests";
17 + const issues = props.tab === "issues";
18 const settings = props.tab === "settings";
19 if (props.tab === "usage") return <View className="flex-1 bg-screen" />;
20 return (
@@ -55,18 +56,22 @@ export function WorkspaceEmptyDetail(props: {
56 ? "Select a setting"
57 : pullRequests
58 ? "Select a pull request"
58 - : "Select a thread"}
59 + : issues
60 + ? "Select an issue"
61 + : "Select a thread"}
62 </Text>
63 <Text className="text-center text-base text-foreground-muted">
64 {settings
65 ? "Choose a page from the sidebar."
66 : pullRequests
67 ? "Choose a pull request from the sidebar to review it."
65 - : Platform.OS === "android"
66 - ? "Choose a thread from the sidebar or start a new thread."
67 - : "Choose a thread from the sidebar or start a new task."}
68 + : issues
69 + ? "Choose an issue from the sidebar to read it."
70 + : Platform.OS === "android"
71 + ? "Choose a thread from the sidebar or start a new thread."
72 + : "Choose a thread from the sidebar or start a new task."}
73 </Text>
69 - {props.onStartNewTask && !pullRequests && !settings ? (
74 + {props.onStartNewTask && !pullRequests && !issues && !settings ? (
75 Platform.OS === "android" ? (
76 <NewThreadButton extended className="mt-2" onPress={props.onStartNewTask} />
77 ) : (
apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx
+12 -7
@@ -47,6 +47,9 @@ import {
47 WorkspaceSidebarTabsFooter,
48 } from "./workspace/WorkspaceNativeTabs.ios";
49 import { workspaceUsesColumns } from "./workspace/workspace-tabs-state";
50 +import { useWorkspaceCompose } from "./workspace/useWorkspaceCompose";
51 +import { NAVIGATION_TAB_ORDER } from "./workspace/navigation-tab-order";
52 +import { selectedIssueKeyOf } from "../issues/issueParams";
53 import { isSettingsRoute, settingsOpenIn } from "../settings/settings-navigation";
54 import { workspaceRoutesOf } from "./workspace-overlay-routes";
55 import { setNativelyPoppingWorkspaceRoute } from "./workspace/workspace-detail-selection";
@@ -97,6 +100,8 @@ const isPullRequestRoute = (route: Route) =>
100 route.name === "PullRequestFile" ||
101 route.name === "PullRequestFiles";
102
103 +const isIssueRoute = (route: Route) => route.name.startsWith("Issue");
104 +
105 // Every step of starting a task, from the project picker to the draft thread itself.
106 const isNewTaskRoute = (route: Route) =>
107 route.name.startsWith("NewTask") ||
@@ -114,6 +119,7 @@ function ColumnScreen(props: {
119 readonly animatesPush?: boolean;
120 readonly selectedThreadKey?: string | null;
121 readonly selectedPullRequestKey?: string | null;
122 + readonly selectedIssueKey?: string | null;
123 readonly onDismiss: (routeKey: string, native: boolean) => void;
124 readonly onAppearance: (
125 type: "willAppear" | "didAppear" | "willDisappear" | "didDisappear",
@@ -139,6 +145,7 @@ function ColumnScreen(props: {
145 presented,
146 selectedThreadKey: props.selectedThreadKey ?? null,
147 selectedPullRequestKey: props.selectedPullRequestKey ?? null,
148 + selectedIssueKey: props.selectedIssueKey ?? null,
149 }
150 : null;
151 const key = descriptor.route.key;
@@ -270,10 +277,8 @@ function WorkspaceColumns(
277 const openNewTask = startNewTask;
278 // The cover detail rail needs room for thread tools above the fixed tabs.
279 // The unfolded Duo keeps compose in its detail bar.
273 - const detailCompose =
274 - deviceType === "duo-unfolded" && selectedTab !== "pullRequests" && !settingsOpen
275 - ? openNewTask
276 - : undefined;
280 + const compose = useWorkspaceCompose();
281 + const detailCompose = deviceType === "duo-unfolded" ? compose?.onPress : undefined;
282 // Pages a hidden tab opens as it's shown belong to the tab, so they appear in place.
283 const headerOnly = use(NativeWorkspaceTabActivityContext)?.headerOnly === true;
284 const [shownPages, setShownPages] = useState({ headerOnly, keys: new Set<string>() });
@@ -305,6 +310,7 @@ function WorkspaceColumns(
310 typeof pullRequestParams.number === "number"
311 ? `${pullRequestParams.environmentId}:${pullRequestParams.host}:${pullRequestParams.repository}:${pullRequestParams.number}`
312 : null;
313 + const selectedIssueKey = selectedIssueKeyOf(props.detail.findLast(isIssueRoute)?.params);
314 const selectedThreadKey =
315 threadParams &&
316 "environmentId" in threadParams &&
@@ -382,9 +388,7 @@ function WorkspaceColumns(
388 if (workspace.some((route) => route.name !== "Home" && route.name !== "Settings")) return;
389 const tab = workspace.some((route) => route.name === "Settings")
390 ? "settings"
385 - : (["threads", "pullRequests", "usage"] as const).find((candidate) =>
386 - workspaceTabs?.isTabActive(candidate),
387 - );
391 + : NAVIGATION_TAB_ORDER.find((candidate) => workspaceTabs?.isTabActive(candidate));
392 openWorkspaceTab(tab ?? "threads", { columns: true });
393 }}
394 preferredDisplayMode={
@@ -437,6 +441,7 @@ function WorkspaceColumns(
441 }
442 selectedThreadKey={selectedThreadKey}
443 selectedPullRequestKey={selectedPullRequestKey}
444 + selectedIssueKey={selectedIssueKey}
445 onDismiss={handleNativeDismiss}
446 onAppearance={followCollapsedSplit}
447 navigation={props.navigation}
apps/mobile/src/features/layout/workspace/AndroidWorkspaceSidebar.android.tsx
+24 -3
@@ -9,7 +9,9 @@ import { FLOATING_TABS } from "./floating-workspace-tabs";
9 import { View } from "react-native";
10 import { ScreenContent } from "../../../components/ui/ScreenContent";
11 import { PullRequestsScreen } from "../../pull-requests/PullRequestsScreen";
12 -import { PullRequestToolbar } from "./PullRequestToolbar.android";
12 +import { ListSearchToolbar } from "./ListSearchToolbar.android";
13 +import { IssuesScreen } from "../../issues/IssuesScreen";
14 +import { selectedIssueKey } from "../../issues/issueParams";
15 import { selectedPullRequestKey } from "../../pull-requests/pullRequestSelection";
16 import { AndroidHomeFabLayout } from "../../home/AndroidHomeFab";
17 import { useAdaptiveWorkspaceLayout } from "../adaptive-workspace-context";
@@ -28,6 +30,7 @@ export function AndroidWorkspaceSidebar() {
30 const { fabSize } = useAndroidControlSizing();
31 const { revealPrimarySidebar, startNewTask } = useAdaptiveWorkspaceLayout();
32 const selectedPullRequest = useNavigationState(selectedPullRequestKey);
33 + const selectedIssue = useNavigationState(selectedIssueKey);
34 // Settings and Usage cover the sidebar.
35 const coveredByPage =
36 (useAndroidWorkspaceRoot()?.settingsOpen ?? false) || workspace.state.selectedTab === "usage";
@@ -46,8 +49,25 @@ export function AndroidWorkspaceSidebar() {
49 <AndroidHomeFabLayout sidebar disabled={coveredByPage} onStartNewTask={startNewTask}>
50 <WorkspaceThreadSidebar />
51 </AndroidHomeFabLayout>
49 - ) : tab !== "pullRequests" ? (
52 + ) : tab === "usage" ? (
53 <View className="flex-1 bg-screen" />
54 + ) : tab === "issues" ? (
55 + <WorkspaceTabsContext value={context}>
56 + <IssuesScreen
57 + sidebar
58 + selectedIssueKey={selectedIssue}
59 + renderFrame={(filters, list) => (
60 + <View className="flex-1 bg-header">
61 + <ListSearchToolbar
62 + tab="issues"
63 + filters={filters}
64 + onRequestVisibility={revealPrimarySidebar}
65 + />
66 + <ScreenContent insetHorizontal>{list}</ScreenContent>
67 + </View>
68 + )}
69 + />
70 + </WorkspaceTabsContext>
71 ) : (
72 <WorkspaceTabsContext value={context}>
73 <PullRequestsScreen
@@ -55,7 +75,8 @@ export function AndroidWorkspaceSidebar() {
75 selectedPullRequestKey={selectedPullRequest}
76 renderFrame={(filters, list) => (
77 <View className="flex-1 bg-header">
58 - <PullRequestToolbar
78 + <ListSearchToolbar
79 + tab="pullRequests"
80 filters={filters}
81 onRequestVisibility={revealPrimarySidebar}
82 />
apps/mobile/src/features/layout/workspace/ListSearchToolbar.android.tsx renamed
+27 -21
@@ -4,67 +4,73 @@ import { BackHandler, Keyboard } from "react-native";
4 import { AppBar } from "../../../components/ui/AppBar";
5 import { appBarMenuItemsFromActions } from "../../../components/ui/menuActionItems";
6 import { useHardwareKeyboardCommand } from "../../keyboard/hardwareKeyboardCommands";
7 -import { WorkspaceBrandTitle } from "./WorkspaceBrandTitle";
7 +import { WorkspaceConnectionTitle } from "../../home/WorkspaceConnectionTitle";
8 +import { SharedSlotTitle } from "./SharedSlotTitle";
9 import { useWorkspaceTabs } from "./WorkspaceTabsContext";
10 import type { PullRequestFilterMenu } from "../../pull-requests/PullRequestListFilters";
11 import { openSettings } from "../../settings/settings-navigation";
12
12 -/** PR search shares the thread list's Android header. */
13 -export function PullRequestToolbar(props: {
14 - readonly filters: PullRequestFilterMenu | null;
13 +const NOUNS = { pullRequests: "pull requests", issues: "issues" } as const;
14 +
15 +/** Pull request and issue search share the thread list's Android header. */
16 +export function ListSearchToolbar(props: {
17 + readonly tab: keyof typeof NOUNS;
18 + readonly filters?: PullRequestFilterMenu | null;
19 readonly onRequestVisibility?: () => void;
20 }) {
21 const navigation = useNavigation();
18 - const { filters } = props;
22 + const { filters, tab: section } = props;
23 + const noun = NOUNS[section];
24 const workspace = useWorkspaceTabs()!;
25 const { dispatch, getScrollOffset, recordScrollOffset, isTabActive } = workspace;
26 const { onRequestVisibility } = props;
22 - const tab = workspace.state.tabs.pullRequests;
27 + const tab = workspace.state.tabs[section];
28 const searching = tab.searchMode !== "resting";
29 const openSearch = () => {
30 onRequestVisibility?.();
31 dispatch({
32 type: "scroll",
28 - tab: "pullRequests",
29 - offset: getScrollOffset("pullRequests"),
33 + tab: section,
34 + offset: getScrollOffset(section),
35 });
31 - dispatch({ type: "search", tab: "pullRequests" });
36 + dispatch({ type: "search", tab: section });
37 return true;
38 };
39 useHardwareKeyboardCommand("focusSearch", openSearch);
40 const closeSearch = () => {
41 Keyboard.dismiss();
37 - recordScrollOffset("pullRequests", tab.searchEntryOffset);
38 - dispatch({ type: "cancel", tab: "pullRequests" });
42 + recordScrollOffset(section, tab.searchEntryOffset);
43 + dispatch({ type: "cancel", tab: section });
44 };
40 - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to BackHandler while searching to close the PR search on Android back
45 + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to BackHandler while searching to close the list search on Android back
46 useEffect(() => {
47 if (!searching) return;
48 const subscription = BackHandler.addEventListener("hardwareBackPress", () => {
49 // Frozen Home screens stay mounted under a detail route or another tab,
45 - // so back only applies while the PR list is in front.
50 + // so back only applies while this list is in front.
51 const state = navigation.getState();
47 - if (!state || state.routes[state.index]?.name !== "Home" || !isTabActive("pullRequests"))
52 + if (!state || state.routes[state.index]?.name !== "Home" || !isTabActive(section))
53 return false;
54 if (Keyboard.isVisible()) Keyboard.dismiss();
55 else closeSearch();
56 return true;
57 });
58 return () => subscription.remove();
54 - }, [searching, closeSearch, navigation, isTabActive]);
59 + }, [searching, closeSearch, navigation, isTabActive, section]);
60 return (
61 <AppBar
62 title="T3 Code"
63 titleContent={
59 - <WorkspaceBrandTitle
60 - accessibilityLabel="T3 Code, Pull requests"
61 - onOpenEnvironments={() => openSettings(navigation, "SettingsEnvironments")}
64 + <WorkspaceConnectionTitle
65 + grow
66 + onPress={() => openSettings(navigation, "SettingsEnvironments")}
67 + brand={<SharedSlotTitle tab={section} />}
68 />
69 }
70 search={{
71 value: tab.query,
66 - onChangeText: (query) => dispatch({ type: "query", tab: "pullRequests", query }),
67 - placeholder: "Search pull requests",
72 + onChangeText: (query) => dispatch({ type: "query", tab: section, query }),
73 + placeholder: `Search ${noun}`,
74 active: searching,
75 onOpen: openSearch,
76 onClose: closeSearch,
@@ -73,7 +79,7 @@ export function PullRequestToolbar(props: {
79 filters
80 ? [
81 {
76 - title: "Filter pull requests",
82 + title: `Filter ${noun}`,
83 icon: filters.customized
84 ? "line.3.horizontal.decrease.circle.fill"
85 : "line.3.horizontal.decrease.circle",
apps/mobile/src/features/layout/workspace/SharedSlotTitle.tsx new
+53
@@ -0,0 +1,53 @@
1 +import { Platform, Pressable } from "react-native";
2 +
3 +import { SymbolView } from "../../../components/ui/AppSymbol";
4 +import { AppText as Text } from "../../../components/ui/AppText";
5 +import { Menu } from "../../../components/ui/Menu";
6 +import { useAndroidControlSizing } from "../../../components/ui/useAndroidControlSizing";
7 +import { isSharedSlotTab, type SharedSlotTab } from "./navigation-tab-order";
8 +import { useSelectWorkspaceTab } from "./useSelectWorkspaceTab";
9 +
10 +const TITLES = { pullRequests: "Pull requests", issues: "Issues" } as const;
11 +
12 +/** The header title of the tab pull requests and issues share: names the list and switches it. */
13 +export function SharedSlotTitle(props: { readonly tab: SharedSlotTab }) {
14 + const selectTab = useSelectWorkspaceTab();
15 + const { scale } = useAndroidControlSizing();
16 + return (
17 + <Menu
18 + actions={Object.entries(TITLES).map(([id, title]) => ({
19 + id,
20 + title,
21 + state: id === props.tab ? ("on" as const) : ("off" as const),
22 + }))}
23 + onPressAction={({ nativeEvent }) => {
24 + const id = nativeEvent.event;
25 + if (isSharedSlotTab(id) && id !== props.tab) selectTab(id);
26 + }}
27 + >
28 + <Pressable
29 + accessibilityRole="button"
30 + accessibilityLabel={`${TITLES[props.tab]}, switch list`}
31 + hitSlop={8}
32 + className="flex-row items-center gap-1.5"
33 + >
34 + <Text
35 + allowFontScaling={Platform.OS === "ios"}
36 + maxFontSizeMultiplier={1.4}
37 + numberOfLines={1}
38 + className="font-t3-bold text-foreground"
39 + style={{ fontSize: 20 * scale, letterSpacing: -0.4 * scale }}
40 + >
41 + {TITLES[props.tab]}
42 + </Text>
43 + <SymbolView
44 + name="chevron.down"
45 + size={Math.round(12 * scale)}
46 + tintColorClassName="accent-icon-muted"
47 + type="monochrome"
48 + weight="semibold"
49 + />
50 + </Pressable>
51 + </Menu>
52 + );
53 +}
apps/mobile/src/features/layout/workspace/WorkspaceExtraTab.tsx
+1 -3
@@ -2,9 +2,7 @@ import { type NavigationTab } from "./navigation-tab-order";
2 import { NativeStackScreenOptions } from "../../../native/StackHeader";
3 import { UsageRouteScreen } from "../../usage/UsageRouteScreen";
4
5 -export function WorkspaceExtraTab(_props: {
6 - tab: Exclude<NavigationTab, "threads" | "pullRequests">;
7 -}) {
5 +export function WorkspaceExtraTab(_props: { tab: Extract<NavigationTab, "usage"> }) {
6 return (
7 <>
8 <NativeStackScreenOptions options={{ headerSearchBarOptions: undefined }} />
apps/mobile/src/features/layout/workspace/WorkspaceNativeTabs.ios.tsx
+7 -8
@@ -38,8 +38,10 @@ import { useDeviceType } from "../../../native/native-layout-metrics";
38 import { WorkspaceSidebarTabs } from "./WorkspaceSidebarTabs";
39 import { useAdaptiveWorkspaceLayout, useWorkspacePaneState } from "../AdaptiveWorkspaceLayout";
40 import { useSelectWorkspaceTab } from "./useSelectWorkspaceTab";
41 +import { useWorkspaceCompose } from "./useWorkspaceCompose";
42
43 const PULL_REQUEST_ICON = require("../../../../assets/icons/pull-request.png");
44 +const ISSUE_ICON = require("../../../../assets/icons/issue.png");
45
46 /** Retain each native controller tree; removing its root can leave RNS's stack empty. */
47 function RetainedWorkspaceTab(props: {
@@ -239,7 +241,9 @@ export function WorkspaceNativeTabs(props: {
241 ? { type: "sfSymbol", name: "gearshape" }
242 : tab === "pullRequests"
243 ? { type: "templateSource", templateSource: PULL_REQUEST_ICON }
242 - : { type: "sfSymbol", name: NAVIGATION_TAB_ICONS[tab] },
244 + : tab === "issues"
245 + ? { type: "templateSource", templateSource: ISSUE_ICON }
246 + : { type: "sfSymbol", name: NAVIGATION_TAB_ICONS[tab] },
247 selectedIcon:
248 !settings && tab === "threads"
249 ? { type: "sfSymbol", name: "text.bubble.fill" }
@@ -292,18 +296,13 @@ export function WorkspaceNativeTabs(props: {
296
297 /** The workspace tabs at the foot of the sidebar. */
298 export function WorkspaceSidebarTabsFooter() {
295 - const workspace = useWorkspaceTabs()!;
296 - const { startNewTask } = useAdaptiveWorkspaceLayout();
299 + const compose = useWorkspaceCompose();
300 const compact = useFloatingWorkspaceTabs();
301 return (
302 <WorkspaceSidebarTabs
303 compact={compact}
304 reserveComposeSpace={compact}
302 - onNewTask={
303 - compact && !workspace.settingsOpen && workspace.state.selectedTab === "threads"
304 - ? startNewTask
305 - : undefined
306 - }
305 + onNewTask={compact ? compose?.onPress : undefined}
306 />
307 );
308 }
apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.android.tsx
+15 -5
@@ -13,7 +13,8 @@ import { ScreenContent } from "../../../components/ui/ScreenContent";
13 import { useAndroidControlSizing } from "../../../components/ui/useAndroidControlSizing";
14 import { HomeRouteScreen } from "../../home/HomeRouteScreen";
15 import { PullRequestsScreen } from "../../pull-requests/PullRequestsScreen";
16 -import { PullRequestToolbar } from "./PullRequestToolbar.android";
16 +import { ListSearchToolbar } from "./ListSearchToolbar.android";
17 +import { IssuesScreen } from "../../issues/IssuesScreen";
18 import { useAdaptiveWorkspaceLayout } from "../AdaptiveWorkspaceLayout";
19 import { WorkspaceSettledContentWidthContext } from "../workspace-content-width";
20 import { AndroidWorkspaceNavigation, FloatingWorkspaceTabs } from "./AndroidWorkspaceNavigation";
@@ -95,21 +96,30 @@ function WorkspaceRoot() {
96 renderTab={(tab) =>
97 tab === "threads" ? (
98 <HomeRouteScreen />
98 - ) : tab !== "pullRequests" ? (
99 + ) : tab === "usage" ? (
100 <WorkspacePageFrame width={workspacePageWidth ?? null}>
101 <WorkspaceExtraTab tab={tab} />
102 </WorkspacePageFrame>
103 ) : layout.usesSplitView ? (
104 <>
105 <NativeStackScreenOptions options={{ headerShown: false }} />
105 - <AppBar embedded title="Pull requests" />
106 - <WorkspaceEmptyDetail tab="pullRequests" />
106 + <AppBar embedded title={tab === "issues" ? "Issues" : "Pull requests"} />
107 + <WorkspaceEmptyDetail tab={tab} />
108 </>
109 + ) : tab === "issues" ? (
110 + <IssuesScreen
111 + renderFrame={(filters, list) => (
112 + <>
113 + <ListSearchToolbar tab="issues" filters={filters} />
114 + <ScreenContent>{list}</ScreenContent>
115 + </>
116 + )}
117 + />
118 ) : (
119 <PullRequestsScreen
120 renderFrame={(filters, list) => (
121 <>
112 - <PullRequestToolbar filters={filters} />
122 + <ListSearchToolbar tab="pullRequests" filters={filters} />
123 <ScreenContent>{list}</ScreenContent>
124 </>
125 )}
apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.tsx
+13 -3
@@ -1,4 +1,6 @@
1 import { WorkspaceNoTabs } from "./WorkspaceNoTabs";
2 +import { isSharedSlotTab } from "./navigation-tab-order";
3 +import { SharedSlotTitle } from "./SharedSlotTitle";
4 import { WORKSPACE_TAB_LABELS, useEnabledNavigationTabs } from "./navigation-tabs";
5 import { WorkspaceExtraTab } from "./WorkspaceExtraTab";
6 import { WorkspaceSettingsList } from "../../settings/SettingsRouteScreen";
@@ -27,6 +29,7 @@ import { HomeRouteScreen } from "../../home/HomeRouteScreen";
29 import { WorkspaceConnectionTitle } from "../../home/WorkspaceConnectionTitle";
30 import { useAdaptiveWorkspaceLayout } from "../AdaptiveWorkspaceLayout";
31 import { PullRequestsScreen } from "../../pull-requests/PullRequestsScreen";
32 +import { IssuesScreen } from "../../issues/IssuesScreen";
33 import {
34 WorkspaceTabsContext,
35 WorkspaceTabsProvider,
@@ -59,7 +62,13 @@ function WorkspaceRootTitle(props: {
62 return (
63 <View style={{ width: maxWidth, minHeight: 32, justifyContent: "center" }}>
64 <WorkspaceConnectionTitle
62 - brand={<CompactBrandTitle accessibilityLabel={`T3 Code, ${tabTitle}`} fit />}
65 + brand={
66 + !settingsOpen && isSharedSlotTab(state.selectedTab) ? (
67 + <SharedSlotTitle tab={state.selectedTab} />
68 + ) : (
69 + <CompactBrandTitle accessibilityLabel={`T3 Code, ${tabTitle}`} fit />
70 + )
71 + }
72 maxWidth={maxWidth}
73 onPress={props.onOpenEnvironments}
74 />
@@ -161,6 +170,8 @@ function WorkspaceRootContent() {
170 <HomeRouteScreen />
171 ) : state.selectedTab === "pullRequests" ? (
172 <PullRequestsScreen />
173 + ) : state.selectedTab === "issues" ? (
174 + <IssuesScreen />
175 ) : (
176 <WorkspaceExtraTab tab={state.selectedTab} />
177 )}
@@ -169,8 +180,7 @@ function WorkspaceRootContent() {
180 <WorkspaceSidebarTabs />
181 ) : null}
182 {enabled.length === 0 && !settingsOpen ? null : settingsOpen ||
172 - state.selectedTab === "threads" ||
173 - state.selectedTab === "pullRequests" ? (
183 + state.selectedTab !== "usage" ? (
184 <WorkspaceToolbar sidebar={sidebarNavigation} onNewTask={startNewTask} />
185 ) : (
186 <WorkspaceSectionToolbar onNewTask={startNewTask} showCompose={false} />
apps/mobile/src/features/layout/workspace/WorkspaceSectionToolbar.tsx
+4 -1
@@ -13,6 +13,7 @@ import { useSelectWorkspaceTab } from "./useSelectWorkspaceTab";
13 import { useCompactWorkspaceTabs, useSidebarWorkspaceTabs } from "./useSystemWorkspaceTabBar";
14
15 const PULL_REQUEST_ICON = require("../../../../assets/icons/pull-request.png");
16 +const ISSUE_ICON = require("../../../../assets/icons/issue.png");
17
18 export function WorkspaceTabToolbarButtons() {
19 const order = useNavigationTabOrder();
@@ -36,7 +37,9 @@ export function WorkspaceTabToolbarButtons() {
37 icon={
38 tab === "pullRequests"
39 ? { type: "image", source: PULL_REQUEST_ICON, tinted: true }
39 - : NAVIGATION_TAB_ICONS[tab]
40 + : tab === "issues"
41 + ? { type: "image", source: ISSUE_ICON, tinted: true }
42 + : NAVIGATION_TAB_ICONS[tab]
43 }
44 tintColor={selected === tab ? selectedTint : undefined}
45 onPress={() => selectTab(tab)}
apps/mobile/src/features/layout/workspace/WorkspaceTabsContext.tsx
+16 -6
@@ -1,9 +1,11 @@
1 -import { RegistryContext, useAtomValue } from "@effect/atom-react";
1 +import { RegistryContext, useAtomSet, useAtomValue } from "@effect/atom-react";
2 import { AsyncResult, Atom } from "effect/reactivity";
3 import { createContext, use, useState, type Dispatch, type ReactNode } from "react";
4
5 -import { mobilePreferencesAtom } from "../../../state/preferences";
5 +import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../../state/preferences";
6 import {
7 + isSharedSlotTab,
8 + sharedSlotAbsentee,
9 navigationCustomizationAvailable,
10 resolveHiddenNavigationTabs,
11 resolveSelectedNavigationTab,
@@ -43,9 +45,12 @@ function resolveWorkspaceTabsSelection(
45 ): WorkspaceTabsState {
46 const saved = AsyncResult.isSuccess(preferences) ? preferences.value : undefined;
47 const order = resolveWorkspaceTabOrder(saved?.navigationTabOrder);
46 - const hidden = navigationCustomizationAvailable()
47 - ? resolveHiddenNavigationTabs(saved?.hiddenNavigationTabs)
48 - : [];
48 + const hidden = [
49 + ...(navigationCustomizationAvailable()
50 + ? resolveHiddenNavigationTabs(saved?.hiddenNavigationTabs)
51 + : []),
52 + sharedSlotAbsentee(state.selectedTab, saved?.sharedSlotTab),
53 + ];
54 const selected = resolveSelectedNavigationTab(order, hidden, state.selectedTab);
55 return selected && selected !== state.selectedTab
56 ? workspaceTabsReducer(state, { type: "select", tab: selected })
@@ -59,6 +64,7 @@ function createWorkspaceTabsModel(selectedTab?: WorkspaceTab) {
64 const scrollOffsets: Record<WorkspaceSearchTab, number> = {
65 threads: 0,
66 pullRequests: 0,
67 + issues: 0,
68 usage: 0,
69 settings: 0,
70 };
@@ -82,8 +88,12 @@ export function WorkspaceTabsProvider(props: {
88 const registry = use(RegistryContext);
89 const [model] = useState(() => createWorkspaceTabsModel(props.initialTab));
90 const state = useAtomValue(model.resolved);
85 - const dispatch = (action: WorkspaceTabsAction) =>
91 + const savePreferences = useAtomSet(updateMobilePreferencesAtom);
92 + const dispatch = (action: WorkspaceTabsAction) => {
93 registry.set(model.stored, workspaceTabsReducer(registry.get(model.resolved), action));
94 + if (action.type === "select" && isSharedSlotTab(action.tab))
95 + savePreferences({ sharedSlotTab: action.tab });
96 + };
97 const context = {
98 state,
99 dispatch,
apps/mobile/src/features/layout/workspace/WorkspaceToolbar.tsx
+10 -10
@@ -20,10 +20,12 @@ import { useWorkspaceTabs } from "./WorkspaceTabsContext";
20 import { shouldRestoreNativeSearch } from "./workspace-tabs-state";
21 import { useFloatingWorkspaceTabs, useSidebarWorkspaceTabs } from "./useSystemWorkspaceTabBar";
22 import { WorkspaceTabToolbarButtons } from "./WorkspaceSectionToolbar";
23 +import { useWorkspaceCompose } from "./useWorkspaceCompose";
24
25 const SEARCH_LABELS = {
26 threads: "Search threads",
27 pullRequests: "Search pull requests",
28 + issues: "Search issues",
29 settings: "Search settings",
30 } as const;
31
@@ -38,12 +40,10 @@ export function WorkspaceToolbar(props: {
40 const floatingTabs = useFloatingWorkspaceTabs();
41 const duoSearch = NATIVE_LIQUID_GLASS_SUPPORTED && isDuoDevice(deviceType);
42 const bottomSearch = duoSearch && sidebarTabs !== "picker";
41 - // On the Duo, compose belongs to the threads tab, in the detail column's bar when unfolded.
43 + const compose = useWorkspaceCompose();
44 + // On the Duo, compose sits in the list's bar when folded and the detail column's when unfolded.
45 const nativeToolbarCompose =
43 - deviceType === "duo-folded" &&
44 - !workspace.settingsOpen &&
45 - workspace.state.selectedTab === "threads" &&
46 - activeNewTask === null;
46 + deviceType === "duo-folded" && compose !== null && activeNewTask === null;
47 const tabActive = use(NativeWorkspaceTabActivityContext)?.active ?? true;
48 const focused = useIsFocused();
49 const { layout, togglePrimarySidebar } = useAdaptiveWorkspaceLayout();
@@ -126,9 +126,9 @@ export function WorkspaceToolbar(props: {
126 const composeButton = nativeToolbarCompose ? (
127 <Toolbar.Button
128 identifier="workspace-compose"
129 - accessibilityLabel="New chat"
129 + accessibilityLabel={compose?.label}
130 icon="square.and.pencil"
131 - onPress={props.onNewTask}
131 + onPress={compose?.onPress}
132 separateBackground
133 />
134 ) : null;
@@ -197,15 +197,15 @@ export function WorkspaceToolbar(props: {
197 {searchButton}
198 {nativeToolbarCompose && foldedSearch ? <Toolbar.Spacer width={8} /> : null}
199 {composeButton}
200 - {selectedTab !== "threads" ||
200 + {compose === null ||
201 isDuoDevice(deviceType) ||
202 (deviceType === "pad" && layout.usesSplitView) ||
203 sidebarTabs === "picker" ||
204 floatingTabs ? null : (
205 <Toolbar.Button
206 - accessibilityLabel="New chat"
206 + accessibilityLabel={compose.label}
207 icon="square.and.pencil"
208 - onPress={props.onNewTask}
208 + onPress={compose.onPress}
209 />
210 )}
211 {NATIVE_LIQUID_GLASS_SUPPORTED ? null : (
apps/mobile/src/features/layout/workspace/android-workspace-tabs.ts
+1 -1
@@ -11,7 +11,7 @@ import { rememberedSettingsPage, workspaceSelectionsIn } from "./workspace-tab-n
11 /** Settings joins the two list tabs as a top-level Android destination. */
12 export type AndroidWorkspaceNavigationTab = WorkspaceTab | "settings";
13
14 -const WORKSPACE_ROUTES = new Set(["Home", "Thread", "PullRequest"]);
14 +const WORKSPACE_ROUTES = new Set(["Home", "Thread", "PullRequest", "Issue"]);
15
16 /** The Settings tab resets over Home alone so stale chat and PR history is dropped. */
17 export function androidWorkspaceTabNavigationState(
apps/mobile/src/features/layout/workspace/navigation-tab-order.test.ts
+12 -4
@@ -5,6 +5,7 @@ import {
5 moveNavigationTab,
6 overflowNavigationTabs,
7 enabledNavigationTabs,
8 + sharedSlotAbsentee,
9 toggleNavigationTabVisibility,
10 resolveSelectedNavigationTab,
11 resolveNavigationTabOrder,
@@ -23,11 +24,18 @@ describe("navigation tab order", () => {
24
25 it("fills missing sections and drops removed placeholders, duplicates, and Settings", () => {
26 expect(
26 - resolveNavigationTabOrder(["usage", "home", "issues", "settings", "usage", null]),
27 - ).toEqual(["usage", "threads", "pullRequests"]);
27 + resolveNavigationTabOrder(["usage", "home", "inbox", "settings", "usage", null]),
28 + ).toEqual(["usage", "threads", "pullRequests", "issues"]);
29 expect(resolveNavigationTabOrder()).toEqual(NAVIGATION_TAB_ORDER);
30 });
31
32 + it("gives the shared slot to the open list, or else the one opened last", () => {
33 + expect(sharedSlotAbsentee("issues", "pullRequests")).toBe("pullRequests");
34 + expect(sharedSlotAbsentee("pullRequests", "issues")).toBe("issues");
35 + expect(sharedSlotAbsentee("threads", "issues")).toBe("pullRequests");
36 + expect(sharedSlotAbsentee("usage", undefined)).toBe("issues");
37 + });
38 +
39 it("moves a section without changing the relative order of the others", () => {
40 for (const tab of NAVIGATION_TAB_ORDER) {
41 for (let position = 0; position < NAVIGATION_TAB_ORDER.length; position++) {
@@ -51,10 +59,10 @@ describe("navigation tab order", () => {
59 it("removes hidden sections from navigation and restores their saved positions", () => {
60 const order = moveNavigationTab(undefined, "usage", 0);
61 const hidden = toggleNavigationTabVisibility([], "usage");
54 - expect(enabledNavigationTabs(order, hidden)).toEqual(["threads", "pullRequests"]);
62 + expect(enabledNavigationTabs(order, hidden)).toEqual(["threads", "pullRequests", "issues"]);
63 expect(toggleNavigationTabVisibility(hidden, "usage")).toEqual([]);
64 expect(visibleNavigationTabs(order, [], 5)).toEqual(order);
57 - expect(enabledNavigationTabs(undefined, ["home", "issues", "settings"])).toEqual(
65 + expect(enabledNavigationTabs(undefined, ["home", "inbox", "settings"])).toEqual(
66 NAVIGATION_TAB_ORDER,
67 );
68 });
apps/mobile/src/features/layout/workspace/navigation-tab-order.ts
+19 -2
@@ -1,8 +1,24 @@
1 -export const NAVIGATION_TAB_ORDER = ["threads", "pullRequests", "usage"] as const;
1 +export const NAVIGATION_TAB_ORDER = ["threads", "pullRequests", "issues", "usage"] as const;
2 export type NavigationTab = (typeof NAVIGATION_TAB_ORDER)[number];
3
4 +const SHARED_SLOT_TABS = ["pullRequests", "issues"] as const;
5 +export type SharedSlotTab = (typeof SHARED_SLOT_TABS)[number];
6 +
7 +export function isSharedSlotTab(value: unknown): value is SharedSlotTab {
8 + return SHARED_SLOT_TABS.some((tab) => tab === value);
9 +}
10 +
11 +/**
12 + * Pull requests and issues share one slot in the tab bar. The open one holds it, or else the one
13 + * opened last; this returns the other, which the bar leaves out.
14 + */
15 +export function sharedSlotAbsentee(selected: NavigationTab, last: unknown): SharedSlotTab {
16 + const holder = isSharedSlotTab(selected) ? selected : last === "issues" ? last : "pullRequests";
17 + return holder === "issues" ? "pullRequests" : "issues";
18 +}
19 +
20 export function navigationCustomizationAvailable(
5 - registeredSections: number = NAVIGATION_TAB_ORDER.length,
21 + registeredSections: number = NAVIGATION_TAB_ORDER.length - 1,
22 ) {
23 return registeredSections > 4;
24 }
@@ -10,6 +26,7 @@ export function navigationCustomizationAvailable(
26 export const NAVIGATION_TAB_LABELS: Readonly<Record<NavigationTab, string>> = {
27 threads: "Threads",
28 pullRequests: "Pulls",
29 + issues: "Issues",
30 usage: "Usage",
31 };
32
apps/mobile/src/features/layout/workspace/navigation-tabs.ts
+11 -4
@@ -6,11 +6,13 @@ import {
6 navigationCustomizationAvailable,
7 resolveHiddenNavigationTabs,
8 enabledNavigationTabs,
9 + sharedSlotAbsentee,
10 type NavigationTab,
11 } from "./navigation-tab-order";
12 import type { AppSymbolName } from "../../../components/ui/AppSymbol";
13 import { mobilePreferencesAtom } from "../../../state/preferences";
14 import { PullRequestGlyph } from "../../pull-requests/pullRequestGlyphs";
15 +import { useWorkspaceTabs } from "./WorkspaceTabsContext";
16 import { resolveWorkspaceTabOrder } from "./workspace-tabs-state";
17
18 export const WORKSPACE_TAB_LABELS = {
@@ -21,6 +23,7 @@ export const WORKSPACE_TAB_LABELS = {
23 export const NAVIGATION_TAB_ICONS = {
24 threads: "text.bubble",
25 pullRequests: PullRequestGlyph.pullRequest,
26 + issues: "git.issue",
27 usage: "chart.bar.xaxis",
28 } as const satisfies Readonly<Record<NavigationTab, AppSymbolName>>;
29
@@ -34,10 +37,14 @@ export function useNavigationTabOrder() {
37
38 export function useHiddenNavigationTabs() {
39 const preferences = useAtomValue(mobilePreferencesAtom);
37 - const saved = AsyncResult.isSuccess(preferences)
38 - ? preferences.value.hiddenNavigationTabs
39 - : undefined;
40 - return navigationCustomizationAvailable() ? resolveHiddenNavigationTabs(saved) : [];
40 + const selected = useWorkspaceTabs()?.state.selectedTab ?? "threads";
41 + const saved = AsyncResult.isSuccess(preferences) ? preferences.value : undefined;
42 + return [
43 + ...(navigationCustomizationAvailable()
44 + ? resolveHiddenNavigationTabs(saved?.hiddenNavigationTabs)
45 + : []),
46 + sharedSlotAbsentee(selected, saved?.sharedSlotTab),
47 + ];
48 }
49
50 export function useEnabledNavigationTabs() {
apps/mobile/src/features/layout/workspace/useWorkspaceCompose.ts new
+11
@@ -0,0 +1,11 @@
1 +import { useAdaptiveWorkspaceLayout } from "../adaptive-workspace-context";
2 +import { useWorkspaceTabs } from "./WorkspaceTabsContext";
3 +
4 +/** What the compose button starts on the selected tab; null where the tab has nothing to start. */
5 +export function useWorkspaceCompose() {
6 + const workspace = useWorkspaceTabs();
7 + const { startNewTask } = useAdaptiveWorkspaceLayout();
8 + if (!workspace || workspace.settingsOpen || workspace.state.selectedTab !== "threads")
9 + return null;
10 + return { label: "New chat", onPress: startNewTask } as const;
11 +}
apps/mobile/src/features/layout/workspace/workspace-detail-selection.ts
+6 -3
@@ -13,7 +13,8 @@ type RootParams = ReactNavigation.RootParamList;
13 /** A page the workspace's detail column shows on its own: what a list row selects. */
14 export type WorkspaceDetail =
15 | { readonly name: "Thread"; readonly params: RootParams["Thread"] }
16 - | { readonly name: "PullRequest"; readonly params: RootParams["PullRequest"] };
16 + | { readonly name: "PullRequest"; readonly params: RootParams["PullRequest"] }
17 + | { readonly name: "Issue"; readonly params: RootParams["Issue"] };
18
19 /** Android opens the reviewers sheet over the pull request in the same step. */
20 export type WorkspaceDetailSheet = {
@@ -42,6 +43,7 @@ export function selectWorkspaceDetail(
43 const IDENTITY = {
44 Thread: ["environmentId", "threadId"],
45 PullRequest: ["environmentId", "projectId", "repository", "number", "host"],
46 + Issue: ["environmentId", "projectId", "tracker", "host", "scope", "issueKey"],
47 } as const;
48
49 type RouteLike = { readonly name: string; readonly key?: string; readonly params?: object };
@@ -102,13 +104,14 @@ export function workspaceDetailRouter<Action extends NavigationAction>(
104 };
105 }
106
105 -/** A link to a single thread or pull request selects it, like its list row would. */
107 +/** A link to a single thread, pull request or issue selects it, like its list row would. */
108 export function workspaceDetailLinkAction(
109 state: PartialState<NavigationState> | NavigationState,
110 ): SelectWorkspaceDetailAction | undefined {
111 const pages = state.routes.filter((route) => route.name !== "Home");
112 const [page] = pages;
113 if (pages.length !== 1 || !page || page.state) return undefined;
112 - if (page.name !== "Thread" && page.name !== "PullRequest") return undefined;
114 + if (page.name !== "Thread" && page.name !== "PullRequest" && page.name !== "Issue")
115 + return undefined;
116 return selectWorkspaceDetail({ name: page.name, params: page.params } as WorkspaceDetail);
117 }
apps/mobile/src/features/layout/workspace/workspace-selection-store.ts
+10 -1
@@ -55,11 +55,19 @@ function save() {
55 function withoutRouteKeys(saved: WorkspaceSelections | undefined): WorkspaceSelections {
56 const omitKey = <Selection extends { readonly key?: string }>({ key: _, ...rest }: Selection) =>
57 rest;
58 - const { threads, pullRequests, settingsKey: _, threadsDraft: _draft, ...rest } = saved ?? {};
58 + const {
59 + threads,
60 + pullRequests,
61 + issues,
62 + settingsKey: _,
63 + threadsDraft: _draft,
64 + ...rest
65 + } = saved ?? {};
66 return {
67 ...rest,
68 ...(threads ? { threads: omitKey(threads) } : {}),
69 ...(pullRequests ? { pullRequests: omitKey(pullRequests) } : {}),
70 + ...(issues ? { issues: omitKey(issues) } : {}),
71 };
72 }
73
@@ -115,6 +123,7 @@ export const workspaceSelectionCheck: WorkspaceSelectionCheck = {
123 .has(selection.threadId as ThreadId);
124 },
125 pullRequest: (selection) => !environmentRemoved(selection.environmentId),
126 + issue: (selection) => !environmentRemoved(selection.environmentId),
127 };
128
129 /** Whether the window lays the workspace out in columns, by the rule the layout itself uses. */
apps/mobile/src/features/layout/workspace/workspace-tab-navigation.test.ts
+2 -2
@@ -32,7 +32,7 @@ const { StackRouter } = NodeModule.createRequire(
32 )("@react-navigation/routers") as {
33 readonly StackRouter: typeof import("@react-navigation/native").StackRouter;
34 };
35 -const available = { thread: () => true, pullRequest: () => true };
35 +const available = { thread: () => true, pullRequest: () => true, issue: () => true };
36 const names = (state: { routes: readonly { name: string }[] }) =>
37 state.routes.map((route) => route.name);
38
@@ -179,7 +179,7 @@ describe("opening a workspace tab", () => {
179 });
180
181 it("falls back to the list for a chat that no longer exists, or an unknown Settings page", () => {
182 - const missing = { thread: () => false, pullRequest: () => true };
182 + const missing = { thread: () => false, pullRequest: () => true, issue: () => true };
183 expect(
184 names(
185 workspaceTabNavigationState(
apps/mobile/src/features/layout/workspace/workspace-tab-navigation.ts
+48 -4
@@ -13,6 +13,7 @@ type RouteLike = {
13 };
14 type ThreadSelection = NonNullable<WorkspaceSelections["threads"]>;
15 type PullRequestSelection = NonNullable<WorkspaceSelections["pullRequests"]>;
16 +type IssueSelection = NonNullable<WorkspaceSelections["issues"]>;
17
18 /** Opened when Settings has columns and none of its pages has been opened yet. */
19 export const DEFAULT_SETTINGS_PAGE = "SettingsEnvironments" satisfies SettingsPageTarget;
@@ -38,10 +39,11 @@ export function rememberedSettingsPage(selections: WorkspaceSelections): Setting
39 : DEFAULT_SETTINGS_PAGE;
40 }
41
41 -/** Whether a remembered chat or pull request can still be opened. */
42 +/** Whether a remembered chat, pull request or issue can still be opened. */
43 export interface WorkspaceSelectionCheck {
44 readonly thread: (selection: ThreadSelection) => boolean;
45 readonly pullRequest: (selection: PullRequestSelection) => boolean;
46 + readonly issue: (selection: IssueSelection) => boolean;
47 }
48
49 function stringParam(params: object | undefined, key: string) {
@@ -83,8 +85,32 @@ function samePullRequest(
85 );
86 }
87
88 +const ISSUE_IDENTITY = ["environmentId", "projectId", "tracker", "scope", "issueKey"] as const;
89 +
90 +function issueSelection(params: object | undefined): Omit<IssueSelection, "key"> | undefined {
91 + const value = params as Record<string, unknown> | undefined;
92 + if (ISSUE_IDENTITY.some((key) => typeof value?.[key] !== "string")) return undefined;
93 + const identity = value as Record<(typeof ISSUE_IDENTITY)[number], string>;
94 + return {
95 + environmentId: identity.environmentId,
96 + projectId: identity.projectId,
97 + tracker: identity.tracker,
98 + scope: identity.scope,
99 + issueKey: identity.issueKey,
100 + ...(typeof value?.host === "string" ? { host: value.host } : {}),
101 + };
102 +}
103 +
104 +function sameIssue(left: IssueSelection | undefined, right: Omit<IssueSelection, "key">) {
105 + return (
106 + left !== undefined &&
107 + ISSUE_IDENTITY.every((key) => left[key] === right[key]) &&
108 + left.host === right.host
109 + );
110 +}
111 +
112 /**
87 - * The page each tab shows in a root route chain: the newest chat, the newest pull request, and
113 + * The page each tab shows in a root route chain: the newest chat, pull request and issue, and
114 * the Settings page directly above the Settings route. Returns `previous` when nothing changed.
115 */
116 export function workspaceSelectionsIn(
@@ -121,6 +147,11 @@ export function workspaceSelectionsIn(
147 ) {
148 next = { ...next, pullRequests: { ...pullRequest, key: pullRequestRoute?.key } };
149 }
150 + const issueRoute = routes.findLast((route) => route.name === "Issue");
151 + const issue = issueSelection(issueRoute?.params);
152 + if (issue && (!sameIssue(next.issues, issue) || next.issues?.key !== issueRoute?.key)) {
153 + next = { ...next, issues: { ...issue, key: issueRoute?.key } };
154 + }
155 const list = routes.findIndex((route) => route.name === "Settings");
156 const page = list < 0 ? undefined : routes[list + 1];
157 if (
@@ -133,7 +164,10 @@ export function workspaceSelectionsIn(
164 return next;
165 }
166
136 -function identityOf({ key: _key, ...identity }: PullRequestSelection) {
167 +function identityOf<Selection extends { readonly key?: string }>({
168 + key: _key,
169 + ...identity
170 +}: Selection) {
171 return identity;
172 }
173
@@ -155,7 +189,7 @@ function keyedPage<Route extends RouteLike>(route: Route): Route & { readonly ke
189
190 function detailRoute(
191 state: { readonly routes: readonly RouteLike[] },
158 - tab: "threads" | "pullRequests",
192 + tab: "threads" | "pullRequests" | "issues",
193 selections: WorkspaceSelections,
194 check: WorkspaceSelectionCheck,
195 seedPullRequest?: (identity: Omit<PullRequestSelection, "key">) => object,
@@ -186,6 +220,16 @@ function detailRoute(
220 }
221 );
222 }
223 + if (tab === "issues") {
224 + const issue = selections.issues;
225 + if (!issue || !check.issue(issue)) return undefined;
226 + return (
227 + state.routes.find((route) => {
228 + const shown = route.name === "Issue" ? issueSelection(route.params) : undefined;
229 + return shown !== undefined && sameIssue(issue, shown);
230 + }) ?? { key: issue.key, name: "Issue", params: identityOf(issue) }
231 + );
232 + }
233 const pullRequest = selections.pullRequests;
234 if (!pullRequest || !check.pullRequest(pullRequest)) return undefined;
235 return (
apps/mobile/src/features/layout/workspace/workspace-tabs-state.test.ts
+8 -2
@@ -63,7 +63,12 @@ describe("workspace root navigation", () => {
63 });
64
65 it("keeps the registered defaults while customization is unavailable", () => {
66 - expect(resolveWorkspaceTabOrder(undefined)).toEqual(["threads", "pullRequests", "usage"]);
66 + expect(resolveWorkspaceTabOrder(undefined)).toEqual([
67 + "threads",
68 + "pullRequests",
69 + "issues",
70 + "usage",
71 + ]);
72 expect(resolveWorkspaceTabOrder(["home", "usage", "issues", "threads"])).toEqual(
73 resolveWorkspaceTabOrder(undefined),
74 );
@@ -245,7 +250,8 @@ vi.mock("../../pull-requests/PullRequestFilterMenuContext", () => ({
250 createElement("div", null, children),
251 }));
252 vi.mock("../../pull-requests/PullRequestsScreen", () => ({ PullRequestsScreen: () => null }));
248 -vi.mock("./PullRequestToolbar.android", () => ({ PullRequestToolbar: () => null }));
253 +vi.mock("../../issues/IssuesScreen", () => ({ IssuesScreen: () => null }));
254 +vi.mock("./ListSearchToolbar.android", () => ({ ListSearchToolbar: () => null }));
255 vi.mock("./AndroidWorkspaceNavigation", () => ({
256 AndroidWorkspaceNavigation: () => null,
257 FloatingWorkspaceTabs: () => null,
apps/mobile/src/features/layout/workspace/workspace-tabs-state.ts
+5 -3
@@ -16,9 +16,9 @@ export type WorkspaceTab = NavigationTab;
16 export type WorkspaceSearchTab = WorkspaceTab | "settings";
17 export type WorkspaceSearchMode = "resting" | "active" | "expanded";
18
19 -/** Settings, Chats and pull requests pair a list with a detail column; Usage is one page. */
19 +/** Settings, Chats, pull requests and issues pair a list with a detail column; Usage is one page. */
20 export function workspaceUsesColumns(tab: WorkspaceTab, settingsOpen = false) {
21 - return settingsOpen || tab === "threads" || tab === "pullRequests";
21 + return settingsOpen || tab !== "usage";
22 }
23
24 export interface WorkspaceTabState {
@@ -40,6 +40,7 @@ function emptyTab(): WorkspaceTabState {
40
41 /** The list a workspace page belongs to. */
42 export function workspaceTabOf(routeName: string | undefined): WorkspaceTab {
43 + if (routeName === "Issue") return "issues";
44 return routeName === "PullRequest" ? "pullRequests" : "threads";
45 }
46
@@ -52,6 +53,7 @@ export function initialWorkspaceTabsState(
53 tabs: {
54 threads: emptyTab(),
55 pullRequests: emptyTab(),
56 + issues: emptyTab(),
57 usage: emptyTab(),
58 settings: emptyTab(),
59 },
@@ -79,7 +81,7 @@ export function workspaceTabsReducer(
81 selectionRevision: state.selectionRevision + 1,
82 };
83 const tab = action.tab ?? state.selectedTab;
82 - if (tab !== "threads" && tab !== "pullRequests" && tab !== "settings") return state;
84 + if (tab === "usage") return state;
85 const current = state.tabs[tab];
86 let next: WorkspaceTabState;
87 switch (action.type) {
apps/mobile/src/features/pull-requests/PullRequestDescription.tsx
+12 -8
@@ -22,13 +22,17 @@ const COLLAPSED_HEIGHT = 240;
22
23 export function PullRequestDescription(props: {
24 readonly markdown: string;
25 - readonly onCollapse: () => void;
26 - readonly expanded: boolean;
27 - readonly onExpandedChange: (expanded: boolean) => void;
25 + /** Clips a long description behind "Show more"; absent, it is always shown in full. */
26 + readonly collapse?: {
27 + readonly expanded: boolean;
28 + readonly onExpandedChange: (expanded: boolean) => void;
29 + readonly onCollapse: () => void;
30 + };
31 readonly footer?: ReactNode;
32 readonly onTaskListChange?: ComponentProps<typeof PullRequestMarkdown>["onTaskListChange"];
33 }) {
31 - const { expanded, onExpandedChange } = props;
34 + const { collapse } = props;
35 + const expanded = collapse?.expanded ?? true;
36 const [bodyHeight, setBodyHeight] = useState(0);
37 const mediaContext = useContext(PullRequestMediaContext);
38 const { themeVariables: colors } = useAppearancePreferences();
@@ -49,7 +53,7 @@ export function PullRequestDescription(props: {
53 name: new URL(attachment.uri).pathname.split("/").pop() || "Image",
54 };
55 });
52 - const canCollapse = bodyHeight > COLLAPSED_HEIGHT;
56 + const canCollapse = collapse !== undefined && bodyHeight > COLLAPSED_HEIGHT;
57 const collapsed = canCollapse && !expanded;
58 return (
59 <View className="gap-5">
@@ -108,14 +112,14 @@ export function PullRequestDescription(props: {
112 />
113 </View>
114 ) : null}
111 - {canCollapse ? (
115 + {collapse !== undefined && canCollapse ? (
116 <Pressable
117 accessibilityRole="button"
118 accessibilityState={{ expanded }}
119 accessibilityLabel={expanded ? "Collapse description" : "Expand description"}
120 onPress={() => {
117 - if (expanded) props.onCollapse();
118 - onExpandedChange(!expanded);
121 + if (expanded) collapse.onCollapse();
122 + collapse.onExpandedChange(!expanded);
123 }}
124 style={
125 collapsed
apps/mobile/src/features/pull-requests/PullRequestListRow.tsx
+24 -25
@@ -33,6 +33,27 @@ import {
33 } from "./pullRequestStatus";
34 import { PullRequestGlyph } from "./pullRequestGlyphs";
35
36 +/** A label as list rows show it: small, tinted by its color, truncating. */
37 +export function ListRowLabel(props: {
38 + readonly label: { readonly name: string; readonly color: string | null };
39 + readonly textClassName: string;
40 +}) {
41 + const color = pullRequestLabelColor(props.label.color);
42 + return (
43 + <View
44 + className="min-w-0 shrink flex-row items-center gap-1 rounded-md bg-subtle px-1.5 py-0.5"
45 + style={{ maxWidth: 160, ...(color ? { backgroundColor: `${color}20` } : {}) }}
46 + >
47 + {color ? (
48 + <View style={{ width: 5, height: 5, borderRadius: 3, backgroundColor: color }} />
49 + ) : null}
50 + <Text className={cn("shrink text-2xs font-t3-medium", props.textClassName)} numberOfLines={1}>
51 + {props.label.name}
52 + </Text>
53 + </View>
54 + );
55 +}
56 +
57 export const PullRequestListRow = memo(
58 function PullRequestListRow(props: {
59 readonly item: EnvironmentPullRequestListEntry;
@@ -144,31 +165,9 @@ export const PullRequestListRow = memo(
165 </Text>
166 <View className="flex-row items-center gap-1.5">
167 <View className="min-w-0 flex-1 flex-row items-center gap-1">
147 - {item.labels.slice(0, 2).map((label) => {
148 - const color = pullRequestLabelColor(label.color);
149 - return (
150 - <View
151 - key={label.name}
152 - className="min-w-0 shrink flex-row items-center gap-1 rounded-md bg-subtle px-1.5 py-0.5"
153 - style={{
154 - maxWidth: 160,
155 - ...(color ? { backgroundColor: `${color}20` } : {}),
156 - }}
157 - >
158 - {color ? (
159 - <View
160 - style={{ width: 5, height: 5, borderRadius: 3, backgroundColor: color }}
161 - />
162 - ) : null}
163 - <Text
164 - className={cn("shrink text-2xs font-t3-medium", mutedForeground)}
165 - numberOfLines={1}
166 - >
167 - {label.name}
168 - </Text>
169 - </View>
170 - );
171 - })}
168 + {item.labels.slice(0, 2).map((label) => (
169 + <ListRowLabel key={label.name} label={label} textClassName={mutedForeground} />
170 + ))}
171 {item.labels.length > 2 ? (
172 <Text className={cn("shrink-0 text-2xs", tertiaryForeground)}>
173 +{item.labels.length - 2}
apps/mobile/src/features/pull-requests/PullRequestReactions.tsx
+27 -21
@@ -31,16 +31,13 @@ const EMPTY_PENDING: ReadonlyMap<PullRequestReactionContent, PendingPullRequestR
31 new Map();
32 const PILL = "min-h-8 flex-row items-center gap-1 rounded-full border px-2.5 active:opacity-70";
33
34 -function ReactionPills(props: {
35 - readonly params: PullRequestParams;
34 +/** Reaction pills for any subject; `onReact` resolves false when the host refused the change. */
35 +export function ReactionPills(props: {
36 readonly reactions: ReadonlyArray<PullRequestReaction>;
37 readonly canReact: boolean;
38 - /** Absent reacts to the change request itself. */
39 - readonly subjectId?: string;
40 - readonly onChanged: () => void;
38 + readonly onReact: (content: PullRequestReactionContent, reacted: boolean) => Promise<boolean>;
39 + readonly onChanged?: () => void;
40 }) {
42 - const target = pullRequestTarget(props.params);
43 - const setReaction = useAtomCommand(composerPullRequests.setReaction, { reportFailure: false });
41 // Keyed by what the host last reported, so a refresh that lands the change drops the overlay.
42 const [pending, setPending] = useState({ signature: "", values: EMPTY_PENDING });
43 const signature = pullRequestReactionsSignature(props.reactions);
@@ -49,16 +46,7 @@ function ReactionPills(props: {
46 const toggle = async (content: PullRequestReactionContent, reacted: boolean) => {
47 const entry: PendingPullRequestReaction = { reacted };
48 setPending({ signature, values: new Map([...values, [content, entry]]) });
52 - const result = await setReaction({
53 - ...target,
54 - input: {
55 - ...target.input,
56 - ...(props.subjectId === undefined ? {} : { subjectId: props.subjectId }),
57 - content,
58 - reacted,
59 - },
60 - });
61 - if (AsyncResult.isFailure(result)) {
49 + if (!(await props.onReact(content, reacted))) {
50 setPending((current) => {
51 if (current.values.get(content) !== entry) return current;
52 const next = new Map(current.values);
@@ -68,7 +56,7 @@ function ReactionPills(props: {
56 Dialog.alert("Couldn't save the reaction", "Try again in a moment.");
57 return;
58 }
71 - props.onChanged();
59 + props.onChanged?.();
60 };
61 return (
62 <>
@@ -121,6 +109,23 @@ function ReactionPills(props: {
109 );
110 }
111
112 +function usePullRequestReact(params: PullRequestParams, subjectId?: string) {
113 + const target = pullRequestTarget(params);
114 + const setReaction = useAtomCommand(composerPullRequests.setReaction, { reportFailure: false });
115 + return async (content: PullRequestReactionContent, reacted: boolean) =>
116 + !AsyncResult.isFailure(
117 + await setReaction({
118 + ...target,
119 + input: {
120 + ...target.input,
121 + ...(subjectId === undefined ? {} : { subjectId }),
122 + content,
123 + reacted,
124 + },
125 + }),
126 + );
127 +}
128 +
129 /** Reactions on the change request itself, which is where its description's reactions live. */
130 export function PullRequestReactions(props: { readonly params: PullRequestParams }) {
131 const target = pullRequestTarget(props.params);
@@ -128,13 +133,14 @@ export function PullRequestReactions(props: { readonly params: PullRequestParams
133 const activity = useEnvironmentQuery(composerPullRequests.activity(target));
134 const { canReact } = usePullRequestPermissions(props.params, detail.data);
135 const reactions = activity.data?.reactions ?? [];
136 + const onReact = usePullRequestReact(props.params);
137 if (!activity.data || (reactions.length === 0 && !canReact)) return null;
138 return (
139 <View className="flex-row flex-wrap items-center gap-1.5">
140 <ReactionPills
135 - params={props.params}
141 reactions={reactions}
142 canReact={canReact}
143 + onReact={onReact}
144 onChanged={activity.refresh}
145 />
146 </View>
@@ -160,14 +166,14 @@ export function PullRequestCommentFooter(props: {
166 const editableKind = comment.kind === "review" ? null : comment.kind;
167 const canEdit = editableKind !== null && props.permissions.canEditComment(comment);
168 const canReact = props.permissions.canReactComment(comment);
169 + const onReact = usePullRequestReact(props.params, comment.id);
170 if (reactions.length === 0 && !canReact && !canEdit) return null;
171 return (
172 <View className="flex-row flex-wrap items-center gap-1.5">
173 <ReactionPills
167 - params={props.params}
174 reactions={reactions}
175 canReact={canReact}
170 - subjectId={comment.id}
176 + onReact={onReact}
177 onChanged={props.onChanged}
178 />
179 {canEdit && editableKind !== null ? (
apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx
+5 -3
@@ -342,9 +342,11 @@ function PullRequestOverview(props: {
342 <PullRequestDescription
343 markdown={props.description.body}
344 onTaskListChange={props.description.toggleTask}
345 - onCollapse={props.onDescriptionCollapse}
346 - expanded={props.descriptionExpanded}
347 - onExpandedChange={props.onDescriptionExpandedChange}
345 + collapse={{
346 + expanded: props.descriptionExpanded,
347 + onExpandedChange: props.onDescriptionExpandedChange,
348 + onCollapse: props.onDescriptionCollapse,
349 + }}
350 footer={<PullRequestReactions params={props.params} />}
351 />
352 </Animated.View>
apps/mobile/src/features/threads/ThreadComposer.tsx
+14 -235
@@ -1,13 +1,7 @@
1 -import { useSidebarWorkspaceTabs } from "../layout/workspace/useSystemWorkspaceTabBar";
1 import { Button } from "../../components/ui/Button";
2 import * as Dialog from "../../components/ui/Dialog";
3 import type { ComposerTextPaste } from "../../native/T3ComposerEditor.types";
5 -import { useDeviceType } from "../../native/native-layout-metrics";
6 -import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
7 -import {
8 - useAppearancePreferences,
9 - useAndroidFloatingTabs,
10 -} from "../settings/appearance/AppearancePreferencesProvider";
4 +import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
5 import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
6 import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
7 import { AsyncResult } from "effect/reactivity";
@@ -33,7 +27,7 @@ import {
27 import { StackActions, useFocusEffect, useNavigation } from "@react-navigation/native";
28 import type { ReactNode } from "react";
29 import { useEffect, useEffectEvent, useRef, useState, type RefObject } from "react";
36 -import { I18nManager, Keyboard, Platform, View, type ViewStyle } from "react-native";
30 +import { Keyboard, Platform, View } from "react-native";
31 import { composerImageGallery } from "../../lib/composerImageGallery";
32 import { filePreviewGallery } from "../../lib/filePreviewGallery";
33 import { FilePreviewModal, type FilePreviewSource } from "../../components/ui/FilePreviewModal";
@@ -42,16 +36,7 @@ import {
36 composerAttachmentsStillUploading,
37 composerAttachmentUploadsAtom,
38 } from "../../state/composer-attachment-uploads";
45 -import Animated, {
46 - FadeIn,
47 - FadeOut,
48 - type LayoutAnimationFunction,
49 - ReduceMotion,
50 - useAnimatedStyle,
51 - useDerivedValue,
52 - useSharedValue,
53 - withTiming,
54 -} from "react-native-reanimated";
39 +import Animated, { FadeIn, FadeOut, ReduceMotion } from "react-native-reanimated";
40 import { useUniwindTheme } from "../../lib/useUniwindTheme";
41 import { themeColorWithAlpha } from "../../lib/mobileTheme";
42 import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
@@ -77,8 +62,15 @@ import {
62 ComposerAttachmentThumbnail,
63 } from "../../components/ComposerAttachmentStrip";
64 import { VideoPreviewModal, type VideoPreviewSource } from "../../components/ui/VideoPreviewModal";
80 -import { GlassSurface } from "../../components/ui/GlassSurface";
65 import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";
66 +import {
67 + COMPOSER_BOTTOM_GUTTER,
68 + COMPOSER_TRANSITION_DURATION_MS,
69 + ComposerSurface,
70 + INLINE_EDITOR_MIN_WIDTH,
71 + useComposerChrome,
72 + useCompactComposerEditor,
73 +} from "../../components/ComposerSurface";
74 import { fileRoutePathSegments } from "../files/filePath";
75 import {
76 ComposerActionButton,
@@ -96,9 +88,8 @@ import {
88 isModelSelectionUnavailable,
89 serverConfigForCwd,
90 } from "../../lib/modelOptions";
99 -import { useComposerTextRole, type ScaledTextRole } from "../settings/appearance/useScaledTextRole";
91 +import { useComposerTextRole } from "../settings/appearance/useScaledTextRole";
92 import type { RemoteClientConnectionState } from "../../lib/connection";
101 -import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
93 import { Menu } from "../../components/ui/Menu";
94 import {
95 composerRunsDraftLocally,
@@ -109,7 +100,6 @@ import {
100 resolveComposerSendPresentation,
101 type ComposerSendPresentation,
102 } from "./composerSendPresentation";
112 -import { compactEditorInsets } from "./compactEditorInsets";
103 import { ComposerCommandPopover } from "./ComposerCommandPopover";
104 import { ComposerPopoverAnchor } from "./ComposerPopoverAnchor";
105 import { ComposerQueuedEditAttachments } from "./ComposerQueuedEdit";
@@ -134,120 +124,9 @@ import {
124 } from "./use-thread-settings-sheet-presentation";
125
126 export const COMPOSER_COLLAPSED_CHROME = 60;
127 +export const THREAD_COMPOSER_BOTTOM_GUTTER = COMPOSER_BOTTOM_GUTTER;
128
129 const NO_MACHINES: ReadonlyArray<ComposerEnvironmentCandidate> = [];
139 -const COLLAPSED_EDITOR_DEFAULT_INSET = 6;
140 -// iOS puts line-height slack above glyphs. DM Sans's lowercase midline is
141 -// descender (0.31em) + half x-height (0.504em) above the line bottom.
142 -const LOWERCASE_MIDLINE_EM = 0.562;
143 -
144 -function lowercaseMidline(text: ScaledTextRole): number {
145 - return text.lineHeight - LOWERCASE_MIDLINE_EM * text.fontSize;
146 -}
147 -
148 -function collapsedEditorInset(text: ScaledTextRole): number {
149 - const shift = lowercaseMidline(text) - lowercaseMidline(MOBILE_TYPOGRAPHY.body);
150 - return Math.max(0, Math.round(COLLAPSED_EDITOR_DEFAULT_INSET - shift));
151 -}
152 -
153 -const EXPANDED_EDITOR_INSET = 14;
154 -// Room under the expanded editor for the toolbar row.
155 -const EXPANDED_EDITOR_BOTTOM = 52;
156 -
157 -function useCompactComposerEditor(text: ScaledTextRole, value: string, animate: boolean) {
158 - const [contentSize, setContentSize] = useState({ width: 0, height: 0 });
159 - const [compactWidth, setCompactWidth] = useState(0);
160 - const contentHeight = contentSize.height;
161 - const rowWidth = useSharedValue(0);
162 - const editorX = useSharedValue(0);
163 - const editorWidth = useSharedValue(0);
164 - const inset =
165 - Platform.OS === "android" ? COLLAPSED_EDITOR_DEFAULT_INSET : collapsedEditorInset(text);
166 - const minimum = Math.max(INLINE_EDITOR_HEIGHT, Math.ceil(text.lineHeight) + 2 * inset);
167 - const height = Math.max(
168 - minimum,
169 - Math.min(text.lineHeight * 4 + 2 * inset, contentHeight + 2 * inset),
170 - );
171 - // A line that fits the expanded editor may still overflow its compact slot.
172 - // Compare its measured width too so widening cannot trigger a collapse loop.
173 - const isExpanded =
174 - value.length > 0 &&
175 - (contentHeight > text.lineHeight * 1.5 ||
176 - (compactWidth > 0 && contentSize.width > compactWidth));
177 - const compactRowHeight = Math.max(44, minimum);
178 - const compactBottom = (compactRowHeight - minimum) / 2;
179 - const isRTL = I18nManager.isRTL;
180 - const expandedRowHeight = height + EXPANDED_EDITOR_BOTTOM;
181 - const expansion = useDerivedValue(() => {
182 - const target = isExpanded ? 1 : 0;
183 - return animate
184 - ? withTiming(target, {
185 - duration: COMPOSER_TRANSITION_DURATION_MS,
186 - reduceMotion: ReduceMotion.System,
187 - })
188 - : target;
189 - });
190 - const editorStyle = useAnimatedStyle(() => {
191 - const compactInsets = compactEditorInsets({
192 - slotX: editorX.value,
193 - slotWidth: editorWidth.value,
194 - rowWidth: rowWidth.value,
195 - isRTL,
196 - });
197 - const progress = expansion.value;
198 - // Hanging from the row top lets the text ride the growing edge and ignore the stale
199 - // height measured while it still wrapped in the compact slot. Layout props only:
200 - // Reanimated applies transforms frames ahead of layout, which tore the text from its frame.
201 - return {
202 - position: "absolute",
203 - overflow: "hidden",
204 - // The compact slot is unknown until its first layout, so the editor would draw over the + button.
205 - opacity: isExpanded || editorWidth.value > 0 ? 1 : 0,
206 - height,
207 - top: compactBottom * (1 - progress),
208 - left: compactInsets.left + (EXPANDED_EDITOR_INSET - compactInsets.left) * progress,
209 - // Snapping the far edge keeps the line from rewrapping while the near edge moves.
210 - right: isExpanded ? EXPANDED_EDITOR_INSET : compactInsets.right,
211 - };
212 - });
213 - const containerStyle = useAnimatedStyle(() => ({
214 - height: compactRowHeight + (expandedRowHeight - compactRowHeight) * expansion.value,
215 - }));
216 - return {
217 - isExpanded,
218 - containerStyle,
219 - // The expanded toolbar takes the row the text is leaving; reveal it once the text has lifted.
220 - // An entering animation hides it from its first frame, which a shared-value opacity cannot.
221 - toolbarControlsEntering:
222 - animate && isExpanded
223 - ? FadeIn.delay(COMPOSER_TRANSITION_DURATION_MS / 2)
224 - .duration(COMPOSER_TRANSITION_DURATION_MS / 2)
225 - .reduceMotion(ReduceMotion.System)
226 - : undefined,
227 - editorStyle,
228 - onRowLayout: (event: { nativeEvent: { layout: { width: number } } }) => {
229 - rowWidth.set(event.nativeEvent.layout.width);
230 - },
231 - onEditorLayout: (event: { nativeEvent: { layout: { x: number; width: number } } }) => {
232 - // The expanded toolbar gives this slot to the model control. Keep the
233 - // compact geometry for the return transition, rather than recording zero.
234 - if (!isExpanded) {
235 - editorX.set(event.nativeEvent.layout.x);
236 - editorWidth.set(event.nativeEvent.layout.width);
237 - setCompactWidth(Math.max(0, event.nativeEvent.layout.width - 8));
238 - }
239 - },
240 - editorProps: {
241 - singleLineCentered: !isExpanded,
242 - scrollEnabled: Platform.OS === "android" || contentHeight >= text.lineHeight * 4,
243 - contentInsetVertical: inset,
244 - onContentSizeChange: (size: { width: number; height: number }) => {
245 - setContentSize(size);
246 - },
247 - style: { flex: 1 },
248 - },
249 - };
250 -}
130
131 export interface ThreadComposerProps {
132 readonly isDraft?: boolean;
@@ -310,42 +189,11 @@ export interface ThreadComposerProps {
189 readonly onEditorFocusChange?: (focused: boolean) => void;
190 }
191
313 -// Android KeyboardStickyView tracks the IME; concurrent timed layout morphs cause jitter.
314 -const COMPOSER_TRANSITION_DURATION_MS = 220;
315 -// Side panes animate dock width; nested horizontal transitions would make the surface trail the toolbar.
316 -const composerHeightTransition: LayoutAnimationFunction = (values) => {
317 - "worklet";
318 - const timing = {
319 - duration: COMPOSER_TRANSITION_DURATION_MS,
320 - reduceMotion: ReduceMotion.System,
321 - };
322 - return {
323 - initialValues: {
324 - originX: values.targetOriginX,
325 - originY: values.currentOriginY,
326 - width: values.targetWidth,
327 - height: values.currentHeight,
328 - },
329 - animations: {
330 - originX: values.targetOriginX,
331 - originY: withTiming(values.targetOriginY, timing),
332 - width: values.targetWidth,
333 - height: withTiming(values.targetHeight, timing),
334 - },
335 - };
336 -};
337 -const COMPOSER_LAYOUT_TRANSITION = Platform.OS === "android" ? undefined : composerHeightTransition;
338 -// Share of the one-row composer the draft keeps; a long model name truncates first.
339 -const INLINE_EDITOR_MIN_WIDTH = "40%";
340 -const INLINE_EDITOR_HEIGHT = 36;
341 -
192 const COMPOSER_ATTACHMENT_ENTERING =
193 Platform.OS === "android"
194 ? FadeIn.duration(160)
195 : FadeIn.delay(COMPOSER_TRANSITION_DURATION_MS).duration(160).reduceMotion(ReduceMotion.System);
196
347 -const AnimatedGlassSurface = Animated.createAnimatedComponent(GlassSurface);
348 -
197 const FOLLOW_UP_ACTION_LABEL = {
198 queue: "Queue",
199 steer: "Steer now",
@@ -401,70 +249,6 @@ function SendActionButton(props: {
249 );
250 }
251
404 -function ComposerSurface(props: {
405 - readonly children: ReactNode;
406 - readonly style: ViewStyle;
407 - readonly animateLayout?: boolean;
408 -}) {
409 - const colors = useUniwindTheme();
410 - const targetBorderRadius =
411 - typeof props.style.borderRadius === "number" ? props.style.borderRadius : 0;
412 - const shouldAnimate = props.animateLayout !== false && Platform.OS !== "android";
413 - const animatedBorderRadius = useDerivedValue(() =>
414 - shouldAnimate
415 - ? withTiming(targetBorderRadius, {
416 - duration: COMPOSER_TRANSITION_DURATION_MS,
417 - reduceMotion: ReduceMotion.System,
418 - })
419 - : targetBorderRadius,
420 - );
421 - const borderCurve = props.style.borderCurve;
422 - const animatedShapeStyle = useAnimatedStyle(() => ({
423 - borderRadius: animatedBorderRadius.value,
424 - ...(borderCurve ? { borderCurve } : {}),
425 - }));
426 - const layoutTransition = shouldAnimate ? COMPOSER_LAYOUT_TRANSITION : undefined;
427 -
428 - // Animate every native frame or glass and content jump to final height inside the clip.
429 - return (
430 - <Animated.View
431 - className={
432 - Platform.OS === "android" ? undefined : "shadow-[0_6px_28px] shadow-adaptive-black-a15-a35"
433 - }
434 - layout={layoutTransition}
435 - style={[
436 - animatedShapeStyle,
437 - {
438 - overflow: "hidden",
439 - },
440 - ]}
441 - >
442 - <AnimatedGlassSurface
443 - chrome="none"
444 - fallbackColor={colors["--color-composer-surface"]}
445 - fallbackClassName="border border-composer-border"
446 - glassEffectStyle="regular"
447 - pointerEvents="none"
448 - tintColor="transparent"
449 - layout={layoutTransition}
450 - style={[{ position: "absolute", inset: 0 }, animatedShapeStyle]}
451 - >
452 - {null}
453 - </AnimatedGlassSurface>
454 - <Animated.View
455 - collapsable={false}
456 - layout={layoutTransition}
457 - style={[props.style, animatedShapeStyle]}
458 - >
459 - {props.children}
460 - </Animated.View>
461 - </Animated.View>
462 - );
463 -}
464 -
465 -/** Space below the composer pill, inside the bottom inset it is given. */
466 -export const THREAD_COMPOSER_BOTTOM_GUTTER = 6;
467 -
252 export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps) {
253 const project = useProject(scopeProjectRef(props.environmentId, props.selectedThread.projectId));
254 const { themeVariables: materialTheme } = useAppearancePreferences();
@@ -660,12 +444,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
444 );
445 const isVoiceInputPresented = voicePresentation.statusKind === "active";
446 const isExpanded = isFocused || settingsSheetPresentation.keepsComposerExpanded;
663 - const { layout } = useAdaptiveWorkspaceLayout();
664 - const floatingSidebarComposer = useAndroidFloatingTabs() && layout.usesSplitView;
665 - const sidebarWorkspaceTabs = useSidebarWorkspaceTabs();
666 - const deviceType = useDeviceType();
667 - const usesLargeControls = sidebarWorkspaceTabs === "picker" || deviceType === "pad";
668 - const surfacePaddingVertical = usesLargeControls ? 9 : floatingSidebarComposer ? 6 : 2;
447 + const { usesLargeControls, paddingVertical: surfacePaddingVertical } = useComposerChrome();
448 const [compactRowWidth, setCompactRowWidth] = useState(0);
449 const compactAttachmentLimit = compactRowWidth >= 500 ? 3 : 1;
450 // Animate only while typing; a thread switch or restored draft lands in place.
apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+3 -32
@@ -115,21 +115,14 @@ import Animated, {
115 useSharedValue,
116 withTiming,
117 } from "react-native-reanimated";
118 -import { useSafeAreaInsets } from "react-native-safe-area-context";
118 import { useBarOverlap } from "../../components/ui/useBarInset";
119 import {
120 useWorkspaceContentWidth,
121 WorkspaceSettledContentWidthContext,
122 useWorkspaceSettledContentWidth,
123 } from "../layout/workspace-content-width";
125 -import { useAdaptiveWorkspaceLayout } from "../layout/adaptive-workspace-context";
124 import { useNativeWorkspaceColumnsSupported } from "../../native/NativeWorkspaceColumns";
127 -import {
128 - useDeviceType,
129 - useDuoBottomBarInset,
130 - useNativeColumnLayoutMetrics,
131 - useNativeLayoutMetrics,
132 -} from "../../native/native-layout-metrics";
125 +import { useDeviceType, useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
126 import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
127 import { collectProviderUsageLimits } from "@t3tools/shared/usageLimits";
128 import type { ComposerEditorHandle } from "../../components/ComposerEditor";
@@ -196,9 +189,9 @@ import {
189 ESTIMATED_KEYBOARD_HEIGHT,
190 USER_INPUT_TOGGLE_DURATION_MS,
191 } from "./pendingUserInputLayout";
192 +import { useComposerBottomInset } from "../../components/ComposerSurface";
193 import {
194 COMPOSER_COLLAPSED_CHROME,
201 - THREAD_COMPOSER_BOTTOM_GUTTER,
195 ThreadComposer,
196 type ThreadComposerProps,
197 } from "./ThreadComposer";
@@ -407,7 +400,6 @@ function ThreadDetailBody(
400 },
401 ) {
402 const usesNativeWorkspaceColumns = useNativeWorkspaceColumnsSupported();
410 - const { layout } = useAdaptiveWorkspaceLayout();
403 const deviceType = useDeviceType();
404 const workspace = useWorkspaceTabs();
405 const sidebarSearchActive =
@@ -454,7 +446,6 @@ function ThreadDetailBody(
446 ...(tabId === undefined ? {} : { tabId }),
447 });
448 };
457 - const insets = useSafeAreaInsets();
449 const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
450 const liveKeyboardHeight = useKeyboardState((state) => state.height);
451 // Android can lose IME hide callbacks on backgrounding. Quarantine translation on resume unless focused input retained its keyboard.
@@ -492,7 +483,6 @@ function ThreadDetailBody(
483 const navigationHeaderHeight = useBarOverlap();
484 const [screenMetrics, setScreenMetrics] = useState<NativeLayoutMetrics | null>(null);
485 const columnMetrics = useNativeColumnLayoutMetrics();
495 - const windowMetrics = useNativeLayoutMetrics();
486 const nativeMetrics = usesNativeWorkspaceColumns ? columnMetrics : screenMetrics;
487 const controlInsets = deriveBottomControlInsets(nativeMetrics);
488 const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
@@ -542,27 +532,8 @@ function ThreadDetailBody(
532 const [isAtEnd, setIsAtEnd] = useState(true);
533 const [sendingWithKeyboard, setSendingWithKeyboard] = useState(false);
534 if (sendingWithKeyboard && !isKeyboardVisible) setSendingWithKeyboard(false);
545 - // Keep the bottom padding fixed while the keyboard animates. Changing it at
546 - // keyboardDidHide makes the composer land low, then jump back above the safe area.
547 - const bottomBarInset = useDuoBottomBarInset();
535 const hasSidebarTabBar = useSidebarWorkspaceTabs() === "picker";
549 - // A pushed screen temporarily inherits the outgoing tab bar's safe area.
550 - // Use the window edge so hiding that bar cannot move the composer mid-push.
551 - const bottomSafeArea =
552 - Platform.OS === "ios" ? (windowMetrics?.safeArea.bottom ?? insets.bottom) : insets.bottom;
553 - // The pill already adds its own gutter; iPad and Duo align its edge with the native bar.
554 - const alignedBottomInset =
555 - bottomBarInset ??
556 - (Platform.OS === "ios" && Platform.isPad
557 - ? Math.max(bottomSafeArea, 12) - (layout.usesSplitView ? 5 : 0)
558 - : undefined);
559 - // The Duo's floating sidebar pill ends three points below the composer's usual gutter.
560 - const composerBottomInset = Math.max(
561 - 0,
562 - (alignedBottomInset !== undefined
563 - ? alignedBottomInset - THREAD_COMPOSER_BOTTOM_GUTTER
564 - : Math.max(bottomSafeArea, 12)) - (hasSidebarTabBar ? 3 : 0),
565 - );
536 + const composerBottomInset = useComposerBottomInset();
537 const composerKeyboardOffset = composerBottomInset;
538 const contentPresentationKind = props.contentPresentation.kind;
539 const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, {
apps/mobile/src/lib/android-workspace-navigation.ts
+2 -1
@@ -76,7 +76,8 @@ export function androidWorkspaceDestinationAnimation(
76 usesSplitView: boolean,
77 ) {
78 if (!usesSplitView) return undefined;
79 - if (route.name === "Thread" || route.name === "PullRequest") return "none" as const;
79 + if (route.name === "Thread" || route.name === "PullRequest" || route.name === "Issue")
80 + return "none" as const;
81 if (route.name === "Settings" || !isSettingsRoute(route.name)) return undefined;
82 const below = routes[routes.findIndex((candidate) => candidate.key === route.key) - 1];
83 return below?.name === "Settings" ? ("none" as const) : ("fade" as const);
apps/mobile/src/lib/pullRequestNavigation.test.ts new
+43
@@ -0,0 +1,43 @@
1 +import { ProjectId } from "@t3tools/contracts";
2 +import { describe, expect, it } from "vite-plus/test";
3 +
4 +import { pullRequestCandidateForIssueLink } from "./pullRequestNavigation";
5 +
6 +const ref = { projectId: ProjectId.make("project-1"), host: "github.com", scope: "acme/app" };
7 +
8 +describe("pullRequestCandidateForIssueLink", () => {
9 + it("offers a pull request only where the host numbers issues and pull requests together", () => {
10 + expect(
11 + pullRequestCandidateForIssueLink("https://github.com/acme/app/issues/12", {
12 + ...ref,
13 + key: "12",
14 + }),
15 + ).toEqual({
16 + target: { projectId: "project-1", host: "github.com", repository: "acme/app", number: 12 },
17 + navigationUrl: undefined,
18 + });
19 + expect(
20 + pullRequestCandidateForIssueLink("https://gitlab.com/acme/app/-/issues/12", {
21 + ...ref,
22 + host: "gitlab.com",
23 + key: "12",
24 + }),
25 + ).toBeNull();
26 + expect(
27 + pullRequestCandidateForIssueLink("https://dev.azure.com/acme/app/_workitems/edit/12", {
28 + ...ref,
29 + host: "dev.azure.com",
30 + key: "12",
31 + }),
32 + ).toBeNull();
33 + });
34 +
35 + it("keeps a comment anchor for the pull request screen to scroll to", () => {
36 + expect(
37 + pullRequestCandidateForIssueLink("https://github.com/acme/app/issues/12#issuecomment-345", {
38 + ...ref,
39 + key: "12",
40 + })?.navigationUrl,
41 + ).toBe("https://github.com/acme/app/pull/12#issuecomment-345");
42 + });
43 +});
apps/mobile/src/lib/pullRequestNavigation.ts
+24 -1
@@ -1,7 +1,8 @@
1 import { parsePullRequestAnchor } from "@t3tools/shared/pullRequestAnchor";
2 import { resolveChangeRequestLinkTarget } from "@t3tools/client-runtime/change-request-links";
3 +import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
4 import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
4 -import { EnvironmentId, ProjectId } from "@t3tools/contracts";
5 +import { EnvironmentId, ProjectId, type IssueRef } from "@t3tools/contracts";
6
7 /** The PullRequest route for a change request link from a project, or null for the browser. */
8 export function nativePullRequestDestination(
@@ -29,3 +30,25 @@ export function nativePullRequestDestination(
30 ...(target.host === undefined ? {} : { host: target.host }),
31 };
32 }
33 +
34 +/**
35 + * The pull request an issue link may name instead, on a host that numbers both in one sequence
36 + * and writes every `#12` through its issue route. Null elsewhere. Only a candidate to read.
37 + */
38 +export function pullRequestCandidateForIssueLink(
39 + url: string,
40 + ref: Pick<IssueRef, "projectId" | "host" | "scope" | "key">,
41 +) {
42 + const candidateUrl = sourceControlClients.changeRequestUrlFromReferenceAutolink(url);
43 + const number = Number(ref.key);
44 + if (candidateUrl === null || !Number.isInteger(number) || number <= 0) return null;
45 + return {
46 + target: {
47 + projectId: ref.projectId,
48 + ...(ref.host === undefined ? {} : { host: ref.host }),
49 + repository: ref.scope,
50 + number,
51 + },
52 + navigationUrl: parsePullRequestAnchor(candidateUrl) ? candidateUrl : undefined,
53 + };
54 +}
apps/mobile/src/native/useOpenPullRequest.ts
+51 -2
@@ -1,10 +1,16 @@
1 import { useNavigation, useRoute, StackActions } from "@react-navigation/native";
2 -import { nativePullRequestDestination } from "../lib/pullRequestNavigation";
2 +import { resolveIssueLinkTarget } from "@t3tools/client-runtime/issue-links";
3 +import {
4 + nativePullRequestDestination,
5 + pullRequestCandidateForIssueLink,
6 +} from "../lib/pullRequestNavigation";
7 import { EnvironmentId, ThreadId } from "@t3tools/contracts";
8 import { useProjects, useThreadShell } from "../state/entities";
9 import { tryOpenExternalUrl } from "../lib/openExternalUrl";
10 import { appAtomRegistry } from "../state/atom-registry";
11 import { environmentServerConfigsAtom } from "../state/server";
12 +import { composerPullRequests } from "../state/pull-requests";
13 +import { useAtomQueryRunner } from "../state/use-atom-query-runner";
14 import { withKnownPullRequestSummary } from "../state/use-thread-pr";
15
16 let linkNavigationId = 0;
@@ -17,13 +23,56 @@ export function useNavigateToPullRequest(options?: { readonly replace?: boolean
23 const navigation = useNavigation();
24 const projects = useProjects();
25 const replace = options?.replace;
26 + const readPreview = useAtomQueryRunner(composerPullRequests.preview, {
27 + reportFailure: false,
28 + reportDefect: false,
29 + });
30 return async (url: string, context: PullRequestContext | null) => {
31 // Read at press time so a config push does not hand every link a new handler.
32 const serverConfigs = appAtomRegistry.get(environmentServerConfigsAtom);
33 const destination = nativePullRequestDestination(url, context, projects, (environmentId) =>
34 serverConfigs.has(environmentId),
35 );
26 - if (!destination) return tryOpenExternalUrl(url, "pull-request");
36 + if (!destination) {
37 + // An issue link from the same text opens the issue; anything else leaves for the browser.
38 + const environmentId = context && EnvironmentId.make(context.environmentId);
39 + const issue =
40 + environmentId && serverConfigs.get(environmentId)?.environment.capabilities.issues === true
41 + ? resolveIssueLinkTarget({
42 + url,
43 + projects: projects.filter((project) => project.environmentId === environmentId),
44 + preferredProjectId: context.projectId,
45 + })
46 + : null;
47 + if (!issue || !environmentId) return tryOpenExternalUrl(url, "pull-request");
48 + const candidate = pullRequestCandidateForIssueLink(url, issue.ref);
49 + if (candidate) {
50 + const preview = await readPreview({ environmentId, input: candidate.target });
51 + if (preview._tag === "Success") {
52 + const params = withKnownPullRequestSummary({
53 + ...candidate.target,
54 + environmentId,
55 + ...(candidate.navigationUrl
56 + ? { navigationUrl: candidate.navigationUrl, navigationId: nextLinkNavigationId() }
57 + : {}),
58 + });
59 + if (replace) navigation.dispatch(StackActions.replace("PullRequest", params));
60 + else navigation.dispatch(StackActions.push("PullRequest", params));
61 + return true;
62 + }
63 + }
64 + const issueParams = {
65 + environmentId,
66 + projectId: issue.ref.projectId,
67 + tracker: issue.ref.tracker,
68 + ...(issue.ref.host === undefined ? {} : { host: issue.ref.host }),
69 + scope: issue.ref.scope,
70 + issueKey: issue.ref.key,
71 + };
72 + if (replace) navigation.dispatch(StackActions.replace("Issue", issueParams));
73 + else navigation.dispatch(StackActions.push("Issue", issueParams));
74 + return true;
75 + }
76 const params = withKnownPullRequestSummary({
77 ...destination,
78 ...(destination.navigationUrl ? { navigationId: nextLinkNavigationId() } : {}),
apps/mobile/src/native/v5-workspace-context.tsx
+1
@@ -47,6 +47,7 @@ export const NativePrimaryColumnContext = createContext<{
47 readonly presented: boolean;
48 readonly selectedThreadKey: string | null;
49 readonly selectedPullRequestKey: string | null;
50 + readonly selectedIssueKey: string | null;
51 } | null>(null);
52 export const NativeWorkspaceInspectorContext = createContext<{
53 readonly content: InspectorContent | undefined;
apps/mobile/src/persistence/mobile-preferences.ts
+18
@@ -72,6 +72,17 @@ const WorkspaceSelections = Schema.Struct({
72 key: Schema.optional(Schema.String),
73 }),
74 ),
75 + issues: Schema.optional(
76 + Schema.Struct({
77 + environmentId: Schema.String,
78 + projectId: Schema.String,
79 + tracker: Schema.String,
80 + host: Schema.optional(Schema.String),
81 + scope: Schema.String,
82 + issueKey: Schema.String,
83 + key: Schema.optional(Schema.String),
84 + }),
85 + ),
86 settings: Schema.optional(Schema.String),
87 settingsKey: Schema.optional(Schema.String),
88 /** A draft the threads tab showed after its last chat; only meaningful in its session. */
@@ -98,6 +109,8 @@ const isThreadProject = Schema.is(ThreadProject);
109 export interface Preferences {
110 readonly navigationTabOrder?: readonly string[];
111 readonly hiddenNavigationTabs?: readonly string[];
112 + /** Whether pull requests or issues last held the tab bar slot they share. */
113 + readonly sharedSlotTab?: "pullRequests" | "issues";
114 readonly pullRequestHideTestFiles?: boolean;
115 /** Which hidden-by-default PR activity is shown: bot comments and resolved or dismissed ones. */
116 readonly pullRequestActivityVisibility?: PullRequestActivityVisibility;
@@ -189,6 +202,7 @@ function sanitizePreferences(parsed: Preferences): Preferences {
202 const preferences: {
203 navigationTabOrder?: readonly string[];
204 hiddenNavigationTabs?: readonly string[];
205 + sharedSlotTab?: "pullRequests" | "issues";
206 pullRequestHideTestFiles?: boolean;
207 pullRequestActivityVisibility?: PullRequestActivityVisibility;
208 pullRequestMergeMethod?: PullRequestMergeMethod;
@@ -239,6 +253,10 @@ function sanitizePreferences(parsed: Preferences): Preferences {
253 );
254 }
255
256 + if (parsed.sharedSlotTab === "pullRequests" || parsed.sharedSlotTab === "issues") {
257 + preferences.sharedSlotTab = parsed.sharedSlotTab;
258 + }
259 +
260 if (typeof parsed.pullRequestHideTestFiles === "boolean") {
261 preferences.pullRequestHideTestFiles = parsed.pullRequestHideTestFiles;
262 }
apps/mobile/src/state/issues.ts new
+29
@@ -0,0 +1,29 @@
1 +import {
2 + createIssueEnvironmentAtoms,
3 + createMergedIssueListAtoms,
4 + type IssueListTarget,
5 +} from "@t3tools/client-runtime/state/issues";
6 +import { useAtomValue } from "@effect/atom-react";
7 +import type { EnvironmentId } from "@t3tools/contracts";
8 +
9 +import { connectionAtomRuntime } from "../connection/runtime";
10 +import { appAtomRegistry } from "./atom-registry";
11 +import { formatEnvironmentQueryError } from "./query";
12 +
13 +export const issueEnvironment = createIssueEnvironmentAtoms(connectionAtomRuntime);
14 +
15 +const mergedIssueLists = createMergedIssueListAtoms(
16 + issueEnvironment.list,
17 + formatEnvironmentQueryError,
18 +);
19 +
20 +/** One listing read across every environment asked. */
21 +export function useIssueList(targets: ReadonlyArray<IssueListTarget>) {
22 + const view = useAtomValue(mergedIssueLists.atom(targets));
23 + return { ...view, refresh: () => mergedIssueLists.refresh(appAtomRegistry, targets) };
24 +}
25 +
26 +/** After a write the list cannot see, such as a new issue filed from a sheet. */
27 +export function refreshIssueLists(environmentId: EnvironmentId) {
28 + mergedIssueLists.refreshEnvironment(appAtomRegistry, environmentId);
29 +}
apps/mobile/src/state/query.ts
+6 -2
@@ -16,7 +16,11 @@ export interface EnvironmentQueryView<A> {
16 readonly refresh: () => void;
17 }
18
19 -function formatError(cause: Cause.Cause<unknown>): string {
19 +/** What a request cut off by a dropped connection says; it carries no error of its own. */
20 +export const ENVIRONMENT_REQUEST_INTERRUPTED = "The connection dropped before this finished.";
21 +
22 +export function formatEnvironmentQueryError(cause: Cause.Cause<unknown>): string {
23 + if (Cause.hasInterruptsOnly(cause)) return ENVIRONMENT_REQUEST_INTERRUPTED;
24 const error = Cause.squash(cause);
25 return error instanceof Error && error.message.trim().length > 0
26 ? error.message
@@ -34,7 +38,7 @@ export function useEnvironmentQuery<A, E>(
38 // Data may be structurally shared; only a settled success proves a new response.
39 successResult: result._tag === "Success" && !result.waiting ? result : null,
40 failure: result._tag === "Failure" ? Cause.squash(result.cause) : null,
37 - error: result._tag === "Failure" ? formatError(result.cause) : null,
41 + error: result._tag === "Failure" ? formatEnvironmentQueryError(result.cause) : null,
42 isPending: atom !== null && result.waiting,
43 isSuccess: result._tag === "Success",
44 refresh,
apps/web/src/components/issue/IssueDetailPanel.tsx
+16 -51
@@ -1,4 +1,9 @@
1 import { useAtomValue } from "@effect/atom-react";
2 +import {
3 + issueCloseReasonLabel,
4 + issueEventSentence,
5 + issueWriteAccess,
6 +} from "@t3tools/client-runtime/issue-presentation";
7 import { prependIssueComments } from "@t3tools/client-runtime/state/issues";
8 import {
9 issueAssigneeHeld,
@@ -71,11 +76,7 @@ import { IssueCommentComposer } from "./IssueCommentComposer";
76 import { IssueDetailGhost } from "./IssueDetailGhost";
77 import { ReactionBar } from "../pullRequest/PullRequestReactions";
78 import { PullRequestsUnavailableState } from "../pullRequest/PullRequestsUnavailableState";
74 -import {
75 - issueCloseReasonLabel,
76 - issueStatePresentation,
77 - issueTrackerPresentation,
78 -} from "./issuePresentation";
79 +import { issueTrackerPresentation, issueStatePresentation } from "./issuePresentation";
80
81 /**
82 * Links or unlinks the issue to the thread it is shown beside. Dispatches the orchestration
@@ -150,14 +151,6 @@ function IssueThreadLinkButton({
151 );
152 }
153
153 -/** Why a control is off, said once so each disabled affordance can point at it. */
154 -function writeBlockReason(detail: IssueDetail, canWrite: boolean): string | null {
155 - if (!canWrite) return "Writing to this tracker needs the source-control write scope.";
156 - if (!detail.writable)
157 - return "This issue is outside every project's own scope, so it is read-only here.";
158 - return null;
159 -}
160 -
154 function IssueReactionBar({
155 reactions,
156 canReact,
@@ -395,31 +388,6 @@ function IssueAssigneePicker({
388 );
389 }
390
398 -function eventSentence(event: IssueEvent): string {
399 - switch (event.kind) {
400 - case "closed":
401 - return event.detail
402 - ? `closed this as ${issueCloseReasonLabel(event.detail).toLowerCase()}`
403 - : "closed this";
404 - case "reopened":
405 - return "reopened this";
406 - case "labeled":
407 - return event.detail ? `added the ${event.detail} label` : "added a label";
408 - case "unlabeled":
409 - return event.detail ? `removed the ${event.detail} label` : "removed a label";
410 - case "assigned":
411 - return event.detail ? `assigned ${event.detail}` : "assigned someone";
412 - case "unassigned":
413 - return event.detail ? `unassigned ${event.detail}` : "unassigned someone";
414 - case "renamed":
415 - return event.detail ? `renamed this to “${event.detail}”` : "renamed this";
416 - case "referenced":
417 - return event.detail ? `referenced this from ${event.detail}` : "referenced this";
418 - case "state-changed":
419 - return event.detail ? `moved this to ${event.detail}` : "changed the state";
420 - }
421 -}
422 -
391 type TimelineItem =
392 | { kind: "comment"; at: string; comment: IssueComment }
393 | { kind: "event"; at: string; event: IssueEvent };
@@ -521,19 +489,16 @@ export function IssueDetailPanel({
489 ...detail.events.map((e): TimelineItem => ({ kind: "event", at: e.createdAt, event: e })),
490 ].sort((a, b) => Date.parse(a.at) - Date.parse(b.at));
491
524 - const blocked = writeBlockReason(detail, canWrite);
525 - const may = (capability: boolean, permission: boolean) =>
526 - blocked === null && capability && permission;
527 - const canComment = may(detail.capabilities.comment, detail.viewerPermissions.comment);
528 - const canEdit = may(detail.capabilities.edit, detail.viewerPermissions.edit);
529 - const canLabel = may(detail.capabilities.labels, detail.viewerPermissions.labels);
530 - const canAssign = may(detail.capabilities.assignees, detail.viewerPermissions.assignees);
531 - const canReact = blocked === null && detail.capabilities.reactions;
532 - const canSetState = may(detail.capabilities.states.length > 0, detail.viewerPermissions.setState);
492 + const access = issueWriteAccess(detail, canWrite);
493 + const { blocked } = access;
494 + const canComment = access.comment;
495 + const canEdit = access.edit;
496 + const canLabel = access.labels;
497 + const canAssign = access.assignees;
498 + const canReact = access.react;
499 + const canSetState = access.states.length > 0;
500 + const otherStates = access.states;
501 const tracker = issueTrackerPresentation(detail.tracker);
534 - const otherStates = detail.capabilities.states.filter(
535 - (state) => state.category !== detail.state.category || state.name !== detail.state.name,
536 - );
502 const closingStates = otherStates.filter((state) => state.category === "closed");
503 const openingStates = otherStates.filter((state) => state.category === "open");
504
@@ -943,7 +908,7 @@ export function IssueDetailPanel({
908 className="px-1 text-xs text-muted-foreground"
909 >
910 <PullRequestActorLabel actor={item.event.actor} />
946 - <span>{eventSentence(item.event)}</span>
911 + <span>{issueEventSentence(item.event)}</span>
912 <span>{formatRelativeTimeLabel(item.event.createdAt)}</span>
913 </PullRequestMetaLine>
914 ),
apps/web/src/components/issue/IssueRow.tsx
+1 -5
@@ -1,4 +1,4 @@
1 -import type { EnvironmentId, IssueListEntry } from "@t3tools/contracts";
1 +import type { EnvironmentIssueEntry } from "@t3tools/client-runtime/issue-list";
2 import { MessageSquareIcon } from "lucide-react";
3 import { memo } from "react";
4
@@ -16,10 +16,6 @@ import {
16 } from "../pullRequest/pullRequestPresentation";
17 import { IssueStateGlyph, issueTrackerPresentation } from "./issuePresentation";
18
19 -export interface EnvironmentIssueEntry extends IssueListEntry {
20 - readonly environmentId: EnvironmentId;
21 -}
22 -
19 export type IssueRowTarget = Pick<
20 EnvironmentIssueEntry,
21 "environmentId" | "projectId" | "tracker" | "host" | "scope" | "key" | "url"
apps/web/src/components/issue/IssuesPage.tsx
+17 -129
@@ -1,23 +1,20 @@
1 import { useAtomValue } from "@effect/atom-react";
2 import {
3 - issueEntryKey,
4 - mergeIssueListErrors,
5 - mergeIssueListPage,
6 -} from "@t3tools/client-runtime/state/issues";
7 -import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
3 + continueIssuePage,
4 + groupIssues,
5 + holdIssuePages,
6 + issueTrackerKey,
7 + type HeldIssuePage,
8 +} from "@t3tools/client-runtime/issue-list";
9 +import { issueEntryKey } from "@t3tools/client-runtime/state/issues";
10 import type {
11 EnvironmentId,
12 IssueInvolvement,
11 - IssueListCursors,
12 - IssueListEntry,
13 IssueListInput,
14 - IssueListProjectError,
15 - IssueListResult,
14 IssueListState,
15 IssueTrackerKind,
16 IssueTrackerSummary,
17 ProjectId,
20 - SourceControlProviderKind,
18 } from "@t3tools/contracts";
19 import { useNavigate, useSearch } from "@tanstack/react-router";
20 import {
@@ -33,11 +30,7 @@ import { Fragment, useEffect, useState, type ReactNode } from "react";
30
31 import { RefreshIcon } from "~/components/ui/refresh-icon";
32 import { IssueDetailPanel } from "~/components/issue/IssueDetailPanel";
36 -import {
37 - IssueRow,
38 - type EnvironmentIssueEntry,
39 - type IssueRowTarget,
40 -} from "~/components/issue/IssueRow";
33 +import { IssueRow, type IssueRowTarget } from "~/components/issue/IssueRow";
34 import {
35 issueListPreferences,
36 writeIssueListPreferences,
@@ -84,7 +77,6 @@ import {
77 } from "~/rightPanelStore";
78 import { useAtomCommand } from "~/state/use-atom-command";
79 import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
87 -import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
80 import { useProjects } from "~/state/entities";
81 import { useEnvironments, useIssuesSupported } from "~/state/environments";
82 import { issueEnvironment, useIssueList, type IssueListTarget } from "~/state/issues";
@@ -131,104 +123,6 @@ function getShortcutContext() {
123 };
124 }
125
134 -/** Rows from every environment that answered, with any continuation pages laid over them. */
135 -interface HeldPage {
136 - readonly answer: IssueListResult;
137 - readonly entries: ReadonlyArray<IssueListEntry>;
138 - readonly errors: ReadonlyArray<IssueListProjectError>;
139 - readonly nextCursors: IssueListCursors;
140 - /** Why the last "Load more" failed, until a retry succeeds or a new first page arrives. */
141 - readonly moreFailure: string | null;
142 -}
143 -
144 -function trackerKey(tracker: Pick<IssueTrackerSummary, "tracker" | "host">): string {
145 - return `${tracker.tracker} ${tracker.host.toLowerCase()}`;
146 -}
147 -
148 -/** Continuations are laid over the first page they continue; a new first page forgets them. */
149 -function holdPages(
150 - answers: ReadonlyArray<readonly [EnvironmentId, IssueListResult]>,
151 - pages: ReadonlyMap<EnvironmentId, HeldPage>,
152 -): ReadonlyMap<EnvironmentId, HeldPage> {
153 - const next = new Map<EnvironmentId, HeldPage>();
154 - for (const [environmentId, answer] of answers) {
155 - const previous = pages.get(environmentId);
156 - next.set(
157 - environmentId,
158 - previous?.answer === answer
159 - ? previous
160 - : {
161 - answer,
162 - entries: answer.entries,
163 - errors: answer.errors,
164 - nextCursors: answer.nextCursors,
165 - moreFailure: null,
166 - },
167 - );
168 - }
169 - return next;
170 -}
171 -
172 -function groupIssues(
173 - held: ReadonlyMap<EnvironmentId, HeldPage>,
174 - query: string,
175 - projects: ReadonlyArray<EnvironmentProject>,
176 -) {
177 - const byTracker = new Map<
178 - string,
179 - {
180 - tracker: IssueTrackerSummary;
181 - rows: EnvironmentIssueEntry[];
182 - errors: Array<{ projectTitle: string; message: string; environmentId: EnvironmentId }>;
183 - more: EnvironmentId[];
184 - }
185 - >();
186 - const needle = query.toLowerCase();
187 - for (const [environmentId, page] of held) {
188 - for (const tracker of page.answer.trackers) {
189 - const key = trackerKey(tracker);
190 - if (!byTracker.has(key)) byTracker.set(key, { tracker, rows: [], errors: [], more: [] });
191 - const group = byTracker.get(key)!;
192 - if (!group.tracker.configured && tracker.configured) group.tracker = tracker;
193 - if (Object.keys(page.nextCursors).some((c) => c.startsWith(`${tracker.host} `)))
194 - group.more.push(environmentId);
195 - }
196 - for (const entry of page.entries) {
197 - const key = trackerKey(entry);
198 - const group = byTracker.get(key);
199 - if (!group) continue;
200 - // A tracker that cannot search is narrowed here instead.
201 - if (
202 - needle.length > 0 &&
203 - group.tracker.capabilities?.search !== true &&
204 - !entry.title.toLowerCase().includes(needle) &&
205 - !entry.displayKey.toLowerCase().includes(needle)
206 - )
207 - continue;
208 - group.rows.push({ ...entry, environmentId });
209 - }
210 - for (const error of page.errors) {
211 - const project = projects.find(
212 - (p) => p.environmentId === environmentId && p.id === error.projectId,
213 - );
214 - const kind = project?.repositoryIdentity?.provider as SourceControlProviderKind | undefined;
215 - const host = kind
216 - ? sourceControlClients.changeRequestHost(project?.repositoryIdentity, kind)
217 - : null;
218 - const group =
219 - (host ? byTracker.get(`${kind} ${host.toLowerCase()}`) : undefined) ??
220 - [...byTracker.values()][0];
221 - group?.errors.push({ ...error, environmentId });
222 - }
223 - }
224 - for (const group of byTracker.values()) {
225 - group.rows.sort((a, b) => Date.parse(b.updatedAt) - Date.parse(a.updatedAt));
226 - }
227 - return [...byTracker.values()].sort((a, b) =>
228 - trackerKey(a.tracker).localeCompare(trackerKey(b.tracker)),
229 - );
230 -}
231 -
126 function hostOptionsFor(groups: ReturnType<typeof groupIssues>) {
127 const hosts = new Map<string, IssueTrackerSummary>();
128 for (const group of groups) hosts.set(group.tracker.host, group.tracker);
@@ -274,8 +168,8 @@ export function IssuesPage() {
168 const list = useIssueList(targets);
169 useLiveRefresh(list.refresh, { key: JSON.stringify(targets) });
170
277 - const [pages, setPages] = useState<ReadonlyMap<EnvironmentId, HeldPage>>(new Map());
278 - const held = holdPages(list.answers, pages);
171 + const [pages, setPages] = useState<ReadonlyMap<EnvironmentId, HeldIssuePage>>(new Map());
172 + const held = holdIssuePages(list.answers, pages);
173 const loadPage = useAtomCommand(issueEnvironment.listPage, { reportFailure: false });
174 const [loadingMore, setLoadingMore] = useState<EnvironmentId | null>(null);
175 const loadMore = async (environmentId: EnvironmentId) => {
@@ -292,18 +186,12 @@ export function IssuesPage() {
186 const next = new Map(current);
187 next.set(
188 environmentId,
295 - result._tag === "Failure"
296 - ? {
297 - ...page,
298 - moreFailure: failure instanceof Error ? failure.message : "The next page failed.",
299 - }
300 - : {
301 - answer: page.answer,
302 - entries: mergeIssueListPage(page.entries, result.value.entries),
303 - errors: mergeIssueListErrors(page.errors, result.value.errors),
304 - nextCursors: result.value.nextCursors,
305 - moreFailure: null,
306 - },
189 + continueIssuePage(
190 + page,
191 + result._tag === "Failure"
192 + ? { failure: failure instanceof Error ? failure.message : "The next page failed." }
193 + : result.value,
194 + ),
195 );
196 return next;
197 });
@@ -497,7 +385,7 @@ export function IssuesPage() {
385 const presentation = issueTrackerPresentation(group.tracker.tracker);
386 const showScope = new Set(group.rows.map((row) => row.scope.toLowerCase())).size > 1;
387 return (
500 - <section key={trackerKey(group.tracker)} className="flex flex-col gap-1">
388 + <section key={issueTrackerKey(group.tracker)} className="flex flex-col gap-1">
389 <h2 className="flex items-center gap-1.5 px-3 text-xs font-medium text-muted-foreground">
390 <presentation.Icon aria-hidden className="size-3.5" />
391 {presentation.providerName}
apps/web/src/components/issue/issuePresentation.tsx
+4 -14
@@ -1,3 +1,4 @@
1 +import { issueStateLabel } from "@t3tools/client-runtime/issue-presentation";
2 import type { IssueState, IssueTrackerKind } from "@t3tools/contracts";
3 import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
4 import { CircleCheckIcon, CircleDotIcon, CircleSlashIcon, TicketIcon } from "lucide-react";
@@ -34,25 +35,20 @@ export function issueStatePresentation(state: IssueState) {
35 if (state.category === "open") {
36 return {
37 ...PULL_REQUEST_STATE_PRESENTATION.open,
37 - label: state.name === "open" ? "Open" : state.name,
38 + label: issueStateLabel(state),
39 Icon: CircleDotIcon,
40 };
41 }
42 if (state.closeReason === "not-planned") {
43 return {
44 ...PULL_REQUEST_STATE_PRESENTATION.draft,
44 - label: "Closed as not planned",
45 + label: issueStateLabel(state),
46 Icon: CircleSlashIcon,
47 };
48 }
49 return {
50 ...PULL_REQUEST_STATE_PRESENTATION.merged,
50 - label:
51 - state.name === "closed"
52 - ? state.closeReason === "completed"
53 - ? "Closed as completed"
54 - : "Closed"
55 - : state.name,
51 + label: issueStateLabel(state),
52 Icon: CircleCheckIcon,
53 };
54 }
@@ -73,9 +69,3 @@ export function IssueStateGlyph({ state, className }: { state: IssueState; class
69 </Tooltip>
70 );
71 }
76 -
77 -/** "completed" → "Completed"; a reason the tracker spells with a dash reads as words. */
78 -export function issueCloseReasonLabel(reason: string): string {
79 - const words = reason.replace(/[-_]+/g, " ").trim();
80 - return words.charAt(0).toUpperCase() + words.slice(1);
81 -}
apps/web/src/state/issues.ts
+17 -56
@@ -1,67 +1,28 @@
1 -import { createIssueEnvironmentAtoms } from "@t3tools/client-runtime/state/issues";
2 -import type { EnvironmentId, IssueListInput, IssueListResult } from "@t3tools/contracts";
1 +import {
2 + createIssueEnvironmentAtoms,
3 + createMergedIssueListAtoms,
4 + type IssueListTarget,
5 + type MergedIssueList,
6 +} from "@t3tools/client-runtime/state/issues";
7 import { useAtomValue } from "@effect/atom-react";
4 -import * as Option from "effect/Option";
5 -import { AsyncResult, Atom } from "effect/reactivity";
8
9 import { connectionAtomRuntime } from "../connection/runtime";
10 import { appAtomRegistry } from "../rpc/atomRegistry";
11 import { formatEnvironmentQueryError } from "./query";
12
11 -export const issueEnvironment = createIssueEnvironmentAtoms(connectionAtomRuntime);
12 -
13 -export interface IssueListTarget {
14 - readonly environmentId: EnvironmentId;
15 - readonly input: IssueListInput;
16 -}
13 +export type { IssueListTarget };
14
18 -export interface MergedIssueListView {
19 - /** One answer per environment that has one, in target order. */
20 - readonly answers: ReadonlyArray<readonly [EnvironmentId, IssueListResult]>;
21 - /** The first environment that failed outright; the others may still have answered. */
22 - readonly error: string | null;
23 - readonly isPending: boolean;
24 - readonly refresh: () => void;
25 -}
15 +export const issueEnvironment = createIssueEnvironmentAtoms(connectionAtomRuntime);
16
27 -/**
28 - * The same listing read across every connected environment at once, as the pull-request page
29 - * does: React cannot subscribe to a list of atoms whose length changes, so the fan-out lives in
30 - * one derived atom keyed by the targets. An environment that fails contributes nothing rather
31 - * than blanking the page.
32 - */
33 -const mergedIssueListFamily = Atom.family((key: string) =>
34 - Atom.make((get) => {
35 - const targets = JSON.parse(key) as ReadonlyArray<IssueListTarget>;
36 - const answers: Array<readonly [EnvironmentId, IssueListResult]> = [];
37 - let error: string | null = null;
38 - let isPending = false;
39 - for (const target of targets) {
40 - const result = get(issueEnvironment.list(target));
41 - isPending ||= result.waiting;
42 - if (result._tag === "Failure" && error === null) {
43 - error = formatEnvironmentQueryError(result.cause);
44 - }
45 - const value = Option.getOrNull(AsyncResult.value(result));
46 - if (value !== null) answers.push([target.environmentId, value]);
47 - }
48 - return { answers, error, isPending };
49 - }).pipe(Atom.withLabel(`web-issues:list:${key}`)),
17 +const mergedIssueLists = createMergedIssueListAtoms(
18 + issueEnvironment.list,
19 + formatEnvironmentQueryError,
20 );
21
52 -const EMPTY_ISSUE_LIST = Atom.make({
53 - answers: [] as ReadonlyArray<readonly [EnvironmentId, IssueListResult]>,
54 - error: null as string | null,
55 - isPending: false,
56 -}).pipe(Atom.withLabel("web-issues:list:empty"));
57 -
58 -export function useIssueList(targets: ReadonlyArray<IssueListTarget>): MergedIssueListView {
59 - const key = JSON.stringify(targets);
60 - const view = useAtomValue(targets.length === 0 ? EMPTY_ISSUE_LIST : mergedIssueListFamily(key));
61 - const refresh = () => {
62 - for (const target of JSON.parse(key) as ReadonlyArray<IssueListTarget>) {
63 - appAtomRegistry.refresh(issueEnvironment.list(target));
64 - }
65 - };
66 - return { ...view, refresh };
22 +/** The same listing read across every connected environment, as the pull-request page does. */
23 +export function useIssueList(
24 + targets: ReadonlyArray<IssueListTarget>,
25 +): MergedIssueList & { readonly refresh: () => void } {
26 + const view = useAtomValue(mergedIssueLists.atom(targets));
27 + return { ...view, refresh: () => mergedIssueLists.refresh(appAtomRegistry, targets) };
28 }
packages/client-runtime/package.json
+8
@@ -563,6 +563,14 @@
563 "types": "./src/pullRequestReply.ts",
564 "default": "./src/pullRequestReply.ts"
565 },
566 + "./issue-presentation": {
567 + "types": "./src/issuePresentation.ts",
568 + "default": "./src/issuePresentation.ts"
569 + },
570 + "./issue-list": {
571 + "types": "./src/issueList.ts",
572 + "default": "./src/issueList.ts"
573 + },
574 "./pull-request-query": {
575 "types": "./src/pullRequestQuery.ts",
576 "default": "./src/pullRequestQuery.ts"
packages/client-runtime/src/issueList.ts new
+147
@@ -0,0 +1,147 @@
1 +import type {
2 + EnvironmentId,
3 + IssueListCursors,
4 + IssueListEntry,
5 + IssueListProjectError,
6 + IssueListResult,
7 + IssueTrackerSummary,
8 + SourceControlProviderKind,
9 +} from "@t3tools/contracts";
10 +
11 +import { mergeIssueListPage } from "./state/issues.ts";
12 +import { sourceControlClients } from "./sourceControlClients.ts";
13 +import type { EnvironmentProject } from "./state/shell.ts";
14 +
15 +export interface EnvironmentIssueEntry extends IssueListEntry {
16 + readonly environmentId: EnvironmentId;
17 +}
18 +
19 +/** Rows from every environment that answered, with any continuation pages laid over them. */
20 +export interface HeldIssuePage {
21 + readonly answer: IssueListResult;
22 + readonly entries: ReadonlyArray<IssueListEntry>;
23 + readonly errors: ReadonlyArray<IssueListProjectError>;
24 + /** What continuations reported, each beside the cursors it was asked to carry on. */
25 + readonly moreErrors: ReadonlyArray<{
26 + readonly asked: ReadonlyArray<string>;
27 + readonly errors: ReadonlyArray<IssueListProjectError>;
28 + }>;
29 + readonly nextCursors: IssueListCursors;
30 + /** Why the last "Load more" failed, until a retry succeeds or a new first page arrives. */
31 + readonly moreFailure: string | null;
32 +}
33 +
34 +export function issueTrackerKey(tracker: Pick<IssueTrackerSummary, "tracker" | "host">): string {
35 + return `${tracker.tracker} ${tracker.host.toLowerCase()}`;
36 +}
37 +
38 +/** Continuations are laid over the first page they continue; a new first page forgets them. */
39 +export function holdIssuePages(
40 + answers: ReadonlyArray<readonly [EnvironmentId, IssueListResult]>,
41 + pages: ReadonlyMap<EnvironmentId, HeldIssuePage>,
42 +): ReadonlyMap<EnvironmentId, HeldIssuePage> {
43 + const next = new Map<EnvironmentId, HeldIssuePage>();
44 + for (const [environmentId, answer] of answers) {
45 + const previous = pages.get(environmentId);
46 + next.set(
47 + environmentId,
48 + previous?.answer === answer
49 + ? previous
50 + : {
51 + answer,
52 + entries: answer.entries,
53 + errors: answer.errors,
54 + moreErrors: [],
55 + nextCursors: answer.nextCursors,
56 + moreFailure: null,
57 + },
58 + );
59 + }
60 + return next;
61 +}
62 +
63 +/**
64 + * Lays the next page over the rows held; a failure keeps them and says why. `asked` is the
65 + * cursors the page was asked to carry on: only those move, and what an earlier continuation
66 + * reported for any of them is replaced, so a retry that works takes its error away.
67 + */
68 +export function continueIssuePage(
69 + page: HeldIssuePage,
70 + next: IssueListResult | { readonly failure: string },
71 + asked: IssueListCursors = page.nextCursors,
72 +): HeldIssuePage {
73 + if ("failure" in next) return { ...page, moreFailure: next.failure };
74 + const moreErrors = page.moreErrors.filter((more) => !more.asked.some((key) => key in asked));
75 + if (next.errors.length > 0) moreErrors.push({ asked: Object.keys(asked), errors: next.errors });
76 + return {
77 + answer: page.answer,
78 + entries: mergeIssueListPage(page.entries, next.entries),
79 + errors: [...page.answer.errors, ...moreErrors.flatMap((more) => more.errors)],
80 + moreErrors,
81 + nextCursors: {
82 + ...Object.fromEntries(Object.entries(page.nextCursors).filter(([key]) => !(key in asked))),
83 + ...next.nextCursors,
84 + },
85 + moreFailure: null,
86 + };
87 +}
88 +
89 +export function groupIssues(
90 + held: ReadonlyMap<EnvironmentId, HeldIssuePage>,
91 + query: string,
92 + projects: ReadonlyArray<EnvironmentProject>,
93 +) {
94 + const byTracker = new Map<
95 + string,
96 + {
97 + tracker: IssueTrackerSummary;
98 + rows: EnvironmentIssueEntry[];
99 + errors: Array<{ projectTitle: string; message: string; environmentId: EnvironmentId }>;
100 + more: EnvironmentId[];
101 + }
102 + >();
103 + const needle = query.toLowerCase();
104 + for (const [environmentId, page] of held) {
105 + for (const tracker of page.answer.trackers) {
106 + const key = issueTrackerKey(tracker);
107 + if (!byTracker.has(key)) byTracker.set(key, { tracker, rows: [], errors: [], more: [] });
108 + const group = byTracker.get(key)!;
109 + if (!group.tracker.configured && tracker.configured) group.tracker = tracker;
110 + if (Object.keys(page.nextCursors).some((c) => c.startsWith(`${tracker.host} `)))
111 + group.more.push(environmentId);
112 + }
113 + for (const entry of page.entries) {
114 + const key = issueTrackerKey(entry);
115 + const group = byTracker.get(key);
116 + if (!group) continue;
117 + // A tracker that cannot search is narrowed here instead.
118 + if (
119 + needle.length > 0 &&
120 + group.tracker.capabilities?.search !== true &&
121 + !entry.title.toLowerCase().includes(needle) &&
122 + !entry.displayKey.toLowerCase().includes(needle)
123 + )
124 + continue;
125 + group.rows.push({ ...entry, environmentId });
126 + }
127 + for (const error of page.errors) {
128 + const project = projects.find(
129 + (p) => p.environmentId === environmentId && p.id === error.projectId,
130 + );
131 + const kind = project?.repositoryIdentity?.provider as SourceControlProviderKind | undefined;
132 + const host = kind
133 + ? sourceControlClients.changeRequestHost(project?.repositoryIdentity, kind)
134 + : null;
135 + const group =
136 + (host ? byTracker.get(`${kind} ${host.toLowerCase()}`) : undefined) ??
137 + [...byTracker.values()][0];
138 + group?.errors.push({ ...error, environmentId });
139 + }
140 + }
141 + for (const group of byTracker.values()) {
142 + group.rows.sort((a, b) => Date.parse(b.updatedAt) - Date.parse(a.updatedAt));
143 + }
144 + return [...byTracker.values()].sort((a, b) =>
145 + issueTrackerKey(a.tracker).localeCompare(issueTrackerKey(b.tracker)),
146 + );
147 +}
packages/client-runtime/src/issuePresentation.ts new
+69
@@ -0,0 +1,69 @@
1 +import type { IssueDetail, IssueEvent, IssueState } from "@t3tools/contracts";
2 +
3 +/** "completed" → "Completed"; a reason the tracker spells with a dash reads as words. */
4 +export function issueCloseReasonLabel(reason: string): string {
5 + const words = reason.replace(/[-_]+/g, " ").trim();
6 + return words.charAt(0).toUpperCase() + words.slice(1);
7 +}
8 +
9 +/** The tracker's own state name is the label, so a workflow tracker's "In Review" reads as itself. */
10 +export function issueStateLabel(state: IssueState): string {
11 + if (state.category === "open") return state.name === "open" ? "Open" : state.name;
12 + if (state.closeReason === "not-planned") return "Closed as not planned";
13 + if (state.name !== "closed") return state.name;
14 + return state.closeReason === "completed" ? "Closed as completed" : "Closed";
15 +}
16 +
17 +export function issueEventSentence(event: IssueEvent): string {
18 + switch (event.kind) {
19 + case "closed":
20 + return event.detail
21 + ? `closed this as ${issueCloseReasonLabel(event.detail).toLowerCase()}`
22 + : "closed this";
23 + case "reopened":
24 + return "reopened this";
25 + case "labeled":
26 + return event.detail ? `added the ${event.detail} label` : "added a label";
27 + case "unlabeled":
28 + return event.detail ? `removed the ${event.detail} label` : "removed a label";
29 + case "assigned":
30 + return event.detail ? `assigned ${event.detail}` : "assigned someone";
31 + case "unassigned":
32 + return event.detail ? `unassigned ${event.detail}` : "unassigned someone";
33 + case "renamed":
34 + return event.detail ? `renamed this to “${event.detail}”` : "renamed this";
35 + case "referenced":
36 + return event.detail ? `referenced this from ${event.detail}` : "referenced this";
37 + case "state-changed":
38 + return event.detail ? `moved this to ${event.detail}` : "changed the state";
39 + }
40 +}
41 +
42 +/**
43 + * What the viewer may do to an issue here: the client's write scope, the issue being inside a
44 + * project's scope, what the tracker can do at all, and what it grants this account.
45 + */
46 +export function issueWriteAccess(detail: IssueDetail, canWrite: boolean) {
47 + const blocked = !canWrite
48 + ? "Writing to this tracker needs the source-control write scope."
49 + : !detail.writable
50 + ? "This issue is outside every project's own scope, so it is read-only here."
51 + : null;
52 + const may = (capability: boolean, permission: boolean) =>
53 + blocked === null && capability && permission;
54 + const others = detail.capabilities.states.filter(
55 + (state) => state.category !== detail.state.category || state.name !== detail.state.name,
56 + );
57 + return {
58 + blocked,
59 + comment: may(detail.capabilities.comment, detail.viewerPermissions.comment),
60 + edit: may(detail.capabilities.edit, detail.viewerPermissions.edit),
61 + labels: may(detail.capabilities.labels, detail.viewerPermissions.labels),
62 + assignees: may(detail.capabilities.assignees, detail.viewerPermissions.assignees),
63 + react: blocked === null && detail.capabilities.reactions,
64 + /** The states the issue can move to; empty when the viewer may not move it. */
65 + states: may(detail.capabilities.states.length > 0, detail.viewerPermissions.setState)
66 + ? others
67 + : [],
68 + };
69 +}
packages/client-runtime/src/state/issues.test.ts
+1 -22
@@ -1,12 +1,7 @@
1 import type { IssueComment, IssueListEntry, IssueTrackerKind, ProjectId } from "@t3tools/contracts";
2 import { describe, expect, it } from "vite-plus/test";
3
4 -import {
5 - issueEntryKey,
6 - mergeIssueListErrors,
7 - mergeIssueListPage,
8 - prependIssueComments,
9 -} from "./issues.ts";
4 +import { issueEntryKey, mergeIssueListPage, prependIssueComments } from "./issues.ts";
5
6 function entry(overrides: Partial<IssueListEntry> & { key: string }): IssueListEntry {
7 return {
@@ -30,22 +25,6 @@ function entry(overrides: Partial<IssueListEntry> & { key: string }): IssueListE
25 };
26 }
27
33 -describe("mergeIssueListErrors", () => {
34 - it("keeps earlier failures and lets a continuation's replace its project's", () => {
35 - const api = "api" as ProjectId;
36 - const web = "web" as ProjectId;
37 - const held = [
38 - { projectId: api, projectTitle: "api", message: "boom" },
39 - { projectId: web, projectTitle: "web", message: "first" },
40 - ];
41 - const page = [{ projectId: web, projectTitle: "web", message: "rate limited" }];
42 - expect(mergeIssueListErrors(held, page).map((error) => error.message)).toEqual([
43 - "boom",
44 - "rate limited",
45 - ]);
46 - });
47 -});
48 -
28 describe("mergeIssueListPage", () => {
29 it("keeps rows from scopes the page did not continue and orders by update", () => {
30 const held = [
packages/client-runtime/src/state/issues.ts
+73 -13
@@ -3,12 +3,14 @@ import {
3 type EnvironmentId,
4 type IssueComment,
5 type IssueListEntry,
6 - type IssueListProjectError,
6 + type IssueListInput,
7 type IssueListResult,
8 type IssueRef,
9 } from "@t3tools/contracts";
10 +import type * as Cause from "effect/Cause";
11 import * as Effect from "effect/Effect";
11 -import { Atom, type AtomRegistry } from "effect/reactivity";
12 +import * as Option from "effect/Option";
13 +import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
14
15 import {
16 createAtomCommandScheduler,
@@ -42,16 +44,6 @@ export function mergeIssueListPage(
44 return [...byKey.values()].sort((a, b) => Date.parse(b.updatedAt) - Date.parse(a.updatedAt));
45 }
46
45 -/** A continuation's failures for a project replace the ones it reported before. */
46 -export function mergeIssueListErrors(
47 - held: ReadonlyArray<IssueListProjectError>,
48 - page: ReadonlyArray<IssueListProjectError>,
49 -): ReadonlyArray<IssueListProjectError> {
50 - if (page.length === 0) return held;
51 - const replaced = new Set(page.map((error) => error.projectId));
52 - return [...held.filter((error) => !replaced.has(error.projectId)), ...page];
53 -}
54 -
47 /** Older comments go in front: the detail carries the newest page and pages walk backwards. */
48 export function prependIssueComments(
49 current: ReadonlyArray<IssueComment>,
@@ -172,4 +164,72 @@ export function createIssueEnvironmentAtoms<R, E>(
164 };
165 }
166
175 -export type IssueListAnswer = IssueListResult;
167 +export interface IssueListTarget {
168 + readonly environmentId: EnvironmentId;
169 + readonly input: IssueListInput;
170 +}
171 +
172 +export interface MergedIssueList {
173 + /** One answer per environment that has one, in target order. */
174 + readonly answers: ReadonlyArray<readonly [EnvironmentId, IssueListResult]>;
175 + /** The first environment that failed outright; the others may still have answered. */
176 + readonly error: string | null;
177 + readonly isPending: boolean;
178 +}
179 +
180 +const NO_ISSUE_LISTS: MergedIssueList = { answers: [], error: null, isPending: false };
181 +
182 +/**
183 + * One listing read across every environment at once: React cannot subscribe to a list of atoms
184 + * whose length changes, so the fan-out lives in one derived atom keyed by the targets. An
185 + * environment that fails contributes nothing rather than blanking the list.
186 + */
187 +export function createMergedIssueListAtoms<E>(
188 + list: (target: IssueListTarget) => Atom.Atom<AsyncResult.AsyncResult<IssueListResult, E>>,
189 + formatError: (cause: Cause.Cause<E>) => string,
190 +) {
191 + const empty = Atom.make(NO_ISSUE_LISTS).pipe(Atom.withLabel("issues:merged-list:empty"));
192 + const family = Atom.family((key: string) =>
193 + Atom.make((get): MergedIssueList => {
194 + const answers: Array<readonly [EnvironmentId, IssueListResult]> = [];
195 + let error: string | null = null;
196 + let isPending = false;
197 + for (const target of JSON.parse(key) as ReadonlyArray<IssueListTarget>) {
198 + const result = get(list(target));
199 + isPending ||= result.waiting;
200 + if (result._tag === "Failure" && error === null) error = formatError(result.cause);
201 + const value = Option.getOrNull(AsyncResult.value(result));
202 + if (value !== null) answers.push([target.environmentId, value]);
203 + }
204 + return { answers, error, isPending };
205 + }).pipe(Atom.withLabel(`issues:merged-list:${key}`)),
206 + );
207 + const refresh = (
208 + registry: AtomRegistry.AtomRegistry,
209 + targets: ReadonlyArray<IssueListTarget>,
210 + ) => {
211 + for (const target of targets) registry.refresh(list(target));
212 + };
213 + // Every listing asked for, so a write made elsewhere can refresh the ones still shown.
214 + const asked = new Map<string, ReadonlyArray<IssueListTarget>>();
215 + return {
216 + atom: (targets: ReadonlyArray<IssueListTarget>) => {
217 + if (targets.length === 0) return empty;
218 + const key = JSON.stringify(targets);
219 + asked.set(key, targets);
220 + return family(key);
221 + },
222 + refresh,
223 + /** Refreshes each listing of `environmentId` that something still reads. */
224 + refreshEnvironment: (registry: AtomRegistry.AtomRegistry, environmentId: EnvironmentId) => {
225 + const live = new Set(registry.getNodes().keys());
226 + for (const [key, targets] of asked) {
227 + if (!live.has(family(key))) continue;
228 + refresh(
229 + registry,
230 + targets.filter((target) => target.environmentId === environmentId),
231 + );
232 + }
233 + },
234 + };
235 +}
vite.config.ts
+1
@@ -647,6 +647,7 @@ export default defineConfig({
647 "apps/mobile/src/features/review/useNativeReviewDiffBridge.ts",
648 "apps/mobile/src/features/settings/SettingsEnvironmentsRouteScreen.tsx",
649 "apps/mobile/src/features/threads/ThreadComposer.tsx",
650 + "apps/mobile/src/components/ComposerSurface.tsx",
651 "apps/mobile/src/features/threads/ThreadFeed.tsx",
652 "apps/mobile/src/features/threads/ThreadQueueControl.tsx",
653 "apps/mobile/src/features/review/ReviewCommentCard.tsx",