fix: add platform selector to storybook (#4380)

This commit is contained in:
Peng Xiao
2023-09-15 16:59:29 +08:00
committed by GitHub
parent f730f2b242
commit eea38a08c5
12 changed files with 81 additions and 26 deletions

View File

@@ -47,6 +47,12 @@ const createPattern = packageName => [
message: 'Do not use this API because it has a bug', message: 'Do not use this API because it has a bug',
importNames: ['mergeUpdates'], importNames: ['mergeUpdates'],
}, },
{
group: ['@affine/env/constant'],
message:
'Do not import from @affine/env/constant. Use `environment.isDesktop` instead',
importNames: ['isDesktop'],
},
]; ];
const allPackages = [ const allPackages = [

View File

@@ -6,7 +6,6 @@ import {
ModalHeader, ModalHeader,
} from '@affine/component/auth-components'; } from '@affine/component/auth-components';
import { pushNotificationAtom } from '@affine/component/notification-center'; import { pushNotificationAtom } from '@affine/component/notification-center';
import { isDesktop } from '@affine/env/constant';
import { import {
sendChangeEmailMutation, sendChangeEmailMutation,
sendChangePasswordEmailMutation, sendChangePasswordEmailMutation,
@@ -118,7 +117,7 @@ const useSendEmail = (emailType: AuthPanelProps['emailType']) => {
return trigger({ return trigger({
email, email,
callbackUrl: `/auth/${callbackUrl}?isClient=${ callbackUrl: `/auth/${callbackUrl}?isClient=${
isDesktop ? 'true' : 'false' environment.isDesktop ? 'true' : 'false'
}`, }`,
}); });
}, },

View File

@@ -3,7 +3,6 @@ import {
appSidebarOpenAtom, appSidebarOpenAtom,
SidebarSwitch, SidebarSwitch,
} from '@affine/component/app-sidebar'; } from '@affine/component/app-sidebar';
import { isDesktop } from '@affine/env/constant';
import { useIsTinyScreen } from '@toeverything/hooks/use-is-tiny-screen'; import { useIsTinyScreen } from '@toeverything/hooks/use-is-tiny-screen';
import clsx from 'clsx'; import clsx from 'clsx';
import { type Atom, useAtomValue } from 'jotai'; import { type Atom, useAtomValue } from 'jotai';
@@ -45,7 +44,7 @@ export const Header = forwardRef<HTMLDivElement, HeaderPros>(function Header(
rightStatic: windowControlsRef, rightStatic: windowControlsRef,
}); });
const isWindowsDesktop = globalThis.platform === 'win32' && isDesktop; const isWindowsDesktop = environment.isDesktop && environment.isWindows;
const open = useAtomValue(appSidebarOpenAtom); const open = useAtomValue(appSidebarOpenAtom);
const appSidebarFloating = useAtomValue(appSidebarFloatingAtom); const appSidebarFloating = useAtomValue(appSidebarFloatingAtom);
return ( return (

View File

@@ -1,6 +1,5 @@
import { BrowserWarning } from '@affine/component/affine-banner'; import { BrowserWarning } from '@affine/component/affine-banner';
import { DownloadTips } from '@affine/component/affine-banner'; import { DownloadTips } from '@affine/component/affine-banner';
import { isDesktop } from '@affine/env/constant';
import { Trans } from '@affine/i18n'; import { Trans } from '@affine/i18n';
import { useAFFiNEI18N } from '@affine/i18n/hooks'; import { useAFFiNEI18N } from '@affine/i18n/hooks';
import { useAtom } from 'jotai'; import { useAtom } from 'jotai';
@@ -11,7 +10,7 @@ import { guideDownloadClientTipAtom } from '../../../atoms/guide';
const minimumChromeVersion = 102; const minimumChromeVersion = 102;
const shouldShowWarning = () => { const shouldShowWarning = () => {
if (isDesktop) { if (environment.isDesktop) {
// even though desktop has compatibility issues, // even though desktop has compatibility issues,
// we don't want to show the warning // we don't want to show the warning
return false; return false;
@@ -64,7 +63,7 @@ export const TopTip = () => {
setShowWarning(shouldShowWarning()); setShowWarning(shouldShowWarning());
}, []); }, []);
if (showDownloadTip && isDesktop) { if (showDownloadTip && environment.isDesktop) {
return ( return (
<DownloadTips <DownloadTips
onClose={() => { onClose={() => {

View File

@@ -8,7 +8,7 @@ import * as style from './style.css';
const maximizedAtom = atomWithObservable(() => { const maximizedAtom = atomWithObservable(() => {
return new Observable<boolean>(subscriber => { return new Observable<boolean>(subscriber => {
subscriber.next(false); subscriber.next(false);
return window?.events.ui.onMaximized(maximized => { return window.events?.ui.onMaximized(maximized => {
return subscriber.next(maximized); return subscriber.next(maximized);
}); });
}); });

View File

@@ -11,7 +11,6 @@ import {
SidebarScrollableContainer, SidebarScrollableContainer,
} from '@affine/component/app-sidebar'; } from '@affine/component/app-sidebar';
import { useCollectionManager } from '@affine/component/page-list'; import { useCollectionManager } from '@affine/component/page-list';
import { isDesktop } from '@affine/env/constant';
import { useAFFiNEI18N } from '@affine/i18n/hooks'; import { useAFFiNEI18N } from '@affine/i18n/hooks';
import { import {
DeleteTemporarilyIcon, DeleteTemporarilyIcon,
@@ -117,7 +116,7 @@ export const RootAppSidebar = ({
// Listen to the "New Page" action from the menu // Listen to the "New Page" action from the menu
useEffect(() => { useEffect(() => {
if (isDesktop) { if (environment.isDesktop) {
return window.events?.applicationMenu.onNewPageAction(onClickNewPage); return window.events?.applicationMenu.onNewPageAction(onClickNewPage);
} }
return; return;
@@ -125,7 +124,7 @@ export const RootAppSidebar = ({
const [sidebarOpen, setSidebarOpen] = useAtom(appSidebarOpenAtom); const [sidebarOpen, setSidebarOpen] = useAtom(appSidebarOpenAtom);
useEffect(() => { useEffect(() => {
if (isDesktop) { if (environment.isDesktop) {
window.apis?.ui.handleSidebarVisibilityChange(sidebarOpen).catch(err => { window.apis?.ui.handleSidebarVisibilityChange(sidebarOpen).catch(err => {
console.error(err); console.error(err);
}); });
@@ -252,7 +251,7 @@ export const RootAppSidebar = ({
)} )}
</SidebarScrollableContainer> </SidebarScrollableContainer>
<SidebarContainer> <SidebarContainer>
{isDesktop && <AppUpdaterButton />} {environment.isDesktop && <AppUpdaterButton />}
<div style={{ height: '4px' }} /> <div style={{ height: '4px' }} />
<AddPageButton onClick={onClickNewPage} /> <AddPageButton onClick={onClickNewPage} />
</SidebarContainer> </SidebarContainer>

View File

@@ -1,7 +1,6 @@
import '@toeverything/hooks/use-affine-ipc-renderer'; import '@toeverything/hooks/use-affine-ipc-renderer';
import { pushNotificationAtom } from '@affine/component/notification-center'; import { pushNotificationAtom } from '@affine/component/notification-center';
import { isDesktop } from '@affine/env/constant';
import { useAFFiNEI18N } from '@affine/i18n/hooks'; import { useAFFiNEI18N } from '@affine/i18n/hooks';
import { refreshRootMetadataAtom } from '@affine/workspace/atom'; import { refreshRootMetadataAtom } from '@affine/workspace/atom';
import { useAtom, useSetAtom } from 'jotai'; import { useAtom, useSetAtom } from 'jotai';
@@ -47,7 +46,7 @@ const SessionDefence = (props: PropsWithChildren) => {
type: 'success', type: 'success',
}); });
if (isDesktop) { if (environment.isDesktop) {
window.affine.ipcRenderer.send('affine:login'); window.affine.ipcRenderer.send('affine:login');
} }
} }

View File

@@ -1,4 +1,3 @@
import { isDesktop } from '@affine/env/constant';
import { import {
generateRandUTF16Chars, generateRandUTF16Chars,
SPAN_ID_BYTES, SPAN_ID_BYTES,
@@ -48,7 +47,7 @@ function onRejectHandleTrace<T>(
export const signInCloud: typeof signIn = async (provider, ...rest) => { export const signInCloud: typeof signIn = async (provider, ...rest) => {
const traceParams = genTraceParams(); const traceParams = genTraceParams();
if (isDesktop) { if (environment.isDesktop) {
if (provider === 'google') { if (provider === 'google') {
open( open(
`${ `${
@@ -104,7 +103,7 @@ export const signOutCloud: typeof signOut = async options => {
export function buildCallbackUrl(callbackUrl: string) { export function buildCallbackUrl(callbackUrl: string) {
const params: string[][] = []; const params: string[][] = [];
if (isDesktop && window.appInfo.schema) { if (environment.isDesktop && window.appInfo.schema) {
params.push(['schema', window.appInfo.schema]); params.push(['schema', window.appInfo.schema]);
} }
const query = const query =

View File

@@ -16,6 +16,9 @@ import { createStore } from 'jotai/vanilla';
import { _setCurrentStore } from '@toeverything/infra/atom'; import { _setCurrentStore } from '@toeverything/infra/atom';
import { setupGlobal } from '@affine/env/global'; import { setupGlobal } from '@affine/env/global';
import type { Preview } from '@storybook/react';
import { useLayoutEffect, useRef } from 'react';
setupGlobal(); setupGlobal();
export const parameters = { export const parameters = {
backgrounds: { disable: true }, backgrounds: { disable: true },
@@ -140,4 +143,58 @@ const withContextDecorator: Decorator = (Story, context) => {
); );
}; };
export const decorators = [withContextDecorator, withI18n, withMockAuth]; const platforms = ['web', 'desktop-macos', 'desktop-windows'] as const;
const withPlatformSelectionDecorator: Decorator = (Story, context) => {
const setupCounterRef = useRef(0);
useLayoutEffect(() => {
if (setupCounterRef.current++ === 0) {
return;
}
switch (context.globals.platform) {
case 'desktop-macos':
environment.isDesktop = true;
environment.isMacOs = true;
environment.isWindows = false;
break;
case 'desktop-windows':
environment.isDesktop = true;
environment.isMacOs = false;
environment.isWindows = true;
break;
default:
globalThis.$AFFINE_SETUP = false;
setupGlobal();
break;
}
}, [context.globals.platform]);
return <Story key={context.globals.platform} {...context} />;
};
const decorators = [
withContextDecorator,
withI18n,
withMockAuth,
withPlatformSelectionDecorator,
];
const preview: Preview = {
decorators,
globalTypes: {
platform: {
description: 'Rendering platform target',
defaultValue: 'web',
toolbar: {
// The label to show for this toolbar item
title: 'platform',
// Array of plain string values or MenuItem shape (see below)
items: platforms,
// Change title based on selected value
dynamicTitle: true,
},
},
},
};
export default preview;

View File

@@ -1,4 +1,3 @@
import { isDesktop } from '@affine/env/constant';
import { useAFFiNEI18N } from '@affine/i18n/hooks'; import { useAFFiNEI18N } from '@affine/i18n/hooks';
import { import {
DeletePermanentlyIcon, DeletePermanentlyIcon,
@@ -66,7 +65,7 @@ export const OperationCell = ({
? t['com.affine.favoritePageOperation.remove']() ? t['com.affine.favoritePageOperation.remove']()
: t['com.affine.favoritePageOperation.add']()} : t['com.affine.favoritePageOperation.add']()}
</MenuItem> </MenuItem>
{!isDesktop && ( {!environment.isDesktop && (
<MenuItem <MenuItem
onClick={onOpenPageInNewTab} onClick={onOpenPageInNewTab}
preFix={ preFix={

View File

@@ -1,4 +1,3 @@
import { isDesktop } from '@affine/env/constant';
import { ThemeProvider as NextThemeProvider, useTheme } from 'next-themes'; import { ThemeProvider as NextThemeProvider, useTheme } from 'next-themes';
import type { PropsWithChildren } from 'react'; import type { PropsWithChildren } from 'react';
import { memo, useRef } from 'react'; import { memo, useRef } from 'react';
@@ -10,7 +9,7 @@ const DesktopThemeSync = memo(function DesktopThemeSync() {
const lastThemeRef = useRef(theme); const lastThemeRef = useRef(theme);
const onceRef = useRef(false); const onceRef = useRef(false);
if (lastThemeRef.current !== theme || !onceRef.current) { if (lastThemeRef.current !== theme || !onceRef.current) {
if (isDesktop && theme) { if (environment.isDesktop && theme) {
window.apis?.ui window.apis?.ui
.handleThemeChange(theme as 'dark' | 'light' | 'system') .handleThemeChange(theme as 'dark' | 'light' | 'system')
.catch(err => { .catch(err => {

View File

@@ -1,4 +1,4 @@
import { isBrowser, isDesktop } from '@affine/env/constant'; import { isBrowser } from '@affine/env/constant';
import type { BlockSuiteFeatureFlags } from '@affine/env/global'; import type { BlockSuiteFeatureFlags } from '@affine/env/global';
import { WorkspaceFlavour } from '@affine/env/workspace'; import { WorkspaceFlavour } from '@affine/env/workspace';
import { createAffinePublicProviders } from '@affine/workspace/providers'; import { createAffinePublicProviders } from '@affine/workspace/providers';
@@ -101,7 +101,7 @@ export function getOrCreateWorkspace(
if (isBrowser) { if (isBrowser) {
blobStorages.push(createIndexeddbStorage); blobStorages.push(createIndexeddbStorage);
blobStorages.push(createCloudBlobStorage); blobStorages.push(createCloudBlobStorage);
if (isDesktop && runtimeConfig.enableSQLiteProvider) { if (environment.isDesktop && runtimeConfig.enableSQLiteProvider) {
blobStorages.push(createSQLiteStorage); blobStorages.push(createSQLiteStorage);
} }
providerCreators.push(...createAffineProviders()); providerCreators.push(...createAffineProviders());
@@ -111,7 +111,7 @@ export function getOrCreateWorkspace(
} else if (flavour === WorkspaceFlavour.LOCAL) { } else if (flavour === WorkspaceFlavour.LOCAL) {
if (isBrowser) { if (isBrowser) {
blobStorages.push(createIndexeddbStorage); blobStorages.push(createIndexeddbStorage);
if (isDesktop && runtimeConfig.enableSQLiteProvider) { if (environment.isDesktop && runtimeConfig.enableSQLiteProvider) {
blobStorages.push(createSQLiteStorage); blobStorages.push(createSQLiteStorage);
} }
} }
@@ -119,7 +119,7 @@ export function getOrCreateWorkspace(
} else if (flavour === WorkspaceFlavour.AFFINE_PUBLIC) { } else if (flavour === WorkspaceFlavour.AFFINE_PUBLIC) {
if (isBrowser) { if (isBrowser) {
blobStorages.push(createIndexeddbStorage); blobStorages.push(createIndexeddbStorage);
if (isDesktop && runtimeConfig.enableSQLiteProvider) { if (environment.isDesktop && runtimeConfig.enableSQLiteProvider) {
blobStorages.push(createSQLiteStorage); blobStorages.push(createSQLiteStorage);
} }
} }