Skip to content
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

Addon Test: Refactor UI & add config options #29662

Merged
merged 26 commits into from
Nov 26, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
d849ed7
allow passing generic up
ndelangen Nov 19, 2024
917bb30
add useful generic types
ndelangen Nov 19, 2024
e47e23a
do not wrap custom render
ndelangen Nov 19, 2024
4e01e33
refactor ui of test addon
ndelangen Nov 19, 2024
3196ee6
add editing
ndelangen Nov 19, 2024
ac091c1
cleanup
ndelangen Nov 20, 2024
e9aa7fb
Merge branch 'next' into norbert/testmodule-options
ndelangen Nov 20, 2024
c889cfb
move editing to local state and move custom state to config and make …
ndelangen Nov 20, 2024
fa74d64
Merge branch 'determine-total-test-count' into norbert/testmodule-opt…
ndelangen Nov 21, 2024
7a53842
Merge branch 'determine-total-test-count' into norbert/testmodule-opt…
ndelangen Nov 22, 2024
b66b5fe
emit config change event when it's set & emit config along with switc…
ndelangen Nov 22, 2024
34b2a53
Merge branch 'norbert/testmodule-options' of https://github.com/story…
ndelangen Nov 22, 2024
b8e0e2e
Merge branch 'determine-total-test-count' into norbert/testmodule-opt…
ndelangen Nov 22, 2024
6938f52
Merge branch 'determine-total-test-count' into norbert/testmodule-opt…
ndelangen Nov 22, 2024
f62c975
add to list of exports
ndelangen Nov 22, 2024
29f1b77
Merge branch 'norbert/testmodule-options' of https://github.com/story…
ndelangen Nov 22, 2024
f603ffb
Merge branch 'determine-total-test-count' into norbert/testmodule-opt…
ndelangen Nov 22, 2024
4956363
Merge branch 'determine-total-test-count' into norbert/testmodule-opt…
ndelangen Nov 22, 2024
255e11f
Merge branch 'determine-total-test-count' into norbert/testmodule-opt…
ndelangen Nov 25, 2024
942e321
Merge branch 'determine-total-test-count' into norbert/testmodule-opt…
ndelangen Nov 25, 2024
2e4075f
fixes
ndelangen Nov 25, 2024
27279ec
refactor the sidebarbottom to support dynamic height content
ndelangen Nov 26, 2024
adb4e15
add more stories & cleanup
ndelangen Nov 26, 2024
8ebbba4
Merge branch 'next' into norbert/testmodule-options
ndelangen Nov 26, 2024
e03be02
fix tests
ndelangen Nov 26, 2024
3f34f9d
rename slow to indicate it's about the CSS transition being toggled o…
ndelangen Nov 26, 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
50 changes: 50 additions & 0 deletions code/addons/test/src/components/Description.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import React from 'react';

import { Link as LinkComponent } from 'storybook/internal/components';
import { type TestProviderConfig, type TestProviderState } from 'storybook/internal/core-events';

import { RelativeTime } from './RelativeTime';
import { DescriptionStyle } from './TestProviderRender';

export function Description({
errorMessage,
setIsModalOpen,
state,
}: {
state: TestProviderConfig & TestProviderState;
errorMessage: string;
setIsModalOpen: React.Dispatch<React.SetStateAction<boolean>>;
}) {
let description: string | React.ReactNode = 'Not run';
ghengeveld marked this conversation as resolved.
Show resolved Hide resolved

if (state.running) {
description = state.progress
? `Testing... ${state.progress.numPassedTests}/${state.progress.numTotalTests}`
: 'Starting...';
Comment on lines +26 to +28
Copy link
Contributor

Choose a reason for hiding this comment

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

logic: numTotalTests could be undefined here, which would show 'Testing... 5/undefined'

} else if (state.failed && !errorMessage) {
description = '';
Comment on lines +29 to +30
Copy link
Contributor

Choose a reason for hiding this comment

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

logic: Setting description to empty string when failed without error message could lead to confusing UI state. Consider showing a default failure message instead.

} else if (state.crashed || (state.failed && errorMessage)) {
description = (
<>
<LinkComponent
isButton
onClick={() => {
setIsModalOpen(true);
}}
>
{state.error?.name || 'View full error'}
</LinkComponent>
</>
Comment on lines +34 to +42
Copy link
Contributor

Choose a reason for hiding this comment

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

style: Fragment wrapper is unnecessary since LinkComponent is the only child

);
} else if (state.progress?.finishedAt) {
description = (
<RelativeTime
timestamp={new Date(state.progress.finishedAt)}
ghengeveld marked this conversation as resolved.
Show resolved Hide resolved
testCount={state.progress.numTotalTests}
/>
);
} else if (state.watching) {
description = 'Watching for file changes';
}
return <DescriptionStyle id="testing-module-description">{description}</DescriptionStyle>;
}
19 changes: 18 additions & 1 deletion code/addons/test/src/components/RelativeTime.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,23 @@
import { useEffect, useState } from 'react';

