Skip to content

Commit

Permalink
refactor: migrate environment to BUILD_CONFIG
Browse files Browse the repository at this point in the history
  • Loading branch information
forehalo committed Sep 12, 2024
1 parent ed217ab commit ab82d30
Show file tree
Hide file tree
Showing 85 changed files with 298 additions and 277 deletions.
2 changes: 1 addition & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ const createPattern = packageName => [
{
group: ['@affine/env/constant'],
message:
'Do not import from @affine/env/constant. Use `environment.isElectron` instead',
'Do not import from @affine/env/constant. Use `BUILD_CONFIG.isElectron` instead',
importNames: ['isElectron'],
},
];
Expand Down
3 changes: 0 additions & 3 deletions packages/common/env/src/constant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,6 @@ declare global {
};
}

//#region runtime variables
export const isElectron = !!globalThis.__appInfo?.electron;
//#endregion
export const DEFAULT_WORKSPACE_NAME = 'Demo Workspace';
export const UNTITLED_WORKSPACE_NAME = 'Untitled';

Expand Down
94 changes: 39 additions & 55 deletions packages/common/env/src/global.ts
Original file line number Diff line number Diff line change
@@ -1,51 +1,47 @@
/// <reference types="@blocksuite/global" />
import { assertEquals } from '@blocksuite/global/utils';
import { z } from 'zod';

import { isElectron } from './constant.js';
import { UaHelper } from './ua-helper.js';

export const BUILD_CONFIG_SCHEMA = z.object({
// this is for the electron app
serverUrlPrefix: z.string(),
appVersion: z.string(),
editorVersion: z.string(),
distribution: z.enum(['web', 'desktop', 'admin', 'mobile']),
appBuildType: z.union([
z.literal('stable'),
z.literal('beta'),
z.literal('internal'),
z.literal('canary'),
]),
isSelfHosted: z.boolean().optional(),
githubUrl: z.string(),
changelogUrl: z.string(),
downloadUrl: z.string(),
// see: tools/workers
imageProxyUrl: z.string(),
linkPreviewUrl: z.string(),
allowLocalWorkspace: z.boolean(),
enablePreloading: z.boolean(),
enableNewSettingUnstableApi: z.boolean(),
enableExperimentalFeature: z.boolean(),
enableThemeEditor: z.boolean(),
});

export type BUILD_CONFIG_TYPE = z.infer<typeof BUILD_CONFIG_SCHEMA>;

