Skip to content

chore(site): migrate a few services to react-query used in the DashboardProvider #9667

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 21 commits into from
Sep 14, 2023
Merged
Show file tree
Hide file tree
Changes from 14 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
33 changes: 33 additions & 0 deletions site/src/api/queries/appearance.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { QueryClient } from "@tanstack/react-query";
import * as API from "api/api";
import { AppearanceConfig } from "api/typesGenerated";

export const appearance = () => {
return {
queryKey: ["appearance"],
queryFn: fetchAppearance,
};
};

export const updateAppearance = (queryClient: QueryClient) => {
return {
mutationFn: API.updateAppearance,
onSuccess: (newConfig: AppearanceConfig) => {
queryClient.setQueryData(["appearance"], newConfig);
},
};
};

const fetchAppearance = () => {
const appearance = document.querySelector("meta[property=appearance]");
if (appearance) {
const rawContent = appearance.getAttribute("content");
try {
return JSON.parse(rawContent as string);
} catch (ex) {
// Ignore this and fetch as normal!
}
}

return API.getAppearance();
};
23 changes: 23 additions & 0 deletions site/src/api/queries/buildInfo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import * as API from "api/api";

export const buildInfo = () => {
return {
queryKey: ["buildInfo"],
queryFn: fetchBuildInfo,
};
};

const fetchBuildInfo = async () => {
// Build info is injected by the Coder server into the HTML document.
const buildInfo = document.querySelector("meta[property=build-info]");
if (buildInfo) {
const rawContent = buildInfo.getAttribute("content");
try {
return JSON.parse(rawContent as string);
} catch (e) {
console.warn("Failed to parse build info from document", e);
}
}

return API.getBuildInfo();
};
37 changes: 37 additions & 0 deletions site/src/api/queries/entitlements.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { QueryClient } from "@tanstack/react-query";
import * as API from "api/api";

const ENTITLEMENTS_QUERY_KEY = ["entitlements"];

export const entitlements = () => {
return {
queryKey: ENTITLEMENTS_QUERY_KEY,
queryFn: fetchEntitlements,
};
};

export const refreshEntitlements = (queryClient: QueryClient) => {
return {
mutationFn: API.refreshEntitlements,
onSuccess: async () => {
await queryClient.invalidateQueries({
queryKey: ENTITLEMENTS_QUERY_KEY,
});
},
};
};

const fetchEntitlements = () => {
// Entitlements is injected by the Coder server into the HTML document.
const entitlements = document.querySelector("meta[property=entitlements]");
if (entitlements) {
const rawContent = entitlements.getAttribute("content");
try {
return JSON.parse(rawContent as string);
} catch (e) {
console.warn("Failed to parse entitlements from document", e);
}
}

return API.getEntitlements();
};
23 changes: 23 additions & 0 deletions site/src/api/queries/experiments.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import * as API from "api/api";

export const experiments = () => {
return {
queryKey: ["experiments"],
queryFn: fetchExperiments,
};
};

const fetchExperiments = async () => {
// Experiments is injected by the Coder server into the HTML document.
const experiments = document.querySelector("meta[property=experiments]");
if (experiments) {
const rawContent = experiments.getAttribute("content");
try {
return JSON.parse(rawContent as string);
} catch (e) {
console.warn("Failed to parse experiments from document", e);
}
}

return API.getExperiments();
};
67 changes: 29 additions & 38 deletions site/src/components/Dashboard/DashboardProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,27 @@
import { useMachine } from "@xstate/react";
import { useQuery } from "@tanstack/react-query";
import { buildInfo } from "api/queries/buildInfo";
import { experiments } from "api/queries/experiments";
import { entitlements } from "api/queries/entitlements";
import {
AppearanceConfig,
BuildInfoResponse,
Entitlements,
Experiments,
} from "api/typesGenerated";
import { FullScreenLoader } from "components/Loader/FullScreenLoader";
import { createContext, FC, PropsWithChildren, useContext } from "react";
import { appearanceMachine } from "xServices/appearance/appearanceXService";
import { buildInfoMachine } from "xServices/buildInfo/buildInfoXService";
import { entitlementsMachine } from "xServices/entitlements/entitlementsXService";
import { experimentsMachine } from "xServices/experiments/experimentsMachine";
import {
createContext,
FC,
PropsWithChildren,
useContext,
useState,
} from "react";
import { appearance } from "api/queries/appearance";

interface Appearance {
config: AppearanceConfig;
preview: boolean;
isPreview: boolean;
setPreview: (config: AppearanceConfig) => void;
save: (config: AppearanceConfig) => void;
}

