Skip to content

Commit

Permalink
refactor: migrate environment to BUILD_CONFIG (#8206)
Browse files Browse the repository at this point in the history
  • Loading branch information
forehalo committed Sep 13, 2024
1 parent 561f96b commit a387e4a
Show file tree
Hide file tree
Showing 90 changed files with 297 additions and 260 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
4 changes: 2 additions & 2 deletions packages/frontend/apps/electron/renderer/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ const desktopWhiteList = [
'/magic-link',
];
if (
!environment.isElectron &&
environment.isDebug &&
!BUILD_CONFIG.isElectron &&
BUILD_CONFIG.debug &&
desktopWhiteList.every(path => !location.pathname.startsWith(path))
) {
document.body.innerHTML = `<h1 style="color:red;font-size:5rem;text-align:center;">Don't run electron entry in browser.</h1>`;
Expand Down
2 changes: 1 addition & 1 deletion packages/frontend/apps/electron/renderer/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ function main() {
performanceMainLogger.info('skip setup');
} else {
performanceMainLogger.info('setup start');
if (window.SENTRY_RELEASE || environment.isDebug) {
if (BUILD_CONFIG.debug || window.SENTRY_RELEASE) {
// https://docs.sentry.io/platforms/javascript/guides/electron/
init({
dsn: process.env.SENTRY_DSN,
Expand Down
8 changes: 4 additions & 4 deletions packages/frontend/apps/electron/renderer/shell/shell.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { AppFallback } from '@affine/core/components/affine/app-container';
import { ShellAppFallback } from '@affine/core/components/affine/app-container';
import { useAppSettingHelper } from '@affine/core/hooks/affine/use-app-setting-helper';
import { AppTabsHeader } from '@affine/core/modules/app-tabs-header';
import { SplitViewFallback } from '@affine/core/modules/workbench/view/split-view/split-view';
Expand All @@ -8,15 +8,15 @@ import * as styles from './shell.css';
export function ShellRoot() {
const { appSettings } = useAppSettingHelper();
const translucent =
environment.isElectron &&
BUILD_CONFIG.isElectron &&
environment.isMacOs &&
appSettings.enableBlurBackground;
return (
<div className={styles.root} data-translucent={translucent}>
<AppTabsHeader mode="shell" className={styles.appTabsHeader} />
<AppFallback className={styles.fallbackRoot}>
<ShellAppFallback className={styles.fallbackRoot}>
<SplitViewFallback className={styles.splitViewFallback} />
</AppFallback>
</ShellAppFallback>
</div>
);
}
6 changes: 3 additions & 3 deletions packages/frontend/apps/electron/scripts/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { resolve } from 'node:path';
import { fileURLToPath } from 'node:url';

// eslint-disable-next-line @typescript-eslint/no-restricted-imports
import { getRuntimeConfig } from '@affine/cli/src/webpack/runtime-config';
import { getBuildConfig } from '@affine/cli/src/webpack/runtime-config';
import { sentryEsbuildPlugin } from '@sentry/esbuild-plugin';
import type { BuildOptions, Plugin } from 'esbuild';

Expand All @@ -20,8 +20,8 @@ export const config = (): BuildOptions => {

define['REPLACE_ME_BUILD_ENV'] = `"${process.env.BUILD_TYPE ?? 'stable'}"`;

define['runtimeConfig'] = JSON.stringify(
getRuntimeConfig({
define['BUILD_CONFIG'] = JSON.stringify(
getBuildConfig({
channel: (process.env.BUILD_TYPE as any) ?? 'canary',
distribution: 'desktop',
mode:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -254,10 +254,10 @@ export async function openUrlInHiddenWindow(urlObj: URL) {
preload: join(__dirname, './preload.js'),
additionalArguments: await getWindowAdditionalArguments(),
},
show: environment.isDebug,
show: BUILD_CONFIG.debug,
});

if (environment.isDebug) {
if (BUILD_CONFIG.debug) {
win.webContents.openDevTools({
mode: 'detach',
});
Expand Down
5 changes: 0 additions & 5 deletions packages/frontend/apps/mobile/src/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,6 @@ import { RouterProvider } from 'react-router-dom';
import { configureMobileModules } from './modules';
import { router } from './router';

if (environment.isElectron && environment.isDebug) {
document.body.innerHTML = `<h1 style="color:red;font-size:5rem;text-align:center;">Don't run web entry in electron.</h1>`;
throw new Error('Wrong distribution');
}

const future = {
v7_startTransition: true,
} as const;
Expand Down
2 changes: 1 addition & 1 deletion packages/frontend/apps/mobile/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { App } from './app';
const performanceMainLogger = performanceLogger.namespace('main');
function main() {
performanceMainLogger.info('setup start');
if (window.SENTRY_RELEASE || environment.isDebug) {
if (BUILD_CONFIG.debug || window.SENTRY_RELEASE) {
// https://docs.sentry.io/platforms/javascript/guides/react/#configure
init({
dsn: process.env.SENTRY_DSN,
Expand Down
4 changes: 2 additions & 2 deletions packages/frontend/apps/mobile/src/pages/workspace/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -125,8 +125,8 @@ export const Component = () => {

if (workspaceNotFound) {
if (
detailDocRoute /* */ &&
environment.isDesktopEdition /* only browser has share page */
BUILD_CONFIG.isDesktopEdition /* only browser has share page */ &&
detailDocRoute
) {
return <div>TODO: share page</div>;
}
Expand Down
5 changes: 0 additions & 5 deletions packages/frontend/apps/web/src/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,6 @@ import {
import { Suspense } from 'react';
import { RouterProvider } from 'react-router-dom';

if (environment.isElectron && environment.isDebug) {
document.body.innerHTML = `<h1 style="color:red;font-size:5rem;text-align:center;">Don't run web entry in electron.</h1>`;
throw new Error('Wrong distribution');
}

const performanceI18nLogger = performanceLogger.namespace('i18n');
const cache = createEmotionCache();

Expand Down
4 changes: 2 additions & 2 deletions packages/frontend/apps/web/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@ function main() {
performanceMainLogger.info('start');

// skip bootstrap setup for desktop onboarding
if (environment.isElectron && appInfo?.windowName === 'onboarding') {
if (BUILD_CONFIG.isElectron && appInfo?.windowName === 'onboarding') {
performanceMainLogger.info('skip setup');
} else {
performanceMainLogger.info('setup start');
if (window.SENTRY_RELEASE || environment.isDebug) {
if (BUILD_CONFIG.debug || window.SENTRY_RELEASE) {
// https://docs.sentry.io/platforms/javascript/guides/react/#configure
init({
dsn: process.env.SENTRY_DSN,
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 ? (
{BUILD_CONFIG.isElectron ? (
<div className={styles.draggableHeader} />
) : (
<div className={styles.topNav}>
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
2 changes: 1 addition & 1 deletion packages/frontend/component/src/ui/button/button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
data-size={size}
data-variant={variant}
data-no-hover={withoutHover || undefined}
data-mobile={environment.isMobileEdition}
data-mobile={BUILD_CONFIG.isMobileEdition}
onClick={handleClick}
>
<IconSlot
Expand Down
Loading

0 comments on commit a387e4a

Please sign in to comment.