export type Environment = {
isDebug: boolean;

// Edition
export type BUILD_CONFIG_TYPE = {
debug: boolean;
distribution: 'web' | 'desktop' | 'admin' | 'mobile';
/**
* 'web' | 'desktop' | 'admin'
*/
isDesktopEdition: boolean;
/**
* 'mobile'
*/
isMobileEdition: boolean;

// Platform/Entry
isElectron: boolean;
isDesktopWeb: boolean;
isWeb: boolean;
isMobileWeb: boolean;
isStandalone?: boolean;

// this is for the electron app
serverUrlPrefix: string;
appVersion: string;
editorVersion: string;
appBuildType: 'stable' | 'beta' | 'internal' | 'canary';

githubUrl: string;
changelogUrl: string;
downloadUrl: string;
// see: tools/workers
imageProxyUrl: string;
linkPreviewUrl: string;

allowLocalWorkspace: boolean;
enablePreloading: boolean;
enableNewSettingUnstableApi: boolean;
enableExperimentalFeature: boolean;
enableThemeEditor: boolean;

// TODO(@forehalo): remove
isSelfHosted: boolean;
};

export type Environment = {
// Device
isLinux: boolean;
isMacOs: boolean;
Expand All @@ -55,6 +51,8 @@ export type Environment = {
isFireFox: boolean;
isMobile: boolean;
isChrome: boolean;
isPwa: boolean;

chromeVersion?: number;
};

Expand All @@ -64,35 +62,23 @@ export function setupGlobal() {
}

let environment: Environment;
const isDebug = process.env.NODE_ENV === 'development';

if (!globalThis.navigator) {
environment = {
isDesktopEdition: false,
isMobileEdition: false,
isElectron: false,
isDesktopWeb: false,
isMobileWeb: false,
isMobile: false,
isDebug,
isLinux: false,
isMacOs: false,
isSafari: false,
isWindows: false,
isFireFox: false,
isChrome: false,
isIOS: false,
isPwa: false,
isMobile: false,
};
} else {
const uaHelper = new UaHelper(globalThis.navigator);

environment = {
isDesktopEdition: BUILD_CONFIG.distribution !== 'mobile',
isMobileEdition: BUILD_CONFIG.distribution === 'mobile',
isDesktopWeb: BUILD_CONFIG.distribution === 'web',
isMobileWeb: BUILD_CONFIG.distribution === 'mobile',
isElectron,
isDebug,
isMobile: uaHelper.isMobile,
isLinux: uaHelper.isLinux,
isMacOs: uaHelper.isMacOs,
Expand All @@ -101,12 +87,10 @@ export function setupGlobal() {
isFireFox: uaHelper.isFireFox,
isChrome: uaHelper.isChrome,
isIOS: uaHelper.isIOS,
isStandalone: uaHelper.isStandalone,
isPwa: uaHelper.isStandalone,
};
// Chrome on iOS is still Safari
if (environment.isChrome && !environment.isIOS) {
assertEquals(environment.isSafari, false);
assertEquals(environment.isFireFox, false);
environment = {
...environment,
isSafari: false,
Expand Down
4 changes: 2 additions & 2 deletions packages/common/infra/src/atom/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export const dateFormatOptions: DateFormats[] = [
];

const appSettingBaseAtom = atomWithStorage<AppSetting>('affine-settings', {
clientBorder: environment.isElectron && !environment.isWindows,
clientBorder: BUILD_CONFIG.isElectron && !environment.isWindows,
windowFrameStyle: 'frameless',
dateFormat: dateFormatOptions[0],
startWeekOnMonday: false,
Expand All @@ -61,7 +61,7 @@ type SetStateAction<Value> = Value | ((prev: Value) => Value);
const appSettingEffect = atomEffect(get => {
const settings = get(appSettingBaseAtom);
// some values in settings should be synced into electron side
if (environment.isElectron) {
if (BUILD_CONFIG.isElectron) {
logger.debug('sync settings to electron', settings);
// this api type in @affine/electron-api, but it is circular dependency this package, use any here
(window as any).apis?.updater
Expand Down
2 changes: 1 addition & 1 deletion packages/common/infra/src/livedata/effect/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ export function effect<T, A, B, C, D, E, F>(
export function effect(...args: any[]) {
const subject$ = new Subject<any>();

const effectLocation = environment.isDebug
const effectLocation = BUILD_CONFIG.debug
? `(${new Error().stack?.split('\n')[2].trim()})`
: '';

Expand Down
2 changes: 1 addition & 1 deletion packages/common/infra/src/modules/feature-flag/constant.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { FlagInfo } from './types';

const isNotStableBuild = BUILD_CONFIG.appBuildType !== 'stable';
const isDesktopEnvironment = environment.isElectron;
const isDesktopEnvironment = BUILD_CONFIG.isElectron;
const isCanaryBuild = BUILD_CONFIG.appBuildType === 'canary';

export const AFFINE_FLAGS = {
Expand Down
5 changes: 2 additions & 3 deletions packages/frontend/component/.storybook/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { StorybookConfig } from '@storybook/react-vite';
import { vanillaExtractPlugin } from '@vanilla-extract/vite-plugin';
import swc from 'unplugin-swc';
import { mergeConfig } from 'vite';
import { getRuntimeConfig } from '@affine/cli/src/webpack/runtime-config';
import { getBuildConfig } from '@affine/cli/src/webpack/runtime-config';

export default {
stories: ['../src/ui/**/*.@(mdx|stories.@(js|jsx|ts|tsx))'],
Expand Down Expand Up @@ -54,13 +54,12 @@ export default {
],
define: {
'process.env.CAPTCHA_SITE_KEY': `"${process.env.CAPTCHA_SITE_KEY}"`,
runtimeConfig: getRuntimeConfig({
runtimeConfig: getBuildConfig({
distribution: 'web',
mode: 'development',
channel: 'canary',
static: false,
coverage: false,
static: false,
}),
},
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export const AffineOtherPageLayout = ({

return (
<div className={styles.root}>
{environment.isElectron ? null : (
{!BUILD_CONFIG.isElectron && (
<div className={styles.topNav}>
<a href="/" rel="noreferrer" className={styles.affineLogo}>
<Logo1Icon width={24} height={24} />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,8 @@ export const OnboardingPage = ({
() => questions?.[questionIdx],
[questionIdx, questions]
);
const isMacosDesktop = environment.isElectron && environment.isMacOs;
const isWindowsDesktop = environment.isElectron && environment.isWindows;
const isMacosDesktop = BUILD_CONFIG.isElectron && environment.isMacOs;
const isWindowsDesktop = BUILD_CONFIG.isElectron && environment.isWindows;

if (!questions) {
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const DesktopThemeSync = memo(function DesktopThemeSync() {
const lastThemeRef = useRef(theme);
const onceRef = useRef(false);
if (lastThemeRef.current !== theme || !onceRef.current) {
if (environment.isElectron && theme) {
if (BUILD_CONFIG.isElectron && theme) {
apis?.ui
.handleThemeChange(theme as 'dark' | 'light' | 'system')
.catch(err => {
Expand Down
10 changes: 6 additions & 4 deletions packages/frontend/component/src/ui/menu/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,14 @@ import { MobileMenu } from './mobile/root';
import { MobileMenuSeparator } from './mobile/separator';
import { MobileMenuSub } from './mobile/sub';

const MenuItem = environment.isMobileEdition ? MobileMenuItem : DesktopMenuItem;
const MenuSeparator = environment.isMobileEdition
const MenuItem = BUILD_CONFIG.isMobileEdition
? MobileMenuItem
: DesktopMenuItem;
const MenuSeparator = BUILD_CONFIG.isMobileEdition
? MobileMenuSeparator
: DesktopMenuSeparator;
const MenuSub = environment.isMobileEdition ? MobileMenuSub : DesktopMenuSub;
const Menu = environment.isMobileEdition ? MobileMenu : DesktopMenu;
const MenuSub = BUILD_CONFIG.isMobileEdition ? MobileMenuSub : DesktopMenuSub;
const Menu = BUILD_CONFIG.isMobileEdition ? MobileMenu : DesktopMenu;

export {
DesktopMenu,
Expand Down
2 changes: 1 addition & 1 deletion packages/frontend/component/src/ui/menu/use-menu-item.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export const useMenuItem = <T extends MenuItemProps>({
checked,
selected,
block,
[mobileMenuItem]: environment.isMobileEdition,
[mobileMenuItem]: BUILD_CONFIG.isMobileEdition,
},
propsClassName
);
Expand Down
6 changes: 3 additions & 3 deletions packages/frontend/component/src/ui/modal/modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ export const ModalInner = forwardRef<HTMLDivElement, ModalProps>(
children,
contentWrapperClassName,
contentWrapperStyle,
animation = environment.isMobileEdition ? 'slideBottom' : 'fadeScaleTop',
animation = BUILD_CONFIG.isMobileEdition ? 'slideBottom' : 'fadeScaleTop',
fullScreen,
...otherProps
} = props;
Expand Down Expand Up @@ -208,15 +208,15 @@ export const ModalInner = forwardRef<HTMLDivElement, ModalProps>(
`anim-${animation}`,
styles.modalOverlay,
overlayClassName,
{ mobile: environment.isMobileEdition }
{ mobile: BUILD_CONFIG.isMobileEdition }
)}
style={{
...overlayStyle,
}}
{...otherOverlayOptions}
>
<SafeArea
bottom={environment.isMobileEdition}
bottom={BUILD_CONFIG.isMobileEdition}
bottomOffset={12}
data-full-screen={fullScreen}
data-modal={modal}
Expand Down
2 changes: 1 addition & 1 deletion packages/frontend/component/src/ui/safe-area/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export const SafeArea = forwardRef<HTMLDivElement, SafeAreaProps>(
<div
ref={ref}
className={clsx(safeArea, className)}
data-standalone={environment.isStandalone ? '' : undefined}
data-standalone={environment.isPwa ? '' : undefined}
data-bottom={bottom ? '' : undefined}
data-top={top ? '' : undefined}
style={{
Expand Down
4 changes: 2 additions & 2 deletions packages/frontend/core/src/commands/affine-creation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export function registerAffineCreationCommands({
category: 'affine:creation',
label: t['com.affine.cmdk.affine.new-page'](),
icon: <PlusIcon />,
keyBinding: environment.isElectron
keyBinding: BUILD_CONFIG.isElectron
? {
binding: '$mod+N',
skipRegister: true,
Expand Down Expand Up @@ -73,7 +73,7 @@ export function registerAffineCreationCommands({
icon: <ImportIcon />,
label: t['com.affine.cmdk.affine.import-workspace'](),
preconditionStrategy: () => {
return environment.isElectron;
return BUILD_CONFIG.isElectron;
},
run() {
track.$.cmdk.workspace.createWorkspace({
Expand Down
7 changes: 4 additions & 3 deletions packages/frontend/core/src/commands/affine-settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ export function registerAffineSettingsCommands({
`,
category: 'affine:settings',
icon: <SettingsIcon />,
preconditionStrategy: () => environment.isElectron,
preconditionStrategy: () => BUILD_CONFIG.isElectron,
run() {
track.$.cmdk.settings.changeAppSetting({
key: 'clientBorder',
Expand Down Expand Up @@ -231,7 +231,7 @@ export function registerAffineSettingsCommands({
]()}`,
category: 'affine:settings',
icon: <SettingsIcon />,
preconditionStrategy: () => environment.isElectron,
preconditionStrategy: () => BUILD_CONFIG.isElectron,
run() {
track.$.cmdk.settings.changeAppSetting({
key: 'enableNoisyBackground',
Expand All @@ -257,7 +257,8 @@ export function registerAffineSettingsCommands({
]()}`,
category: 'affine:settings',
icon: <SettingsIcon />,
preconditionStrategy: () => environment.isElectron && environment.isMacOs,
preconditionStrategy: () =>
BUILD_CONFIG.isElectron && environment.isMacOs,
run() {
track.$.cmdk.settings.changeAppSetting({
key: 'enableBlurBackground',
Expand Down
Loading

0 comments on commit ab82d30

Please sign in to comment.