Skip to content

feat: implement multi-org template gallery #13784

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 25 commits into from
Jul 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
0a5c431
feat: initial changes for multi-org templates page
jaaydenh Jul 1, 2024
6f96fee
feat: add TemplateCard component
jaaydenh Jul 2, 2024
51ebb67
feat: add component stories
jaaydenh Jul 3, 2024
a0effc6
chore: update template query naming
jaaydenh Jul 3, 2024
be37085
fix: fix formatting
jaaydenh Jul 3, 2024
5649166
feat: template card interaction and navigation
jaaydenh Jul 8, 2024
3ea3aa2
fix: copy updates
jaaydenh Jul 8, 2024
f17a0c3
chore: update TemplateFilter type to include FilterQuery
jaaydenh Jul 9, 2024
0077db0
chore: update typesGenerated.ts
jaaydenh Jul 9, 2024
461202e
feat: update template filter api logic
jaaydenh Jul 9, 2024
66e02fb
fix: fix format
jaaydenh Jul 11, 2024
369c59f
fix: get activeOrg
jaaydenh Jul 11, 2024
c41cdc4
fix: add format annotation
jaaydenh Jul 11, 2024
7f5d35e
chore: use organization display name
jaaydenh Jul 11, 2024
6e2a6d8
feat: client side org filtering
jaaydenh Jul 15, 2024
978c047
fix: use org display name
jaaydenh Jul 15, 2024
aaed038
fix: add ExactName
jaaydenh Jul 15, 2024
8d84ad9
feat: show orgs filter only if more than 1 org
jaaydenh Jul 15, 2024
a1c6169
chore: updates for PR review
jaaydenh Jul 16, 2024
15542c0
fix: fix format
jaaydenh Jul 16, 2024
8f4c56f
chore: add story for multi org
jaaydenh Jul 16, 2024
a282bac
fix: aggregate templates by organization id
jaaydenh Jul 17, 2024
b092644
fix: fix format
jaaydenh Jul 17, 2024
32376e6
fix: check org count
jaaydenh Jul 17, 2024
801138a
fix: update ExactName type
jaaydenh Jul 17, 2024
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
10 changes: 8 additions & 2 deletions codersdk/organizations.go
Original file line number Diff line number Diff line change
Expand Up @@ -367,8 +367,9 @@ func (c *Client) TemplatesByOrganization(ctx context.Context, organizationID uui
}

type TemplateFilter struct {
OrganizationID uuid.UUID
ExactName string
OrganizationID uuid.UUID `json:"organization_id,omitempty" format:"uuid" typescript:"-"`
FilterQuery string `json:"q,omitempty"`
ExactName string `json:"exact_name,omitempty" typescript:"-"`
}

// asRequestOption returns a function that can be used in (*Client).Request.
Expand All @@ -386,6 +387,11 @@ func (f TemplateFilter) asRequestOption() RequestOption {
params = append(params, fmt.Sprintf("exact_name:%q", f.ExactName))
}

if f.FilterQuery != "" {
// If custom stuff is added, just add it on here.
params = append(params, f.FilterQuery)
}

q := r.URL.Query()
q.Set("q", strings.Join(params, " "))
r.URL.RawQuery = q.Encode()
Expand Down
10 changes: 9 additions & 1 deletion site/src/api/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -578,7 +578,7 @@ class ApiMethods {
return response.data;
};

