Skip to content

A one-of-a-kind resume builder that keeps your privacy in mind. Completely secure, customizable, portable, open-source and free forever. Try it out today!

26.3 KB
Raw Blame
import type { ApplicationSort } from "./list";
import type { ApplicationSummary } from "./types";
import type { ApplicationClosedReason } from "@reactive-resume/schema/applications/data";
import { ph, plural } from "@lingui/core/macro";
import { useLingui } from "@lingui/react/macro";
import { useRouter } from "expo-router";
import Storage from "expo-sqlite/kv-store";
import { useEffect, useRef, useState } from "react";
import { AccessibilityInfo, RefreshControl, Pressable, SectionList, View } from "react-native";
import Animated from "react-native-reanimated";
import { applicationError } from "./error";
import { useApplicationLanes } from "./lane-queries";
import { getLaneLabel, resolveLane } from "./lanes";
import { filterApplications, groupApplications, visibleSelection } from "./list";
import { describeNextStep, getNextStep, needsFollowUp } from "./next-step";
import { useApplicationDetailPrefetch, useApplicationMutations, useApplications } from "./queries";
import { offerHintFor, useMoveWithUndo, useOfferHints } from "./stage-actions";
import { CLOSED_REASONS, getClosedReasonLabel, PIPELINE } from "./stages";
import { getAccountScope, useSession } from "@/auth/session";
import { useNow, useUserTime } from "@/features/application-detail/hooks";
import { useApplicationSearch } from "@/features/applications-board/search";
import { ApplicationsViewFrame } from "@/features/applications-board/views";
import { routes } from "@/routes";
import { supportsUnmodifiedCommands, useKeyCommands, useRegisteredKeyCommands } from "@/shell/key-commands";
import {
	Banner,
	Button,
	EmptyState,
	Icon,
	IconButton,
	ListRow,
	Screen,
	SelectSheet,
	Sheet,
	Skeleton,
	Switch,
	Text,
	TextField,
	listItemMotion,
	useFirstAppearance,
	useReducedMotion,
	useTheme,
} from "@/ui";
import { usePullRefresh } from "@/ui/use-pull-refresh";

const VIEWABILITY_CONFIG = { itemVisiblePercentThreshold: 30 };

// Dismissed follow-up nudges, remembered on this device as on web.
const NUDGE_STORAGE_KEY = "applications-follow-up-dismissed";

function readDismissed(): string[] {
	try {
		const parsed: unknown = JSON.parse(Storage.getItemSync(NUDGE_STORAGE_KEY) ?? "[]");
		return Array.isArray(parsed) ? parsed.filter((id): id is string => typeof id === "string") : [];
	} catch {
		return [];
	}
}