import { getRelativeTimeString } from '../manager';
export function getRelativeTimeString(date: Date): string {
const delta = Math.round((date.getTime() - Date.now()) / 1000);
Copy link
Contributor

Choose a reason for hiding this comment

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

logic: delta calculation will be negative for future dates, but Math.abs is only used later - could cause incorrect time displays

const cutoffs = [60, 3600, 86400, 86400 * 7, 86400 * 30, 86400 * 365, Infinity];
const units: Intl.RelativeTimeFormatUnit[] = [
'second',
'minute',
'hour',
'day',
'week',
'month',
'year',
];

const unitIndex = cutoffs.findIndex((cutoff) => cutoff > Math.abs(delta));
const divisor = unitIndex ? cutoffs[unitIndex - 1] : 1;
const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
return rtf.format(Math.floor(delta / divisor), units[unitIndex]);
}

export const RelativeTime = ({ timestamp, testCount }: { timestamp: Date; testCount: number }) => {
const [relativeTimeString, setRelativeTimeString] = useState(null);
Copy link
Contributor

Choose a reason for hiding this comment

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

style: initial state should be typed as useState<string | null>(null)

Expand Down
136 changes: 136 additions & 0 deletions code/addons/test/src/components/TestProviderRender.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
import React from 'react';

import type { TestProviderConfig, TestProviderState } from 'storybook/internal/core-events';
import { ManagerContext } from 'storybook/internal/manager-api';
import { styled } from 'storybook/internal/theming';
import { Addon_TypesEnum } from 'storybook/internal/types';

import type { Meta, StoryObj } from '@storybook/react';
import { fn } from '@storybook/test';

import type { Details } from '../constants';
import { TestProviderRender } from './TestProviderRender';

type Story = StoryObj<typeof TestProviderRender>;
const managerContext: any = {
Copy link
Contributor

Choose a reason for hiding this comment

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

style: Avoid using 'any' type for managerContext. Consider creating a proper type definition based on ManagerContext requirements.

state: {
testProviders: {
'test-provider-id': {
id: 'test-provider-id',
name: 'Test Provider',
type: Addon_TypesEnum.experimental_TEST_PROVIDER,
},
},
},
api: {
getDocsUrl: fn().mockName('api::getDocsUrl'),
emit: fn().mockName('api::emit'),
},
};

const config: TestProviderConfig = {
id: 'test-provider-id',
name: 'Test Provider',
type: Addon_TypesEnum.experimental_TEST_PROVIDER,
runnable: true,
watchable: true,
};

const baseState: TestProviderState<Details> = {
cancellable: true,
cancelling: false,
crashed: false,
error: null,
failed: false,
running: false,
watching: false,
details: {
editing: false,
options: {
a11y: false,
coverage: false,
},
testResults: [
{
endTime: 0,
startTime: 0,
status: 'passed',
message: 'All tests passed',
results: [
{
storyId: 'story-id',
status: 'success',
duration: 100,
testRunId: 'test-run-id',
},
],
},
],
},
};

const Content = styled.div({
padding: '12px 6px',
display: 'flex',
flexDirection: 'column',
gap: '12px',
});

export default {
title: 'TestProviderRender',
component: TestProviderRender,
args: {
state: {
...config,
...baseState,
},
},
decorators: [
(StoryFn) => (
<ManagerContext.Provider value={managerContext}>
<StoryFn api={managerContext.api} />
</ManagerContext.Provider>
ndelangen marked this conversation as resolved.
Show resolved Hide resolved
),
(StoryFn) => (
<Content>
<StoryFn />
</Content>
),
],
} as Meta<typeof TestProviderRender>;

export const Default: Story = {
args: {
state: {
...config,
...baseState,
},
},
};

export const Running: Story = {
args: {
state: {
...config,
...baseState,
running: true,
},
},
};

export const EnableA11y: Story = {
args: {
state: {
...config,
...baseState,
details: {
editing: false,
options: {
a11y: true,
coverage: false,
},
testResults: [],
},
},
},
};
130 changes: 130 additions & 0 deletions code/addons/test/src/components/TestProviderRender.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
import React, { type FC, Fragment, useState } from 'react';

import { Button } from 'storybook/internal/components';
import {
TESTING_MODULE_RUN_ALL_REQUEST,
type TestProviderConfig,
type TestProviderState,
} from 'storybook/internal/core-events';
import type { API } from 'storybook/internal/manager-api';
import { styled } from 'storybook/internal/theming';

import { EyeIcon, PlayHollowIcon, StopAltHollowIcon } from '@storybook/icons';

import { type Details, TEST_PROVIDER_ID } from '../constants';
import { Description } from './Description';
import { GlobalErrorModal } from './GlobalErrorModal';

const Info = styled.div({
display: 'flex',
flexDirection: 'column',
marginLeft: 6,
});

const Title2 = styled.div<{ crashed?: boolean }>(({ crashed, theme }) => ({
fontSize: theme.typography.size.s1,
fontWeight: crashed ? 'bold' : 'normal',
color: crashed ? theme.color.negativeText : theme.color.defaultText,
}));

export const DescriptionStyle = styled.div(({ theme }) => ({
fontSize: theme.typography.size.s1,
color: theme.barTextColor,
}));

const Actions = styled.div({
display: 'flex',
gap: 6,
});

const Head = styled.div({
display: 'flex',
justifyContent: 'space-between',
gap: 6,
});

export const TestProviderRender: FC<{
api: API;
state: TestProviderConfig & TestProviderState<Details>;
}> = ({ state, api }) => {
const [isModalOpen, setIsModalOpen] = useState(false);

const title = state.crashed || state.failed ? 'Component tests failed' : 'Component tests';
const errorMessage = state.error?.message;
return (
<Fragment>
<Head>
<Info>
<Title2 crashed={state.crashed} id="testing-module-title">
{title}
</Title2>
<Description errorMessage={errorMessage} setIsModalOpen={setIsModalOpen} state={state} />
</Info>

<Actions>
{state.watchable && (
<Button
aria-label={`${state.watching ? 'Disable' : 'Enable'} watch mode for ${state.name}`}
variant="ghost"
padding="small"
active={state.watching}
onClick={() => api.setTestProviderWatchMode(state.id, !state.watching)}
disabled={state.crashed || state.running}
>
<EyeIcon />
</Button>
)}
{state.runnable && (
<>
{state.running && state.cancellable ? (
<Button
aria-label={`Stop ${state.name}`}
variant="ghost"
padding="small"
onClick={() => api.cancelTestProvider(state.id)}
disabled={state.cancelling}
>
<StopAltHollowIcon />
</Button>
) : (
<Button
aria-label={`Start ${state.name}`}
variant="ghost"
padding="small"
onClick={() => api.runTestProvider(state.id)}
disabled={state.crashed || state.running}
>
<PlayHollowIcon />
</Button>
)}
</>
)}
</Actions>
</Head>

{!state.details.editing ? (
<Fragment>
{state.details?.options?.a11y ? <div>A11Y</div> : null}
{state.details?.options?.coverage ? <div>COVERAGE</div> : null}
</Fragment>
) : (
<Fragment>
<div>EDITING A11Y</div>
<div>EDITING COVERAGE</div>
</Fragment>
)}

<GlobalErrorModal
error={errorMessage}
open={isModalOpen}
onClose={() => {
setIsModalOpen(false);
}}
onRerun={() => {
setIsModalOpen(false);
api.getChannel().emit(TESTING_MODULE_RUN_ALL_REQUEST, { providerId: TEST_PROVIDER_ID });
}}
ndelangen marked this conversation as resolved.
Show resolved Hide resolved
/>
</Fragment>
);
};
13 changes: 13 additions & 0 deletions code/addons/test/src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { TestResult } from './node/reporter';

export const ADDON_ID = 'storybook/test';
export const TEST_PROVIDER_ID = `${ADDON_ID}/test-provider`;
export const PANEL_ID = `${ADDON_ID}/panel`;
Expand All @@ -7,3 +9,14 @@ export const TUTORIAL_VIDEO_LINK = 'https://youtu.be/Waht9qq7AoA';
export const DOCUMENTATION_LINK = 'writing-tests/test-addon';
export const DOCUMENTATION_DISCREPANCY_LINK = `${DOCUMENTATION_LINK}#what-happens-when-there-are-different-test-results-in-multiple-environments`;
export const DOCUMENTATION_FATAL_ERROR_LINK = `${DOCUMENTATION_LINK}#what-happens-if-vitest-itself-has-an-error`;

interface Options {
coverage: boolean;
a11y: boolean;
}
ndelangen marked this conversation as resolved.
Show resolved Hide resolved

export type Details = {
testResults: TestResult[];
options: Options;
editing: boolean;
};
ndelangen marked this conversation as resolved.
Show resolved Hide resolved
Loading