interface DashboardProviderValue {
Expand All @@ -31,29 +36,16 @@ export const DashboardProviderContext = createContext<
>(undefined);

export const DashboardProvider: FC<PropsWithChildren> = ({ children }) => {
const [buildInfoState] = useMachine(buildInfoMachine);
const [entitlementsState] = useMachine(entitlementsMachine);
const [appearanceState, appearanceSend] = useMachine(appearanceMachine);
const [experimentsState] = useMachine(experimentsMachine);
const { buildInfo } = buildInfoState.context;
const { entitlements } = entitlementsState.context;
const { appearance, preview } = appearanceState.context;
const { experiments } = experimentsState.context;
const isLoading = !buildInfo || !entitlements || !appearance || !experiments;

const setAppearancePreview = (config: AppearanceConfig) => {
appearanceSend({
type: "SET_PREVIEW_APPEARANCE",
appearance: config,
});
};

const saveAppearance = (config: AppearanceConfig) => {
appearanceSend({
type: "SAVE_APPEARANCE",
appearance: config,
});
};
const buildInfoQuery = useQuery(buildInfo());
const entitlementsQuery = useQuery(entitlements());
const experimentsQuery = useQuery(experiments());
const appearanceQuery = useQuery(appearance());
const isLoading =
!buildInfoQuery.data ||
!entitlementsQuery.data ||
!appearanceQuery.data ||
!experimentsQuery.data;
const [configPreview, setConfigPreview] = useState<AppearanceConfig>();

if (isLoading) {
return <FullScreenLoader />;
Expand All @@ -62,14 +54,13 @@ export const DashboardProvider: FC<PropsWithChildren> = ({ children }) => {
return (
<DashboardProviderContext.Provider
value={{
buildInfo,
entitlements,
experiments,
buildInfo: buildInfoQuery.data,
entitlements: entitlementsQuery.data,
experiments: experimentsQuery.data,
appearance: {
preview,
config: appearance,
setPreview: setAppearancePreview,
save: saveAppearance,
config: configPreview ?? appearanceQuery.data,
setPreview: setConfigPreview,
isPreview: configPreview !== undefined,
},
}}
>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export const ServiceBanner: React.FC = () => {
<ServiceBannerView
message={message}
backgroundColor={background_color}
preview={appearance.preview}
isPreview={appearance.isPreview}
/>
);
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,6 @@ export const Preview: Story = {
args: {
message: "weeeee",
backgroundColor: "#000000",
preview: true,
isPreview: true,
},
};
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@ import { hex } from "color-convert";
export interface ServiceBannerViewProps {
message: string;
backgroundColor: string;
preview: boolean;
isPreview: boolean;
}

export const ServiceBannerView: React.FC<ServiceBannerViewProps> = ({
message,
backgroundColor,
preview,
isPreview,
}) => {
const styles = useStyles();
// We don't want anything funky like an image or a heading in the service
Expand All @@ -34,7 +34,7 @@ export const ServiceBannerView: React.FC<ServiceBannerViewProps> = ({
className={styles.container}
style={{ backgroundColor: backgroundColor }}
>
{preview && <Pill text="Preview" type="info" lightBorder />}
{isPreview && <Pill text="Preview" type="info" lightBorder />}
<div
className={styles.centerContent}
style={{
Expand Down
2 changes: 1 addition & 1 deletion site/src/hooks/useFeatureVisibility.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { FeatureName } from "api/typesGenerated";
import { useDashboard } from "components/Dashboard/DashboardProvider";
import { selectFeatureVisibility } from "xServices/entitlements/entitlementsSelectors";
import { selectFeatureVisibility } from "utils/entitlements";

export const useFeatureVisibility = (): Record<FeatureName, boolean> => {
const { entitlements } = useDashboard();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,23 @@ import { FC } from "react";
import { Helmet } from "react-helmet-async";
import { pageTitle } from "utils/page";
import { AppearanceSettingsPageView } from "./AppearanceSettingsPageView";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { updateAppearance } from "api/queries/appearance";
import { getErrorMessage } from "api/errors";
import { displayError, displaySuccess } from "components/GlobalSnackbar/utils";

// ServiceBanner is unlike the other Deployment Settings pages because it
// implements a form, whereas the others are read-only. We make this
// exception because the Service Banner is visual, and configuring it from
// the command line would be a significantly worse user experience.
const AppearanceSettingsPage: FC = () => {
const { appearance, entitlements } = useDashboard();
const queryClient = useQueryClient();
const updateAppearanceMutation = useMutation(updateAppearance(queryClient));
const isEntitled =
entitlements.features["appearance"].entitlement !== "not_entitled";

const updateAppearance = (
const onSaveAppearance = async (
newConfig: Partial<UpdateAppearanceConfig>,
preview: boolean,
) => {
Expand All @@ -26,7 +32,14 @@ const AppearanceSettingsPage: FC = () => {
appearance.setPreview(newAppearance);
return;
}
appearance.save(newAppearance);
try {
await updateAppearanceMutation.mutateAsync(newAppearance);
displaySuccess("Successfully updated appearance settings!");
} catch (error) {
displayError(
getErrorMessage(error, "Failed to update appearance settings."),
);
}
};

return (
Expand All @@ -38,7 +51,7 @@ const AppearanceSettingsPage: FC = () => {
<AppearanceSettingsPageView
appearance={appearance.config}
isEntitled={isEntitled}
updateAppearance={updateAppearance}
onSaveAppearance={onSaveAppearance}
/>
</>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,16 @@ const meta: Meta<typeof AppearanceSettingsPageView> = {
},
},
isEntitled: false,
updateAppearance: () => {
return undefined;
},
},
};

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

export const Page: Story = {};
export const Entitled: Story = {
args: {
isEntitled: true,
},
};

export const NotEntitled: Story = {};
Loading