export function ApplicationsListScreen() {
	const session = useSession();
	const { space } = useTheme();
	// Discard selection/forms when switching servers or leaving the authenticated session.
	return session.status === "signed-in" ? (
		<ApplicationsList key={getAccountScope() ?? session.server} />
	) : (
		<Screen>{session.status === "loading" ? <Skeleton height={space.s12} /> : <SignedOut />}</Screen>
	);
}
function SignedOut() {
	const router = useRouter();
	const { t } = useLingui();
	return <Button label={t`Sign in to view applications`} onPress={() => router.push(routes.signIn())} />;
}
function ApplicationsList() {
	const router = useRouter();
	const { t, i18n } = useLingui();
	const { colors, space, radius, size } = useTheme();
	const query = useApplications();
	const now = useNow();
	const lanes = useApplicationLanes();
	const pull = usePullRefresh(query.refetch);
	const firstAppearance = useFirstAppearance(!query.isPending);
	const reduced = useReducedMotion();
	const { timeZone } = useUserTime();
	const { bulkUpdate, bulkDelete, logFollowUp } = useApplicationMutations();
	const offerHints = useOfferHints();
	const moveWithUndo = useMoveWithUndo();
	const { search, setSearch, needsYou, clearFilters } = useApplicationSearch();
	const [tag, setTag] = useState("");
	const [showClosed, setShowClosed] = useState(false);
	// Next step first, as on web: what's dated soonest, then whatever has waited longest in its stage.
	const [sort, setSort] = useState<ApplicationSort>("next");
	const [direction, setDirection] = useState<"asc" | "desc">("asc");
	const [collapsed, setCollapsed] = useState<Set<string>>(new Set());
	const listRef = useRef<SectionList<ApplicationSummary>>(null);
	const [keyboardMode, setKeyboardMode] = useState(false);
	const [focusedId, setFocusedId] = useState<string | null>(null);
	const [selected, setSelected] = useState<Set<string>>(new Set());
	const [selecting, setSelecting] = useState(false);
	const [filters, setFilters] = useState(false);
	const [bulk, setBulk] = useState<"move" | "tag" | "close" | "delete" | null>(null);
	const [moveLaneId, setMoveLaneId] = useState("");
	const selectedLane = lanes.active.find((lane) => lane.id === moveLaneId);
	const moveLane = selectedLane ?? resolveLane(lanes.lanes, { status: "applied" });
	const laneAvailable = !moveLaneId || !!selectedLane;
	const [reason, setReason] = useState<ApplicationClosedReason>("not-selected");
	const [newTag, setNewTag] = useState("");
	const [busy, setBusy] = useState(false);
	const [failure, setFailure] = useState<string | null>(null);
	const [result, setResult] = useState<string | null>(null);
	const lock = useRef(false);
	const applications = query.data ?? [];
	const laneList = lanes.supported ? lanes.lanes : undefined;
	const [followUpOnly, setFollowUpOnly] = useState(false);
	const [dismissed, setDismissed] = useState(readDismissed);
	// Same rule as web and Career → Today: a due follow-up, or ten days without a reply.
	const owesFollowUp = (application: (typeof applications)[number]) =>
		needsFollowUp(getNextStep(application, now, laneList, timeZone, offerHintFor(offerHints, application.id)), now);
	const owed = applications
		.filter((application) => !dismissed.includes(application.id) && owesFollowUp(application))
		.map((application) => ({
			application,
			step: getNextStep(application, now, laneList, timeZone, offerHintFor(offerHints, application.id)),
		}))
		.sort((a, b) => (b.step.kind === "no-reply" ? b.step.days : -1) - (a.step.kind === "no-reply" ? a.step.days : -1));
	const company = owed[0]?.application.company ?? "";
	const count = owed.length;
	const days = owed[0]?.step.kind === "no-reply" ? owed[0].step.days : 0;
	const dismissOwed = () => {
		const next = [...new Set([...dismissed, ...owed.map(({ application }) => application.id)])];
		setDismissed(next);
		try {
			Storage.setItemSync(NUDGE_STORAGE_KEY, JSON.stringify(next));
		} catch {
			// Without storage the nudge is dismissed for this visit only.
		}
	};
	const filtered = filterApplications(
		applications,
		{ search, tag, showClosed, needsYou },
		now,
		timeZone,
		offerHints,
	).filter((application) => !followUpOnly || owesFollowUp(application));
	const filtersActive = Boolean(search.trim() || tag || showClosed || followUpOnly || needsYou);
	const groups = groupApplications(filtered, sort, direction, now, laneList, timeZone, offerHints);
	const selectedIds = visibleSelection(groups, collapsed, selected);
	if (selectedIds.length !== selected.size) setSelected(new Set(selectedIds));
	const onViewableItemsChanged = useApplicationDetailPrefetch();
	const tags = [...new Set(applications.flatMap((item) => item.tags))].sort();
	const changeFilters = (change: () => void) => {
		change();
		setSelected(new Set());
	};
	const toggle = (id: string) =>
		setSelected((current) => {
			const next = new Set(current);
			if (next.has(id)) next.delete(id);
			else next.add(id);
			return next;
		});
	const visibleRows = query.isError ? [] : groups.flatMap((group) => (collapsed.has(group.status) ? [] : group.data));
	const focusedRow = visibleRows.find((row) => row.id === focusedId);
	const focusRow = (id: string) => setFocusedId(id);

	const step = (direction: number) => {
		const index = visibleRows.findIndex((row) => row.id === focusedId);
		const next = visibleRows[index < 0 ? 0 : Math.max(0, Math.min(visibleRows.length - 1, index + direction))];
		if (next) focusRow(next.id);
	};
	useKeyCommands(
		keyboardMode && !busy && !query.isError
			? [
					{ id: "applications-next", input: "j", title: t`Next application`, modifier: "none", run: () => step(1) },
					{
						id: "applications-previous",
						input: "k",
						title: t`Previous application`,
						modifier: "none",
						run: () => step(-1),
					},
					{
						id: "applications-open",
						input: "enter",
						title: t`Open application`,
						modifier: "none",
						run: () => {
							if (focusedRow) router.push(routes.applicationDetails(focusedRow.id));
						},
					},
					{
						id: "applications-select",
						input: "x",
						title: t`Toggle selection`,
						modifier: "none",
						run: () => {
							if (focusedRow) {
								setSelecting(true);
								toggle(focusedRow.id);
							}
						},
					},
					{
						id: "applications-follow-up",
						input: "f",
						title: t`Followed up`,
						modifier: "none",
						run: () => {
							if (
								focusedRow &&
								focusedRow.status !== "saved" &&
								focusedRow.status !== "closed" &&
								!logFollowUp.isPending
							)
								logFollowUp.mutate({ id: focusedRow.id });
						},
					},
					...PIPELINE.map((status, index) => ({
						id: `applications-stage-${status}`,
						input: `${index + 1}`,
						modifier: "none" as const,
						title: t`Moved to ${getLaneLabel(resolveLane(lanes.lanes, { status }))}`,
						run: () => {
							if (!focusedRow || !lanes.ready) return;
							const lane = resolveLane(lanes.lanes, { status });
							if (resolveLane(lanes.lanes, focusedRow).id === lane.id) return;
							moveWithUndo({
								applications: [focusedRow],
								lane,
								supported: lanes.supported,
								message: t`Moved to ${getLaneLabel(lane)}`,
							});
						},
					})),
				]
			: [],
		"screen",
	);
	const triageActive = useRegisteredKeyCommands().some((command) => command.id === "applications-next");
	const focusAnnouncement = focusedRow ? `${focusedRow.role} · ${focusedRow.company}` : "";
	useEffect(() => {
		if (triageActive && focusAnnouncement) AccessibilityInfo.announceForAccessibility(focusAnnouncement);
	}, [triageActive, focusedId, focusAnnouncement]);
	useEffect(() => {
		if (!triageActive || !focusedId) return;
		const sectionIndex = groups.findIndex((group) => group.data.some((row) => row.id === focusedId));
		const itemIndex = groups[sectionIndex]?.data.findIndex((row) => row.id === focusedId) ?? -1;
		const group = groups[sectionIndex];
		if (group && itemIndex >= 0 && !collapsed.has(group.status))
			listRef.current?.scrollToLocation({ sectionIndex, itemIndex, animated: false, viewPosition: 0.5 });
	}, [triageActive, focusedId, groups, collapsed]);
	const applyBulk = async () => {
		if (
			!lanes.ready ||
			(bulk === "move" && !laneAvailable) ||
			!bulk ||
			lock.current ||
			!selectedIds.length ||
			selectedIds.length > 200 ||
			(bulk === "tag" && !newTag.trim())
		)
			return;
		const ids = selectedIds;
		// Moves and closes show at once with Undo; the server gets them when the toast ends.
		if (bulk === "move" || bulk === "close") {
			const lane = bulk === "close" ? resolveLane(lanes.lanes, { status: "closed" }) : moveLane;
			moveWithUndo({
				applications: ids.map((id) => ({ id })),
				lane,
				supported: lanes.supported,
				...(lane.category === "closed" && !lane.closedReason ? { closedReason: reason } : {}),
				message:
					lane.category === "closed"
						? plural(ids.length, { one: "# application closed", other: "# applications closed" })
						: plural(ids.length, {
								one: `# application moved to ${getLaneLabel(lane)}`,
								other: `# applications moved to ${getLaneLabel(lane)}`,
							}),
			});
			setBulk(null);
			setSelected(new Set());
			setSelecting(false);
			return;
		}
		lock.current = true;
		setBusy(true);
		setFailure(null);
		try {
			const count =
				bulk === "delete"
					? (await bulkDelete.mutateAsync({ ids })).deleted
					: (await bulkUpdate.mutateAsync({ ids, addTags: [newTag.trim()] })).updated;
			setResult(
				plural(ids.length, {
					one: `${ph({ count: i18n.number(count) })} of # application changed.`,
					other: `${ph({ count: i18n.number(count) })} of # applications changed.`,
				}),
			);
			setBulk(null);
			setSelected(new Set());
			setSelecting(false);
			setNewTag("");
		} catch (cause) {
			setFailure(applicationError(cause));
		} finally {
			lock.current = false;
			setBusy(false);
		}
	};
	const content = (
		<>
			<View style={{ flexDirection: "row", flexWrap: "wrap", gap: space.s3 }}>
				<Button
					label={t`Trash`}
					variant="secondary"
					icon="trash"
					disabled={busy}
					onPress={() => router.push(routes.applicationTrash())}
				/>
				<Button
					label={t`Sort and filter`}
					variant="secondary"
					icon="sliders-horizontal"
					disabled={busy}
					onPress={() => setFilters(true)}
				/>
				{supportsUnmodifiedCommands && (
					<Button
						label={keyboardMode ? t`Stop keyboard triage` : t`Keyboard triage`}
						variant="secondary"
						onPress={() => {
							if (!keyboardMode && !focusedRow && visibleRows[0]) focusRow(visibleRows[0].id);
							setKeyboardMode(!keyboardMode);
						}}
					/>
				)}
				{selecting && (
					<Button
						label={t`Done selecting`}
						variant="link"
						disabled={busy}
						onPress={() => {
							setSelecting(false);
							setSelected(new Set());
						}}
					/>
				)}
			</View>
			{triageActive && focusedRow && <Text color="ink2">{focusAnnouncement}</Text>}
			{(search || tag || showClosed) && (
				<Text color="ink2">
					{plural(filtered.length, { one: "# match", other: "# matches" })}
					{tag ? ` · ${tag}` : ""}
					{showClosed ? ` · ${t`Including closed`}` : ""}
				</Text>
			)}
			{followUpOnly ? (
				<Banner
					tone="info"
					icon="clock"
					message={plural(filtered.length, {
						one: "Showing # application that needs a follow-up.",
						other: "Showing # applications that need a follow-up.",
					})}
					action={{ label: t`Show all`, onPress: () => changeFilters(() => setFollowUpOnly(false)) }}
				/>
			) : owed[0] ? (
				<Banner
					tone="warn"
					icon="clock"
					message={
						owed.length > 1
							? plural(count, {
									one: "# application needs a follow-up.",
									other: "# applications need a follow-up.",
								})
							: owed[0].step.kind === "no-reply" && owed[0].step.after === "interview"
								? plural(days, {
										one: `${company}: no word since your interview # day ago. A short follow-up is usually fine now.`,
										other: `${company}: no word since your interview # days ago. A short follow-up is usually fine now.`,
									})
								: owed[0].step.kind === "no-reply"
									? plural(days, {
											one: `${company}: no reply for # day. A short follow-up is usually fine now.`,
											other: `${company}: no reply for # days. A short follow-up is usually fine now.`,
										})
									: t`${company}: a follow-up is due.`
					}
					action={
						owed.length > 1
							? {
									label: t`Show`,
									onPress: () =>
										changeFilters(() => {
											setShowClosed(false);
											setFollowUpOnly(true);
										}),
								}
							: { label: t`Open`, onPress: () => router.push(routes.applicationDetails(owed[0]?.application.id ?? "")) }
					}
					onDismiss={dismissOwed}
				/>
			) : null}
			{failure && bulk === null && <Banner tone="danger" message={failure} onDismiss={() => setFailure(null)} />}
			{result && <Banner tone="info" message={result} onDismiss={() => setResult(null)} />}
			{query.isError && (
				<>
					<Banner tone="warn" message={applicationError(query.error)} />
					<Button label={t`Retry loading applications`} onPress={() => void query.refetch()} />
				</>
			)}
			{!query.isError && query.isPending && (
				<>
					<Skeleton height={space.s12} />
					<Skeleton height={space.s12} />
					<Skeleton height={space.s12} />
				</>
			)}
			{selecting && (
				<>
					<Text variant="title">{t`${i18n.number(selectedIds.length)} selected`}</Text>
					<View style={{ flexDirection: "row", flexWrap: "wrap", gap: space.s2 }}>
						<Button
							label={t`Select all`}
							variant="secondary"
							disabled={busy}
							onPress={() =>
								setSelected(
									new Set(
										groups
											.filter((group) => !collapsed.has(group.status))
											.flatMap((group) => group.data.map((item) => item.id)),
									),
								)
							}
						/>
						<Button
							label={t`Tags…`}
							variant="secondary"
							disabled={busy || !lanes.ready || !selectedIds.length}
							onPress={() => {
								setFailure(null);
								setBulk("tag");
							}}
						/>
						<Button
							label={t`Move to…`}
							variant="secondary"
							disabled={busy || !lanes.ready || !selectedIds.length}
							onPress={() => {
								setFailure(null);
								setBulk("move");
							}}
						/>
						<Button
							label={t`Close…`}
							variant="secondary"
							disabled={busy || !lanes.ready || !selectedIds.length}
							onPress={() => {
								setFailure(null);
								setBulk("close");
							}}
						/>
						<Button label={t`Clear selection`} variant="ghost" disabled={busy} onPress={() => setSelected(new Set())} />
						<Button
							label={t`Move to Trash`}
							variant="danger"
							disabled={busy || !lanes.ready || !selectedIds.length}
							onPress={() => {
								setFailure(null);
								setBulk("delete");
							}}
						/>
					</View>
					{selectedIds.length > 200 && (
						<Banner tone="warn" message={t`Choose up to 200 applications per bulk action.`} />
					)}
				</>
			)}
		</>
	);
	return (
		<ApplicationsViewFrame
			current="list"
			search={{ value: search, onChangeText: (value) => changeFilters(() => setSearch(value)), disabled: busy }}
			addDisabled={busy}
		>
			<Screen scroll={false} contentStyle={{ padding: 0 }}>
				<SectionList
					ref={listRef}
					sections={
						query.isError
							? []
							: groups.map((group) => ({
									...group,
									total: group.data.length,
									data: collapsed.has(group.status) ? [] : group.data,
								}))
					}
					onScrollToIndexFailed={({ averageItemLength, index }) => {
						listRef.current?.getScrollResponder()?.scrollTo({ y: averageItemLength * index, animated: false });
					}}
					extraData={{ keyboardMode, focusedId, selectedIds }}
					keyExtractor={(item) => item.id}
					onViewableItemsChanged={onViewableItemsChanged}
					viewabilityConfig={VIEWABILITY_CONFIG}
					keyboardShouldPersistTaps="handled"
					refreshControl={<RefreshControl {...pull} tintColor={colors.accent} colors={[colors.accent]} />}
					stickySectionHeadersEnabled={false}
					contentContainerStyle={{ padding: space.s4, gap: space.s2 }}
					ListHeaderComponent={<View style={{ gap: space.s3, paddingBottom: space.s4 }}>{content}</View>}
					ListEmptyComponent={
						!query.isPending && !query.isError ? (
							<EmptyState
								variant="card"
								icon="briefcase"
								title={
									!applications.length
										? t`Track your first job`
										: filtersActive
											? t`No matching applications`
											: t`All your applications are closed`
								}
								message={
									applications.length
										? filtersActive
											? t`Try different words or clear your filters.`
											: t`Show closed applications to see your past job searches.`
										: t`Paste a job link. We'll save the posting so Check, the assistant and your letter can use it.`
								}
								action={{
									label: !applications.length
										? t`Save a job`
										: filtersActive
											? t`Clear filters`
											: t`Show closed applications`,
									onPress: () =>
										applications.length
											? !filtersActive
												? setShowClosed(true)
												: changeFilters(() => {
														clearFilters();
														setTag("");
														setShowClosed(false);
														setFollowUpOnly(false);
													})
											: router.setParams({ create: "1" }),
								}}
							/>
						) : undefined
					}
					renderSectionHeader={({ section }) => (
						<Pressable
							accessibilityRole="button"
							accessibilityLabel={plural(section.total, {
								one: `${getLaneLabel(section.lane)}, # application`,
								other: `${getLaneLabel(section.lane)}, # applications`,
							})}
							accessibilityState={{ expanded: !collapsed.has(section.status) }}
							disabled={busy}
							onPress={() => {
								setSelected(new Set());
								setCollapsed((current) => {
									const next = new Set(current);
									if (next.has(section.status)) next.delete(section.status);
									else next.add(section.status);
									return next;
								});
							}}
							style={{
								minHeight: size.hit,
								flexDirection: "row",
								alignItems: "center",
								gap: space.s2,
								marginTop: space.s4,
							}}
						>
							<View
								style={{
									width: space.s2,
									height: space.s2,
									borderRadius: radius.rLg,
									backgroundColor: section.lane.color,
								}}
							/>
							<Text variant="title" style={{ flex: 1 }}>
								{getLaneLabel(section.lane)}
							</Text>
							<Text color="ink3">{i18n.number(section.total)}</Text>
							<Icon
								name={collapsed.has(section.status) ? "caret-right" : "caret-down"}
								size={size.icon.meta}
								color={colors.ink3}
							/>
						</Pressable>
					)}
					renderItem={({ item, index }) => {
						const next = describeNextStep(
							getNextStep(item, now, lanes.lanes, timeZone, offerHintFor(offerHints, item.id)),
							item,
							i18n.locale,
							timeZone,
						);
						const sentDocuments = [
							item.resumeId ? t`Resume` : null,
							item.coverLetterId ? t`Cover letter` : null,
							item.resumeFileUrl ? t`Resume file` : null,
							item.coverLetterUrl ? t`Cover letter file` : null,
						]
							.filter(Boolean)
							.join(" · ");
						return (
							<Animated.View
								{...listItemMotion(index, firstAppearance, { reduced })}
								style={{
									borderWidth: triageActive && focusedRow?.id === item.id ? 2 : 0,
									borderColor: colors.accent,
									borderBottomWidth: 1,
									borderBottomColor: colors.line,
									flexDirection: "row",
									alignItems: "center",
								}}
							>
								<View style={{ flex: 1 }}>
									<ListRow
										title={item.role}
										subtitle={`${item.company}${item.location ? ` · ${item.location}` : ""}${item.tags.length ? ` · ${item.tags.slice(0, 2).join(", ")}${item.tags.length > 2 ? ` +${item.tags.length - 2}` : ""}` : ""}\n${next.title}${next.sub ? ` · ${next.sub}` : ""}${sentDocuments ? `\n${sentDocuments}` : ""}`}
										selected={selectedIds.includes(item.id)}
										leading={selecting ? (selectedIds.includes(item.id) ? "check-square" : "square") : undefined}
										accessibilityHint={selecting ? t`Toggle selection` : t`Open application`}
										disabled={busy}
										onPress={() => (selecting ? toggle(item.id) : router.push(routes.applicationDetails(item.id)))}
									/>
								</View>
								<IconButton
									icon="dots-three"
									label={t`Actions for ${item.role} at ${item.company}`}
									disabled={busy}
									onPress={() => {
										setSelected(new Set([item.id]));
										setSelecting(true);
									}}
								/>
							</Animated.View>
						);
					}}
				/>
				<Sheet open={filters} onClose={() => setFilters(false)} title={t`Sort and filter`}>
					<View style={{ padding: space.s4, gap: space.s3 }}>
						<SelectSheet
							label={t`Sort by`}
							value={sort}
							options={[
								{ value: "updated", label: t`Updated` },
								{ value: "role", label: t`Role` },
								{ value: "next", label: t`Next step` },
							]}
							onChange={setSort}
						/>
						<SelectSheet
							label={t`Direction`}
							value={direction}
							options={[
								{ value: "asc", label: t`Ascending` },
								{ value: "desc", label: t`Descending` },
							]}
							onChange={setDirection}
						/>
						<SelectSheet
							label={t`Tag`}
							value={tag}
							options={[{ value: "", label: t`All tags` }, ...tags.map((value) => ({ value, label: value }))]}
							onChange={(value) => changeFilters(() => setTag(value))}
						/>
						<Text>{t`Show closed applications`}</Text>
						<Switch
							label={t`Show closed applications`}
							value={showClosed}
							onValueChange={(value) => changeFilters(() => setShowClosed(value))}
						/>
						<Button label={t`Done`} onPress={() => setFilters(false)} />
					</View>
				</Sheet>
				<Sheet
					open={bulk !== null}
					onClose={() => setBulk(null)}
					title={
						bulk === "delete"
							? t`Move to Trash`
							: bulk === "close"
								? t`Close selected applications`
								: bulk === "tag"
									? t`Tag selected applications`
									: t`Move selected applications`
					}
				>
					<View style={{ padding: space.s4, gap: space.s3 }}>
						<Text>
							{plural(selectedIds.length, { one: "# application selected.", other: "# applications selected." })}
						</Text>
						{busy && (
							<Banner tone="info" message={t`Applying changes. Closing this sheet does not cancel the request.`} />
						)}
						{failure && <Banner tone="danger" message={failure} />}
						{bulk === "move" && !laneAvailable && (
							<Banner tone="warn" message={t`This lane is no longer available. Choose another lane.`} />
						)}
						{bulk === "move" && (
							<SelectSheet
								label={t`Move to…`}
								value={moveLaneId || moveLane.id}
								options={lanes.active.map((lane) => ({ value: lane.id, label: getLaneLabel(lane) }))}
								onChange={setMoveLaneId}
								disabled={busy}
							/>
						)}
						{bulk === "tag" && <TextField label={t`Tag`} value={newTag} onChangeText={setNewTag} editable={!busy} />}
						{(bulk === "close" || (bulk === "move" && moveLane.category === "closed" && !moveLane.closedReason)) && (
							<SelectSheet
								label={t`Reason`}
								value={reason}
								options={CLOSED_REASONS.map((value) => ({ value, label: getClosedReasonLabel(value) }))}
								onChange={setReason}
								disabled={busy}
							/>
						)}
						{bulk === "delete" && (
							<Banner tone="warn" message={t`Applications and their timelines can be restored from Trash.`} />
						)}
						<Button
							label={
								bulk === "delete"
									? t`Move to Trash`
									: bulk === "close"
										? t`Close applications`
										: bulk === "tag"
											? t`Add tag`
											: t`Move applications`
							}
							variant={bulk === "delete" ? "danger" : "primary"}
							loading={busy}
							disabled={
								busy ||
								!lanes.ready ||
								(bulk === "move" && !laneAvailable) ||
								!selectedIds.length ||
								selectedIds.length > 200 ||
								(bulk === "tag" && !newTag.trim())
							}
							onPress={() => void applyBulk()}
						/>
						<Button label={t`Cancel`} variant="ghost" disabled={busy} onPress={() => setBulk(null)} />
					</View>
				</Sheet>
			</Screen>
		</ApplicationsViewFrame>
	);
}