Skip to content

Commit 2ee883d

Browse files
ericallamTrigger.dev RepoOps
authored andcommitted
feat(webapp): filter environment variables by environment and confirm before delete
The Environment variables page now filters by environment. It opens on the environment you're in, Preview gets a branch picker, and the search box shows how many keys the current view has. Deleting a variable asks for confirmation first. Mono-RevId: 545a59ff773894979ae36c7ace87c81c1737913f
1 parent 9a88f23 commit 2ee883d

9 files changed

Lines changed: 1161 additions & 72 deletions

File tree

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
area: webapp
3+
type: improvement
4+
---
5+
6+
The Environment variables page now filters by environment, opening on the environment you're in, with a picker for preview branches. Deleting a variable asks for confirmation first.

‎apps/webapp/app/components/primitives/SearchInput.tsx‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { Input } from "~/components/primitives/Input";
55
import { ShortcutKey } from "~/components/primitives/ShortcutKey";
66
import { SimpleTooltip } from "~/components/primitives/Tooltip";
77
import { useSearchParams } from "~/hooks/useSearchParam";
8+
import { type ShortcutDefinition, useShortcutKeys } from "~/hooks/useShortcutKeys";
89
import { cn } from "~/utils/cn";
910

1011
export type SearchInputProps = {
@@ -30,6 +31,8 @@ export type SearchInputProps = {
3031
* mode; `paramName`/`resetParams` are ignored when it's set.
3132
*/
3233
onValueChange?: (value: string) => void;
34+
/** A key that focuses the input. Ignored while a dialog is open. */
35+
shortcut?: ShortcutDefinition;
3336
};
3437

3538
export function SearchInput({
@@ -41,9 +44,23 @@ export function SearchInput({
4144
normalizeForValidation,
4245
value: controlledValue,
4346
onValueChange,
47+
shortcut,
4448
}: SearchInputProps) {
4549
const inputRef = useRef<HTMLInputElement>(null);
4650

51+
useShortcutKeys({
52+
shortcut,
53+
disabled: shortcut === undefined,
54+
action: (event) => {
55+
if (document.querySelector('[role="dialog"], [role="alertdialog"]')) {
56+
return;
57+
}
58+
// Keep the key itself out of the input it focuses.
59+
event.preventDefault();
60+
inputRef.current?.focus();
61+
},
62+
});
63+
4764
const { value, replace, del } = useSearchParams();
4865
const isControlled = onValueChange !== undefined;
4966

@@ -191,6 +208,8 @@ export function SearchInput({
191208
disableHoverableContent
192209
/>
193210
</div>
211+
) : shortcut && !isFocused ? (
212+
<ShortcutKey shortcut={shortcut} variant="small" />
194213
) : undefined
195214
}
196215
/>

‎apps/webapp/app/presenters/v3/EnvironmentVariablesPresenter.server.ts‎

Lines changed: 61 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,10 @@ import type { PrismaClient, PrismaReplicaClient } from "~/db.server";
33
import { $replica, prisma } from "~/db.server";
44
import type { Project } from "~/models/project.server";
55
import type { User } from "~/models/user.server";
6+
import {
7+
selectEnvironmentVariablesFilter,
8+
type EnvironmentVariablesFilter,
9+
} from "~/v3/environmentVariables/environmentFilter";
610
import { EnvironmentVariablesRepository } from "~/v3/environmentVariables/environmentVariablesRepository.server";
711
import type { EnvironmentVariableUpdater } from "~/v3/environmentVariables/repository";
812
import type { SyncEnvVarsMapping, EnvSlug } from "~/v3/vercel/vercelProjectIntegrationSchema";
@@ -30,12 +34,21 @@ export class EnvironmentVariablesPresenter {
3034
page = 1,
3135
pageSize = DEFAULT_ENV_VARS_PAGE_SIZE,
3236
search,
37+
environmentFilter,
38+
branches,
39+
currentEnvironmentSlug,
3340
}: {
3441
userId: User["id"];
3542
projectId: Project["id"];
3643
page?: number;
3744
pageSize?: number;
3845
search?: string;
46+
/** The requested filter. Without one, the current environment's type is used. */
47+
environmentFilter?: EnvironmentVariablesFilter;
48+
/** Preview branch names, or `ALL_BRANCHES`. Only used by the Preview filter. */
49+
branches?: string[];
50+
/** The environment the page is opened in. Without one, every environment is listed. */
51+
currentEnvironmentSlug?: string;
3952
}) {
4053
const project = await this.#replicaClient.project.findFirst({
4154
select: {
@@ -65,9 +78,31 @@ export class EnvironmentVariablesPresenter {
6578
{ skipProjectAccessCheck: true }
6679
);
6780

68-
// Only load values for the environments we display. Projects can accumulate
69-
// values in archived branch environments, which would otherwise all be loaded here.
70-
const environmentIds = sortedEnvironments.map((env) => env.id);
81+
// Narrow to the filtered environments before counting and paging, so the totals and the
82+
// pages follow the filter. Archived branch environments are never in this list, so the
83+
// values projects accumulate in them are never loaded.
84+
const currentEnvironment = currentEnvironmentSlug
85+
? sortedEnvironments.find((env) => env.slug === currentEnvironmentSlug)
86+
: undefined;
87+
// An archived branch isn't in the list, but its URL still opens the page: default to its type.
88+
const missingCurrentEnvironment =
89+
currentEnvironmentSlug && !currentEnvironment
90+
? await this.#replicaClient.runtimeEnvironment.findFirst({
91+
select: { type: true },
92+
where: { projectId: project.id, slug: currentEnvironmentSlug },
93+
})
94+
: null;
95+
const { filter, environmentIds, branchEnvironmentIds } = selectEnvironmentVariablesFilter({
96+
environments: sortedEnvironments,
97+
requested: environmentFilter,
98+
requestedBranches: branches,
99+
currentEnvironmentId: currentEnvironment?.id,
100+
currentEnvironmentType: missingCurrentEnvironment?.type,
101+
});
102+
const filteredEnvironmentIds = new Set(environmentIds);
103+
const listedEnvironments = sortedEnvironments.filter((env) =>
104+
filteredEnvironmentIds.has(env.id)
105+
);
71106

72107
const variableWhere: Prisma.EnvironmentVariableWhereInput = {
73108
projectId: project.id,
@@ -78,6 +113,21 @@ export class EnvironmentVariablesPresenter {
78113
const totalCount = await this.#replicaClient.environmentVariable.count({
79114
where: variableWhere,
80115
});
116+
// A project with no variables in any listed environment gets the first-run empty state
117+
// whatever the filter is. Only an unsearched view with nothing in it has to look further.
118+
const projectHasNoVariables =
119+
totalCount === 0 &&
120+
!search &&
121+
(filter === "all" ||
122+
(await this.#replicaClient.environmentVariable.findFirst({
123+
select: { id: true },
124+
where: {
125+
projectId: project.id,
126+
values: {
127+
some: { environmentId: { in: boundedIn(sortedEnvironments.map((env) => env.id)) } },
128+
},
129+
},
130+
})) === null);
81131
const totalPages = Math.max(1, Math.ceil(totalCount / pageSize));
82132
const currentPage = Math.min(Math.max(1, page), totalPages);
83133

@@ -151,7 +201,7 @@ export class EnvironmentVariablesPresenter {
151201

152202
const nonSecretItems: Array<{ environmentId: string; key: string }> = [];
153203
for (const environmentVariable of environmentVariables) {
154-
for (const env of sortedEnvironments) {
204+
for (const env of listedEnvironments) {
155205
const valueRecord = environmentVariable.values.find((v) => v.environmentId === env.id);
156206
if (valueRecord && !valueRecord.isSecret) {
157207
nonSecretItems.push({ environmentId: env.id, key: environmentVariable.key });
@@ -183,7 +233,7 @@ export class EnvironmentVariablesPresenter {
183233
this.#prismaClient
184234
),
185235
environmentVariables: environmentVariables.flatMap((environmentVariable) => {
186-
return sortedEnvironments.flatMap((env) => {
236+
return listedEnvironments.flatMap((env) => {
187237
const valueRecord = environmentVariable.values.find((v) => v.environmentId === env.id);
188238
const isSecret = valueRecord?.isSecret ?? false;
189239

@@ -230,7 +280,13 @@ export class EnvironmentVariablesPresenter {
230280
];
231281
});
232282
}),
283+
// Every environment, not only the listed ones: the page needs them all for its filter
284+
// options, its permission lists and the create dialog.
233285
environments: sortedEnvironments,
286+
filter,
287+
filterEnvironmentIds: environmentIds,
288+
filterBranchEnvironmentIds: branchEnvironmentIds ?? [],
289+
projectHasNoVariables,
234290
hasStaging,
235291
pagination: {
236292
currentPage,

‎apps/webapp/app/presenters/v3/environmentVariablesEnvironments.server.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { filterOrphanedEnvironments, sortEnvironments } from "~/utils/environmen
44

55
export type EnvironmentVariablesEnvironment = {
66
id: string;
7+
slug: string;
78
type: RuntimeEnvironmentType;
89
isBranchableEnvironment: boolean;
910
branchName: string | null;
@@ -45,6 +46,7 @@ export async function loadEnvironmentVariablesEnvironments(
4546
const environments = await prismaClient.runtimeEnvironment.findMany({
4647
select: {
4748
id: true,
49+
slug: true,
4850
type: true,
4951
isBranchableEnvironment: true,
5052
branchName: true,
@@ -68,6 +70,7 @@ export async function loadEnvironmentVariablesEnvironments(
6870
return {
6971
environments: sortedEnvironments.map((environment) => ({
7072
id: environment.id,
73+
slug: environment.slug,
7174
type: environment.type,
7275
isBranchableEnvironment: environment.isBranchableEnvironment,
7376
branchName: environment.branchName,

‎apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.environment-variables.new/route.tsx‎

Lines changed: 47 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import {
33
emptyEnvironmentVariableValuesEnabled,
44
EMPTY_ENV_VALUES_DISABLED,
55
} from "~/v3/environmentVariables/emptyValuesFlag.server";
6+
import { listViewSearch } from "~/v3/environmentVariables/environmentFilter";
67
import { parseEnvironmentVariableForm } from "~/v3/environmentVariables/forms";
78
import {
89
LockClosedIcon,
@@ -11,7 +12,7 @@ import {
1112
PlusIcon,
1213
XMarkIcon,
1314
} from "@heroicons/react/20/solid";
14-
import { Form, useActionData, useNavigate, useNavigation } from "@remix-run/react";
15+
import { Form, useActionData, useLocation, useNavigate, useNavigation } from "@remix-run/react";
1516
import { json } from "@remix-run/server-runtime";
1617
import dotenv from "dotenv";
1718
import { useState } from "react";
@@ -227,12 +228,13 @@ export const action = dashboardAction(
227228
return json(submission.reply({ fieldErrors }));
228229
}
229230

231+
// Back to the list view the dialog was opened from.
230232
return redirect(
231-
v3EnvironmentVariablesPath(
233+
`${v3EnvironmentVariablesPath(
232234
{ slug: organizationSlug },
233235
{ slug: projectParam },
234236
{ slug: envParam }
235-
)
237+
)}${listViewSearch(request.url)}`
236238
);
237239
}
238240
);
@@ -246,8 +248,15 @@ export default function Page() {
246248
parentData,
247249
"Environment variables page loader data must be defined when rendering the create dialog"
248250
);
249-
const { environments, hasStaging, writableEnvironmentIds, allowEmptyEnvironmentVariableValues } =
250-
parentData;
251+
const {
252+
environments,
253+
filter,
254+
filterEnvironmentIds,
255+
filterBranchEnvironmentIds,
256+
hasStaging,
257+
writableEnvironmentIds,
258+
allowEmptyEnvironmentVariableValues,
259+
} = parentData;
251260
// Creating a variable is a write, so gate the targets on write access.
252261
const writableEnvironmentIdSet = new Set(writableEnvironmentIds);
253262
const lastSubmission = useActionData();
@@ -256,8 +265,32 @@ export default function Page() {
256265
const organization = useOrganization();
257266
const project = useProject();
258267
const environment = useEnvironment();
259-
const [selectedEnvironmentIds, setSelectedEnvironmentIds] = useState<Set<string>>(new Set());
260-
const [selectedBranchId, setSelectedBranchId] = useState<string | undefined>(undefined);
268+
const location = useLocation();
269+
// The list this dialog sits on, with its filter, search and page.
270+
const listPath = `${v3EnvironmentVariablesPath(organization, project, environment)}${location.search}`;
271+
// Start with the environment the list is filtered to (never a branch).
272+
const [selectedEnvironmentIds, setSelectedEnvironmentIds] = useState<Set<string>>(
273+
() =>
274+
new Set(
275+
filter === "all"
276+
? []
277+
: environments
278+
.filter(
279+
(env) =>
280+
env.parentEnvironmentId === null &&
281+
filterEnvironmentIds.includes(env.id) &&
282+
writableEnvironmentIdSet.has(env.id)
283+
)
284+
.map((env) => env.id)
285+
)
286+
);
287+
// And with the preview branch it is narrowed to, when it is narrowed to exactly one.
288+
const [selectedBranchId, setSelectedBranchId] = useState<string | undefined>(() => {
289+
const [onlyBranchId, ...others] = filterBranchEnvironmentIds;
290+
return onlyBranchId && others.length === 0 && writableEnvironmentIdSet.has(onlyBranchId)
291+
? onlyBranchId
292+
: undefined;
293+
});
261294

262295
// TODO: we only support branch-specific env vars for Preview environments.
263296
// This keeps setting consistent env vars across Dev/Staging/Prod easier.
@@ -289,6 +322,10 @@ export default function Page() {
289322
isChecked: boolean,
290323
environmentType?: string
291324
) => {
325+
// A branch only applies while Preview is ticked.
326+
if (!isChecked && environmentType === "PREVIEW") {
327+
setSelectedBranchId(undefined);
328+
}
292329
setSelectedEnvironmentIds((prev) => {
293330
const newSet = new Set(prev);
294331

@@ -330,7 +367,7 @@ export default function Page() {
330367
open={isOpen}
331368
onOpenChange={(o) => {
332369
if (!o) {
333-
navigate(v3EnvironmentVariablesPath(organization, project, environment));
370+
navigate(listPath);
334371
}
335372
}}
336373
>
@@ -340,7 +377,7 @@ export default function Page() {
340377
<Fieldset className="max-h-[70vh] overflow-y-auto p-4 scrollbar-thin scrollbar-track-transparent scrollbar-thumb-surface-control">
341378
<InputGroup fullWidth>
342379
<Label>Environments</Label>
343-
{selectedBranchId ? (
380+
{previewIsSelected && selectedBranchId ? (
344381
<input type="hidden" name="environmentIds" value={selectedBranchId} />
345382
) : (
346383
Array.from(selectedEnvironmentIds).map((id) => (
@@ -542,10 +579,7 @@ export default function Page() {
542579
</div>
543580
}
544581
cancelButton={
545-
<LinkButton
546-
to={v3EnvironmentVariablesPath(organization, project, environment)}
547-
variant="tertiary/medium"
548-
>
582+
<LinkButton to={listPath} variant="tertiary/medium">
549583
Cancel
550584
</LinkButton>
551585
}

0 commit comments

Comments
 (0)