Skip to content

chore(site): add storybook for terminal page #12441

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
Mar 7, 2024
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
5 changes: 2 additions & 3 deletions site/src/@types/storybook.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,11 @@ import type { QueryKey } from "react-query";
import type { Experiments, FeatureName } from "api/typesGenerated";

declare module "@storybook/react" {
type WebSocketEvent = { event: "message"; data: string } | { event: "error" };
interface Parameters {
features?: FeatureName[];
experiments?: Experiments;
queries?: { key: QueryKey; data: unknown }[];
webSocket?: {
messages: string[];
};
webSocket?: WebSocketEvent[];
}
}
1 change: 0 additions & 1 deletion site/src/contexts/auth/AuthProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ export const AuthContext = createContext<AuthContextValue | undefined>(
export const AuthProvider: FC<PropsWithChildren> = ({ children }) => {
const queryClient = useQueryClient();
const meOptions = me();

const userQuery = useQuery(meOptions);
const authMethodsQuery = useQuery(authMethods());
const hasFirstUserQuery = useQuery(hasFirstUser());
Expand Down
7 changes: 4 additions & 3 deletions site/src/pages/CreateTemplatePage/BuildLogsDrawer.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,9 @@ export const Logs: Story = {
},
decorators: [withWebSocket],
parameters: {
webSocket: {
messages: MockWorkspaceBuildLogs.map((log) => JSON.stringify(log)),
},
webSocket: MockWorkspaceBuildLogs.map((log) => ({
event: "message",
data: JSON.stringify(log),
})),
},
};
144 changes: 144 additions & 0 deletions site/src/pages/TerminalPage/TerminalPage.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
import type { Meta, StoryObj } from "@storybook/react";
import {
reactRouterOutlet,
reactRouterParameters,
} from "storybook-addon-react-router-v6";
import { getAuthorizationKey } from "api/queries/authCheck";
import { workspaceByOwnerAndNameKey } from "api/queries/workspaces";
import type { Workspace, WorkspaceAgentLifecycle } from "api/typesGenerated";
import { AuthProvider } from "contexts/auth/AuthProvider";
import { permissionsToCheck } from "contexts/auth/permissions";
import { RequireAuth } from "contexts/auth/RequireAuth";
import {
MockAppearanceConfig,
MockAuthMethodsAll,
MockBuildInfo,
MockEntitlements,
MockExperiments,
MockUser,
MockWorkspace,
MockWorkspaceAgent,
} from "testHelpers/entities";
import { withWebSocket } from "testHelpers/storybook";
import TerminalPage from "./TerminalPage";

const createWorkspaceWithAgent = (lifecycle: WorkspaceAgentLifecycle) => {
return {
key: workspaceByOwnerAndNameKey(
MockWorkspace.owner_name,
MockWorkspace.name,
),
data: {
...MockWorkspace,
latest_build: {
...MockWorkspace.latest_build,
resources: [
{
...MockWorkspace.latest_build.resources[0],
agents: [{ ...MockWorkspaceAgent, lifecycle_state: lifecycle }],
},
],
},
} satisfies Workspace,
};
};

const meta = {
title: "pages/Terminal",
component: RequireAuth,
parameters: {
layout: "fullscreen",
reactRouter: reactRouterParameters({
location: {
pathParams: {
username: `@${MockWorkspace.owner_name}`,
workspace: MockWorkspace.name,
},
},
routing: reactRouterOutlet(
{
path: `/:username/:workspace/terminal`,
},
<TerminalPage />,
),
}),
queries: [
{ key: ["me"], data: MockUser },
{ key: ["authMethods"], data: MockAuthMethodsAll },
{ key: ["hasFirstUser"], data: true },
{ key: ["buildInfo"], data: MockBuildInfo },
{ key: ["entitlements"], data: MockEntitlements },
{ key: ["experiments"], data: MockExperiments },
{ key: ["appearance"], data: MockAppearanceConfig },
{
key: getAuthorizationKey({ checks: permissionsToCheck }),
data: { editWorkspaceProxies: true },
},
],
},
decorators: [
(Story) => (
<AuthProvider>
<Story />
</AuthProvider>
),
],
} satisfies Meta<typeof TerminalPage>;

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

export const Starting: Story = {
decorators: [withWebSocket],
parameters: {
...meta.parameters,
webSocket: [
{
event: "message",
// Copied and pasted this from browser
data: `➜ codergit:(bq/refactor-web-term-notifications) ✗`,
},
],
queries: [...meta.parameters.queries, createWorkspaceWithAgent("starting")],
},
};

export const Ready: Story = {
decorators: [withWebSocket],
parameters: {
...meta.parameters,
webSocket: [
{
event: "message",
// Copied and pasted this from browser
data: `➜ codergit:(bq/refactor-web-term-notifications) ✗`,
},
],
queries: [...meta.parameters.queries, createWorkspaceWithAgent("ready")],
},
};

export const StartError: Story = {
decorators: [withWebSocket],
parameters: {
...meta.parameters,
webSocket: [],
queries: [
...meta.parameters.queries,
createWorkspaceWithAgent("start_error"),
],
},
};

export const ConnectionError: Story = {
decorators: [withWebSocket],
parameters: {
...meta.parameters,
webSocket: [
{
event: "error",
},
],
queries: [...meta.parameters.queries, createWorkspaceWithAgent("ready")],
},
};
40 changes: 27 additions & 13 deletions site/src/testHelpers/storybook.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,25 +45,39 @@ export const withDashboardProvider = (
);
};

type MessageEvent = Record<"data", string>;
type CallbackFn = (ev?: MessageEvent) => void;

export const withWebSocket = (Story: FC, { parameters }: StoryContext) => {
if (!parameters.webSocket) {
console.warn(
"Looks like you forgot to add websocket messages to the story",
);
const events = parameters.webSocket;

if (!events) {
console.warn("You forgot to add `parameters.webSocket` to your story");
return <Story />;
}

const listeners = new Map<string, CallbackFn>();
let callEventsDelay: number;

// @ts-expect-error -- TS doesn't know about the global WebSocket
window.WebSocket = function () {
return {
addEventListener: (
type: string,
callback: (ev: Record<"data", string>) => void,
) => {
if (type === "message") {
parameters.webSocket?.messages.forEach((message) => {
callback({ data: message });
});
}
addEventListener: (type: string, callback: CallbackFn) => {
listeners.set(type, callback);

// Runs when the last event listener is added
clearTimeout(callEventsDelay);
callEventsDelay = window.setTimeout(() => {
Copy link
Member

Choose a reason for hiding this comment

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

Out of curiosity, why do we need the timeout? I think it makes sense since it allows us to make sure all the listeners are hooked up first but was there a bug with how it was before?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Yes, the problem with the previous implementation is that it did not respect the order of the events so if the error listener was defined before it would call it first even if it was the third event in the list for example.

Copy link
Member

Choose a reason for hiding this comment

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

Ohhhhh I see! Makes sense.

for (const entry of events) {
const callback = listeners.get(entry.event);

if (callback) {
entry.event === "message"
? callback({ data: entry.data })
: callback();
}
}
}, 0);
},
close: () => {},
};
Expand Down