Skip to content

feat(site): add support for presets to the create workspace page #16567

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Feb 18, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions site/src/api/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1145,6 +1145,15 @@ class ApiMethods {
return response.data;
};

getTemplateVersionPresets = async (
templateVersionId: string,
): Promise<TypesGen.Preset[]> => {
const response = await this.axios.get<TypesGen.Preset[]>(
`/api/v2/templateversions/${templateVersionId}/presets`,
);
return response.data;
};

startWorkspace = (
workspaceId: string,
templateVersionId: string,
Expand Down
8 changes: 8 additions & 0 deletions site/src/api/queries/templates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { API, type GetTemplatesOptions, type GetTemplatesQuery } from "api/api";
import type {
CreateTemplateRequest,
CreateTemplateVersionRequest,
Preset,
ProvisionerJob,
ProvisionerJobStatus,
Template,
Expand Down Expand Up @@ -305,6 +306,13 @@ export const previousTemplateVersion = (
};
};

export const templateVersionPresets = (versionId: string) => {
return {
queryKey: ["templateVersion", versionId, "presets"],
queryFn: () => API.getTemplateVersionPresets(versionId),
};
};

const waitBuildToBeFinished = async (
version: TemplateVersion,
onRequest?: (data: TemplateVersion) => void,
Expand Down
6 changes: 6 additions & 0 deletions site/src/pages/CreateWorkspacePage/CreateWorkspacePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
richParameters,
templateByName,
templateVersionExternalAuth,
templateVersionPresets,
} from "api/queries/templates";
import { autoCreateWorkspace, createWorkspace } from "api/queries/workspaces";
import type {
Expand Down Expand Up @@ -56,6 +57,10 @@ const CreateWorkspacePage: FC = () => {
const templateQuery = useQuery(
templateByName(organizationName, templateName),
);
const templateVersionPresetsQuery = useQuery({
...templateVersionPresets(templateQuery.data?.active_version_id ?? ""),
enabled: templateQuery.data !== undefined,
});
const permissionsQuery = useQuery(
templateQuery.data
? checkAuthorization({
Expand Down Expand Up @@ -203,6 +208,7 @@ const CreateWorkspacePage: FC = () => {
hasAllRequiredExternalAuth={hasAllRequiredExternalAuth}
permissions={permissionsQuery.data as CreateWSPermissions}
parameters={realizedParameters as TemplateVersionParameter[]}
presets={templateVersionPresetsQuery.data ?? []}
creatingWorkspace={createWorkspaceMutation.isLoading}
onCancel={() => {
navigate(-1);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { action } from "@storybook/addon-actions";
import type { Meta, StoryObj } from "@storybook/react";
import { within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { chromatic } from "testHelpers/chromatic";
import {
MockTemplate,
Expand Down Expand Up @@ -116,6 +118,47 @@ export const Parameters: Story = {
},
};

export const PresetsButNoneSelected: Story = {
args: {
presets: [
{
ID: "preset-1",
Name: "Preset 1",
Parameters: [
{
Name: MockTemplateVersionParameter1.name,
Value: "preset 1 override",
},
],
},
{
ID: "preset-2",
Name: "Preset 2",
Parameters: [
{
Name: MockTemplateVersionParameter2.name,
Value: "42",
},
],
},
],
parameters: [
MockTemplateVersionParameter1,
MockTemplateVersionParameter2,
MockTemplateVersionParameter3,
],
},
};

export const PresetSelected: Story = {
args: PresetsButNoneSelected.args,
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await userEvent.click(canvas.getByLabelText("Preset"));
await userEvent.click(canvas.getByText("Preset 1"));
},
};

export const ExternalAuth: Story = {
args: {
externalAuth: [
Expand Down
85 changes: 84 additions & 1 deletion site/src/pages/CreateWorkspacePage/CreateWorkspacePageView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { Alert } from "components/Alert/Alert";
import { ErrorAlert } from "components/Alert/ErrorAlert";
import { Avatar } from "components/Avatar/Avatar";
import { Button } from "components/Button/Button";
import { SelectFilter } from "components/Filter/SelectFilter";
import {
FormFields,
FormFooter,
Expand Down Expand Up @@ -64,6 +65,7 @@ export interface CreateWorkspacePageViewProps {
hasAllRequiredExternalAuth: boolean;
parameters: TypesGen.TemplateVersionParameter[];
autofillParameters: AutofillBuildParameter[];
presets: TypesGen.Preset[];
permissions: CreateWSPermissions;
creatingWorkspace: boolean;
onCancel: () => void;
Expand All @@ -88,6 +90,7 @@ export const CreateWorkspacePageView: FC<CreateWorkspacePageViewProps> = ({
hasAllRequiredExternalAuth,
parameters,
autofillParameters,
presets = [],
permissions,
creatingWorkspace,
onSubmit,
Expand Down Expand Up @@ -145,6 +148,62 @@ export const CreateWorkspacePageView: FC<CreateWorkspacePageViewProps> = ({
[autofillParameters],
);

const [presetOptions, setPresetOptions] = useState([
{ label: "None", value: "" },
]);
useEffect(() => {
setPresetOptions([
{ label: "None", value: "" },
...presets.map((preset) => ({
label: preset.Name,
value: preset.ID,
})),
]);
}, [presets]);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We only use useMemo when really necessary. In this case, it would be ok to compute this on every render.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cool. I will remove the useMemo. For my own learning: Can you help me understand why not to use useMemo in this case?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It’s just a matter of adding complexity—caching—in a place where it’s not really needed.


const [selectedPresetIndex, setSelectedPresetIndex] = useState(0);
const [presetParameterNames, setPresetParameterNames] = useState<string[]>(
[],
);

useEffect(() => {
const selectedPresetOption = presetOptions[selectedPresetIndex];
let selectedPreset: TypesGen.Preset | undefined;
for (const preset of presets) {
if (preset.ID === selectedPresetOption.value) {
selectedPreset = preset;
break;
}
}

if (!selectedPreset || !selectedPreset.Parameters) {
setPresetParameterNames([]);
return;
}

setPresetParameterNames(selectedPreset.Parameters.map((p) => p.Name));

for (const presetParameter of selectedPreset.Parameters) {
const parameterIndex = parameters.findIndex(
(p) => p.name === presetParameter.Name,
);
if (parameterIndex === -1) continue;

const parameterField = `rich_parameter_values.${parameterIndex}`;

form.setFieldValue(parameterField, {
name: presetParameter.Name,
value: presetParameter.Value,
});
}
}, [
presetOptions,
selectedPresetIndex,
presets,
parameters,
form.setFieldValue,
]);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm assuming this effect is to set in the form the default values right? If yes, I think the best place to set them is in the form initialValues prop here

.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This effect is not only for default values, but also for if the user chooses a new preset. If they choose a new preset then this effect will autofill the form for them using the new preset values.


return (
<Margins size="medium">
<PageHeader
Expand Down Expand Up @@ -213,6 +272,28 @@ export const CreateWorkspacePageView: FC<CreateWorkspacePageViewProps> = ({
</Stack>
)}

{presets.length > 0 && (
<Stack direction="column" spacing={2}>
<span css={styles.description}>
Select a preset to get started
</span>
<Stack direction="row" spacing={2}>
<SelectFilter
label="Preset"
options={presetOptions}
onSelect={(option) => {
setSelectedPresetIndex(
presetOptions.findIndex(
(preset) => preset.value === option?.value,
),
);
}}
placeholder="Select a preset"
selectedOption={presetOptions[selectedPresetIndex]}
/>
</Stack>
</Stack>
)}
<div>
<TextField
{...getFieldHelpers("name")}
Expand Down Expand Up @@ -292,7 +373,9 @@ export const CreateWorkspacePageView: FC<CreateWorkspacePageViewProps> = ({
const isDisabled =
disabledParams?.includes(
parameter.name.toLowerCase().replace(/ /g, "_"),
) || creatingWorkspace;
) ||
creatingWorkspace ||
presetParameterNames.includes(parameter.name);

return (
<RichParameterInput
Expand Down
Loading