getTemplates = async (
getTemplatesByOrganizationId = async (
organizationId: string,
options?: TemplateOptions,
): Promise<TypesGen.Template[]> => {
Expand All @@ -598,6 +598,14 @@ class ApiMethods {
return response.data;
};

getTemplates = async (
options?: TypesGen.TemplateFilter,
): Promise<TypesGen.Template[]> => {
const url = getURLWithSearchParams("/api/v2/templates", options);
const response = await this.axios.get<TypesGen.Template[]>(url);
return response.data;
};

getTemplateByName = async (
organizationId: string,
name: string,
Expand Down
4 changes: 2 additions & 2 deletions site/src/api/queries/audits.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { API } from "api/api";
import type { AuditLogResponse } from "api/typesGenerated";
import { useFilterParamsKey } from "components/Filter/filter";
import type { UsePaginatedQueryOptions } from "hooks/usePaginatedQuery";
import { filterParamsKey } from "utils/filters";

export function paginatedAudits(
searchParams: URLSearchParams,
): UsePaginatedQueryOptions<AuditLogResponse, string> {
return {
searchParams,
queryPayload: () => searchParams.get(useFilterParamsKey) ?? "",
queryPayload: () => searchParams.get(filterParamsKey) ?? "",
queryKey: ({ payload, pageNumber }) => {
return ["auditLogs", payload, pageNumber] as const;
},
Expand Down
32 changes: 23 additions & 9 deletions site/src/api/queries/templates.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { MutationOptions, QueryClient, QueryOptions } from "react-query";
import { API } from "api/api";
import type {
TemplateFilter,
CreateTemplateRequest,
CreateTemplateVersionRequest,
ProvisionerJob,
Expand Down Expand Up @@ -30,16 +31,26 @@ export const templateByName = (
};
};

const getTemplatesQueryKey = (organizationId: string, deprecated?: boolean) => [
organizationId,
"templates",
deprecated,
];
const getTemplatesByOrganizationIdQueryKey = (
organizationId: string,
deprecated?: boolean,
) => [organizationId, "templates", deprecated];

export const templatesByOrganizationId = (
organizationId: string,
deprecated?: boolean,
) => {
return {
queryKey: getTemplatesByOrganizationIdQueryKey(organizationId, deprecated),
queryFn: () =>
API.getTemplatesByOrganizationId(organizationId, { deprecated }),
};
};

export const templates = (organizationId: string, deprecated?: boolean) => {
export const templates = (filter?: TemplateFilter) => {
return {
queryKey: getTemplatesQueryKey(organizationId, deprecated),
queryFn: () => API.getTemplates(organizationId, { deprecated }),
queryKey: ["templates", filter],
queryFn: () => API.getTemplates(filter),
};
};

Expand Down Expand Up @@ -92,7 +103,10 @@ export const setGroupRole = (

export const templateExamples = (organizationId: string) => {
return {
queryKey: [...getTemplatesQueryKey(organizationId), "examples"],
queryKey: [
...getTemplatesByOrganizationIdQueryKey(organizationId),
"examples",
],
queryFn: () => API.getTemplateExamples(organizationId),
};
};
Expand Down
3 changes: 1 addition & 2 deletions site/src/api/typesGenerated.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 3 additions & 4 deletions site/src/components/Filter/filter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
import { InputGroup } from "components/InputGroup/InputGroup";
import { SearchField } from "components/SearchField/SearchField";
import { useDebouncedFunction } from "hooks/debounce";
import { filterParamsKey } from "utils/filters";

export type PresetFilter = {
name: string;
Expand All @@ -35,21 +36,19 @@ type UseFilterConfig = {
onUpdate?: (newValue: string) => void;
};

export const useFilterParamsKey = "filter";

export const useFilter = ({
fallbackFilter = "",
searchParamsResult,
onUpdate,
}: UseFilterConfig) => {
const [searchParams, setSearchParams] = searchParamsResult;
const query = searchParams.get(useFilterParamsKey) ?? fallbackFilter;
const query = searchParams.get(filterParamsKey) ?? fallbackFilter;

const update = (newValues: string | FilterValues) => {
const serialized =
typeof newValues === "string" ? newValues : stringifyFilter(newValues);

searchParams.set(useFilterParamsKey, serialized);
searchParams.set(filterParamsKey, serialized);
setSearchParams(searchParams);

if (onUpdate !== undefined) {
Expand Down
40 changes: 40 additions & 0 deletions site/src/modules/templates/TemplateCard/TemplateCard.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import type { Meta, StoryObj } from "@storybook/react";
import { chromatic } from "testHelpers/chromatic";
import { MockTemplate } from "testHelpers/entities";
import { TemplateCard } from "./TemplateCard";

const meta: Meta<typeof TemplateCard> = {
title: "modules/templates/TemplateCard",
parameters: { chromatic },
component: TemplateCard,
args: {
template: MockTemplate,
},
};

export default meta;
type Story = StoryObj<typeof TemplateCard>;

export const Template: Story = {};

export const DeprecatedTemplate: Story = {
args: {
template: {
...MockTemplate,
deprecated: true,
},
},
};

export const LongContentTemplate: Story = {
args: {
template: {
...MockTemplate,
display_name: "Very Long Template Name",
organization_display_name: "Very Long Organization Name",
description:
"This is a very long test description. This is a very long test description. This is a very long test description. This is a very long test description",
active_user_count: 999,
},
},
};
144 changes: 144 additions & 0 deletions site/src/modules/templates/TemplateCard/TemplateCard.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
import type { Interpolation, Theme } from "@emotion/react";
import ArrowForwardOutlined from "@mui/icons-material/ArrowForwardOutlined";
import Button from "@mui/material/Button";
import type { FC, HTMLAttributes } from "react";
import { Link as RouterLink, useNavigate } from "react-router-dom";
import type { Template } from "api/typesGenerated";
import { ExternalAvatar } from "components/Avatar/Avatar";
import { AvatarData } from "components/AvatarData/AvatarData";
import { DeprecatedBadge } from "components/Badges/Badges";

type TemplateCardProps = HTMLAttributes<HTMLDivElement> & {
template: Template;
};

export const TemplateCard: FC<TemplateCardProps> = ({
template,
...divProps
Copy link
Member

Choose a reason for hiding this comment

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

super minor nit, I tend to call these sorts of captures attrs, but there's definitely precedent for calling it whateverProps too. maybe this is something we should consolidate on...

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I was following the pattern in the files I was working on. In other code bases/the React docs, this is often called ...props as well. I think it depends if we want to call them based on what they are, "props" or how they are used, props on divs "divProps" or attributes on divs "attrs"

}) => {
const navigate = useNavigate();
const templatePageLink = `/templates/${template.name}`;
const hasIcon = template.icon && template.icon !== "";

const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === "Enter" && e.currentTarget === e.target) {
navigate(templatePageLink);
}
};

return (
<div
css={styles.card}
{...divProps}
role="button"
tabIndex={0}
onClick={() => navigate(templatePageLink)}
onKeyDown={handleKeyDown}
>
<div css={styles.header}>
<div>
<AvatarData
title={
template.display_name.length > 0
? template.display_name
: template.name
}
subtitle={template.organization_display_name}
avatar={
hasIcon && (
<ExternalAvatar variant="square" fitImage src={template.icon} />
)
}
/>
</div>
<div>
{template.active_user_count}{" "}
{template.active_user_count === 1 ? "user" : "users"}
</div>
</div>

<div>
<span css={styles.description}>
<p>{template.description}</p>
</span>
</div>

<div css={styles.useButtonContainer}>
{template.deprecated ? (
<DeprecatedBadge />
) : (
<Button
component={RouterLink}
css={styles.actionButton}
className="actionButton"
fullWidth
startIcon={<ArrowForwardOutlined />}
title={`Create a workspace using the ${template.display_name} template`}
to={`/templates/${template.name}/workspace`}
onClick={(e) => {
e.stopPropagation();
}}
>
Create Workspace
</Button>
)}
</div>
</div>
);
};

const styles = {
card: (theme) => ({
width: "320px",
padding: 24,
borderRadius: 6,
border: `1px solid ${theme.palette.divider}`,
textAlign: "left",
color: "inherit",
display: "flex",
flexDirection: "column",
cursor: "pointer",
"&:hover": {
color: theme.experimental.l2.hover.text,
borderColor: theme.experimental.l2.hover.text,
},
}),

header: {
display: "flex",
alignItems: "center",
justifyContent: "space-between",
marginBottom: 24,
},

icon: {
flexShrink: 0,
paddingTop: 4,
width: 32,
height: 32,
},

description: (theme) => ({
fontSize: 13,
color: theme.palette.text.secondary,
lineHeight: "1.6",
display: "block",
}),

useButtonContainer: {
display: "flex",
gap: 12,
flexDirection: "column",
paddingTop: 24,
marginTop: "auto",
alignItems: "center",
},

actionButton: (theme) => ({
transition: "none",
color: theme.palette.text.secondary,
"&:hover": {
borderColor: theme.palette.text.primary,
},
}),
} satisfies Record<string, Interpolation<Theme>>;
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { templateExamples } from "api/queries/templates";
import type { TemplateExample } from "api/typesGenerated";
import { useDashboard } from "modules/dashboard/useDashboard";
import { pageTitle } from "utils/page";
import { getTemplatesByTag } from "utils/starterTemplates";
import { getTemplatesByTag } from "utils/templateAggregators";
import { StarterTemplatesPageView } from "./StarterTemplatesPageView";

const StarterTemplatesPage: FC = () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
MockTemplateExample,
MockTemplateExample2,
} from "testHelpers/entities";
import { getTemplatesByTag } from "utils/starterTemplates";
import { getTemplatesByTag } from "utils/templateAggregators";
import { StarterTemplatesPageView } from "./StarterTemplatesPageView";

const meta: Meta<typeof StarterTemplatesPageView> = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
} from "components/PageHeader/PageHeader";
import { Stack } from "components/Stack/Stack";
import { TemplateExampleCard } from "modules/templates/TemplateExampleCard/TemplateExampleCard";
import type { StarterTemplatesByTag } from "utils/starterTemplates";
import type { StarterTemplatesByTag } from "utils/templateAggregators";

const getTagLabel = (tag: string) => {
const labelByTag: Record<string, string> = {
Expand Down
Loading
Loading