refactor: avoid runtime config object (#8202)

This commit is contained in:
forehalo
2024-09-13 07:27:11 +00:00
parent c76b4d70b0
commit 25969a34e8
45 changed files with 117 additions and 156 deletions
+6 -22
View File
@@ -5,7 +5,7 @@ import { z } from 'zod';
import { isElectron } from './constant.js'; import { isElectron } from './constant.js';
import { UaHelper } from './ua-helper.js'; import { UaHelper } from './ua-helper.js';
export const runtimeFlagsSchema = z.object({ export const BUILD_CONFIG_SCHEMA = z.object({
// this is for the electron app // this is for the electron app
serverUrlPrefix: z.string(), serverUrlPrefix: z.string(),
appVersion: z.string(), appVersion: z.string(),
@@ -27,14 +27,11 @@ export const runtimeFlagsSchema = z.object({
allowLocalWorkspace: z.boolean(), allowLocalWorkspace: z.boolean(),
enablePreloading: z.boolean(), enablePreloading: z.boolean(),
enableNewSettingUnstableApi: z.boolean(), enableNewSettingUnstableApi: z.boolean(),
enableEnhanceShareMode: z.boolean(),
enableExperimentalFeature: z.boolean(), enableExperimentalFeature: z.boolean(),
enableInfoModal: z.boolean(),
enableOrganize: z.boolean(),
enableThemeEditor: z.boolean(), enableThemeEditor: z.boolean(),
}); });
export type RuntimeConfig = z.infer<typeof runtimeFlagsSchema>; export type BUILD_CONFIG_TYPE = z.infer<typeof BUILD_CONFIG_SCHEMA>;
export type Environment = { export type Environment = {
isDebug: boolean; isDebug: boolean;
@@ -61,24 +58,11 @@ export type Environment = {
chromeVersion?: number; chromeVersion?: number;
}; };
function setupRuntimeConfig() {
if (!process.env.RUNTIME_CONFIG) {
return;
}
// registered by [webpack.DefinePlugin]
const runtimeConfig = JSON.parse(process.env.RUNTIME_CONFIG ?? '');
runtimeFlagsSchema.parse(runtimeConfig);
globalThis.runtimeConfig = runtimeConfig;
}
export function setupGlobal() { export function setupGlobal() {
if (globalThis.$AFFINE_SETUP) { if (globalThis.$AFFINE_SETUP) {
return; return;
} }
setupRuntimeConfig();
let environment: Environment; let environment: Environment;
const isDebug = process.env.NODE_ENV === 'development'; const isDebug = process.env.NODE_ENV === 'development';
@@ -103,10 +87,10 @@ export function setupGlobal() {
const uaHelper = new UaHelper(globalThis.navigator); const uaHelper = new UaHelper(globalThis.navigator);
environment = { environment = {
isDesktopEdition: runtimeConfig.distribution !== 'mobile', isDesktopEdition: BUILD_CONFIG.distribution !== 'mobile',
isMobileEdition: runtimeConfig.distribution === 'mobile', isMobileEdition: BUILD_CONFIG.distribution === 'mobile',
isDesktopWeb: runtimeConfig.distribution === 'web', isDesktopWeb: BUILD_CONFIG.distribution === 'web',
isMobileWeb: runtimeConfig.distribution === 'mobile', isMobileWeb: BUILD_CONFIG.distribution === 'mobile',
isElectron, isElectron,
isDebug, isDebug,
isMobile: uaHelper.isMobile, isMobile: uaHelper.isMobile,
@@ -1,8 +1,8 @@
import type { FlagInfo } from './types'; import type { FlagInfo } from './types';
const isNotStableBuild = runtimeConfig.appBuildType !== 'stable'; const isNotStableBuild = BUILD_CONFIG.appBuildType !== 'stable';
const isDesktopEnvironment = environment.isElectron; const isDesktopEnvironment = environment.isElectron;
const isCanaryBuild = runtimeConfig.appBuildType === 'canary'; const isCanaryBuild = BUILD_CONFIG.appBuildType === 'canary';
export const AFFINE_FLAGS = { export const AFFINE_FLAGS = {
enable_ai: { enable_ai: {
@@ -20,15 +20,16 @@ const appNames = {
beta: 'AFFiNE Beta', beta: 'AFFiNE Beta',
internal: 'AFFiNE Internal', internal: 'AFFiNE Internal',
} satisfies Record<Channel, string>; } satisfies Record<Channel, string>;
const appName = appNames[BUILD_CONFIG.appBuildType];
const links = [ const links = [
{ {
href: runtimeConfig.githubUrl, href: BUILD_CONFIG.githubUrl,
icon: <GithubIcon size={20} />, icon: <GithubIcon size={20} />,
label: 'Star AFFiNE on GitHub', label: 'Star AFFiNE on GitHub',
}, },
{ {
href: runtimeConfig.githubUrl, href: BUILD_CONFIG.githubUrl,
icon: <MailWarningIcon size={20} />, icon: <MailWarningIcon size={20} />,
label: 'Report an Issue', label: 'Report an Issue',
}, },
@@ -45,9 +46,6 @@ const links = [
]; ];
export function AboutAFFiNE() { export function AboutAFFiNE() {
const { appBuildType, appVersion, editorVersion } = runtimeConfig;
const appName = appNames[appBuildType];
return ( return (
<div className="flex flex-col h-full gap-3 py-5 px-6 w-full"> <div className="flex flex-col h-full gap-3 py-5 px-6 w-full">
<div className="flex items-center"> <div className="flex items-center">
@@ -80,8 +78,8 @@ export function AboutAFFiNE() {
</div> </div>
</div> </div>
<div className="space-y-3 text-sm font-normal text-gray-500"> <div className="space-y-3 text-sm font-normal text-gray-500">
<div>{`App Version: ${appName} ${appVersion}`}</div> <div>{`App Version: ${appName} ${BUILD_CONFIG.appVersion}`}</div>
<div>{`Editor Version: ${editorVersion}`}</div> <div>{`Editor Version: ${BUILD_CONFIG.editorVersion}`}</div>
</div> </div>
</div> </div>
); );
@@ -55,8 +55,8 @@ function main() {
], ],
}); });
setTags({ setTags({
appVersion: runtimeConfig.appVersion, appVersion: BUILD_CONFIG.appVersion,
editorVersion: runtimeConfig.editorVersion, editorVersion: BUILD_CONFIG.editorVersion,
}); });
apis?.ui.handleNetworkChange(navigator.onLine); apis?.ui.handleNetworkChange(navigator.onLine);
+2 -2
View File
@@ -36,8 +36,8 @@ function main() {
], ],
}); });
setTags({ setTags({
appVersion: runtimeConfig.appVersion, appVersion: BUILD_CONFIG.appVersion,
editorVersion: runtimeConfig.editorVersion, editorVersion: BUILD_CONFIG.editorVersion,
}); });
} }
performanceMainLogger.info('setup done'); performanceMainLogger.info('setup done');
@@ -112,21 +112,19 @@ const DetailPageImpl = () => {
// provide image proxy endpoint to blocksuite // provide image proxy endpoint to blocksuite
editorHost?.std.clipboard.use( editorHost?.std.clipboard.use(
customImageProxyMiddleware(runtimeConfig.imageProxyUrl) customImageProxyMiddleware(BUILD_CONFIG.imageProxyUrl)
); );
ImageBlockService.setImageProxyURL(runtimeConfig.imageProxyUrl); ImageBlockService.setImageProxyURL(BUILD_CONFIG.imageProxyUrl);
// provide link preview endpoint to blocksuite // provide link preview endpoint to blocksuite
BookmarkBlockService.setLinkPreviewEndpoint(runtimeConfig.linkPreviewUrl); BookmarkBlockService.setLinkPreviewEndpoint(BUILD_CONFIG.linkPreviewUrl);
EmbedGithubBlockService.setLinkPreviewEndpoint( EmbedGithubBlockService.setLinkPreviewEndpoint(
runtimeConfig.linkPreviewUrl BUILD_CONFIG.linkPreviewUrl
); );
EmbedYoutubeBlockService.setLinkPreviewEndpoint( EmbedYoutubeBlockService.setLinkPreviewEndpoint(
runtimeConfig.linkPreviewUrl BUILD_CONFIG.linkPreviewUrl
);
EmbedLoomBlockService.setLinkPreviewEndpoint(
runtimeConfig.linkPreviewUrl
); );
EmbedLoomBlockService.setLinkPreviewEndpoint(BUILD_CONFIG.linkPreviewUrl);
// provide page mode and updated date to blocksuite // provide page mode and updated date to blocksuite
const refNodeService = editorHost?.std.getOptional(RefNodeSlotsProvider); const refNodeService = editorHost?.std.getOptional(RefNodeSlotsProvider);
@@ -28,7 +28,7 @@ export const Component = () => {
}} }}
> >
<ExplorerFavorites /> <ExplorerFavorites />
{runtimeConfig.enableOrganize && <ExplorerOrganize />} <ExplorerOrganize />
<ExplorerMigrationFavorites /> <ExplorerMigrationFavorites />
<ExplorerCollections /> <ExplorerCollections />
<ExplorerTags /> <ExplorerTags />
@@ -3,19 +3,17 @@ import { useI18n } from '@affine/i18n';
import { SettingGroup } from '../group'; import { SettingGroup } from '../group';
import { RowLayout } from '../row.layout'; import { RowLayout } from '../row.layout';
const { appVersion, editorVersion } = runtimeConfig;
export const AboutGroup = () => { export const AboutGroup = () => {
const t = useI18n(); const t = useI18n();
return ( return (
<SettingGroup title={t['com.affine.mobile.setting.about.title']()}> <SettingGroup title={t['com.affine.mobile.setting.about.title']()}>
<RowLayout label={t['com.affine.mobile.setting.about.appVersion']()}> <RowLayout label={t['com.affine.mobile.setting.about.appVersion']()}>
{appVersion} {BUILD_CONFIG.appVersion}
</RowLayout> </RowLayout>
<RowLayout label={t['com.affine.mobile.setting.about.editorVersion']()}> <RowLayout label={t['com.affine.mobile.setting.about.editorVersion']()}>
{editorVersion} {BUILD_CONFIG.editorVersion}
</RowLayout> </RowLayout>
</SettingGroup> </SettingGroup>
); );
+2 -2
View File
@@ -43,8 +43,8 @@ function main() {
], ],
}); });
setTags({ setTags({
appVersion: runtimeConfig.appVersion, appVersion: BUILD_CONFIG.appVersion,
editorVersion: runtimeConfig.editorVersion, editorVersion: BUILD_CONFIG.editorVersion,
}); });
} }
performanceMainLogger.info('setup done'); performanceMainLogger.info('setup done');
@@ -15,7 +15,7 @@ export const AffineOtherPageLayout = ({
const t = useI18n(); const t = useI18n();
const openDownloadLink = useCallback(() => { const openDownloadLink = useCallback(() => {
open(runtimeConfig.downloadUrl, '_blank'); open(BUILD_CONFIG.downloadUrl, '_blank');
}, []); }, []);
return ( return (
@@ -46,7 +46,7 @@ export async function createFirstAppData(workspacesService: WorkspacesService) {
return; return;
} }
localStorage.setItem('is-first-open', 'false'); localStorage.setItem('is-first-open', 'false');
if (runtimeConfig.enablePreloading) { if (BUILD_CONFIG.enablePreloading) {
const { meta, defaultDocId } = await buildShowcaseWorkspace( const { meta, defaultDocId } = await buildShowcaseWorkspace(
workspacesService, workspacesService,
WorkspaceFlavour.LOCAL, WorkspaceFlavour.LOCAL,
@@ -23,7 +23,7 @@ export function registerAffineHelpCommands({
label: t['com.affine.cmdk.affine.whats-new'](), label: t['com.affine.cmdk.affine.whats-new'](),
run() { run() {
track.$.cmdk.help.openChangelog(); track.$.cmdk.help.openChangelog();
popupWindow(runtimeConfig.changelogUrl); popupWindow(BUILD_CONFIG.changelogUrl);
}, },
}) })
); );
@@ -50,7 +50,7 @@ function OAuthProvider({ provider }: { provider: OAuthProviderType }) {
const onClick = useCallback(() => { const onClick = useCallback(() => {
let oauthUrl = let oauthUrl =
(environment.isElectron ? runtimeConfig.serverUrlPrefix : '') + (environment.isElectron ? BUILD_CONFIG.serverUrlPrefix : '') +
`/oauth/login?provider=${provider}`; `/oauth/login?provider=${provider}`;
if (environment.isElectron) { if (environment.isElectron) {
@@ -48,7 +48,7 @@ interface NameWorkspaceContentProps extends ConfirmModalProps {
) => void; ) => void;
} }
const shouldEnableCloud = !runtimeConfig.allowLocalWorkspace; const shouldEnableCloud = !BUILD_CONFIG.allowLocalWorkspace;
const NameWorkspaceContent = ({ const NameWorkspaceContent = ({
loading, loading,
@@ -159,7 +159,7 @@ const NameWorkspaceContent = ({
{shouldEnableCloud ? ( {shouldEnableCloud ? (
<a <a
className={styles.cloudTips} className={styles.cloudTips}
href={runtimeConfig.downloadUrl} href={BUILD_CONFIG.downloadUrl}
target="_blank" target="_blank"
rel="noreferrer" rel="noreferrer"
> >
@@ -229,7 +229,7 @@ export const CreateWorkspaceModal = ({
// this will be the last step for web for now // this will be the last step for web for now
// fix me later // fix me later
if (runtimeConfig.enablePreloading) { if (BUILD_CONFIG.enablePreloading) {
const { meta, defaultDocId } = await buildShowcaseWorkspace( const { meta, defaultDocId } = await buildShowcaseWorkspace(
workspacesService, workspacesService,
workspaceFlavour, workspaceFlavour,
@@ -24,7 +24,7 @@ export const IssueFeedbackModal = () => {
onOpenChange={setOpen} onOpenChange={setOpen}
description={t['com.affine.issue-feedback.description']()} description={t['com.affine.issue-feedback.description']()}
cancelText={t['com.affine.issue-feedback.cancel']()} cancelText={t['com.affine.issue-feedback.cancel']()}
to={`${runtimeConfig.githubUrl}/issues/new/choose`} to={`${BUILD_CONFIG.githubUrl}/issues/new/choose`}
confirmText={t['com.affine.issue-feedback.confirm']()} confirmText={t['com.affine.issue-feedback.confirm']()}
confirmButtonOptions={{ confirmButtonOptions={{
variant: 'primary', variant: 'primary',
@@ -21,7 +21,7 @@ export const AboutAffine = () => {
const t = useI18n(); const t = useI18n();
const { appSettings, updateSettings } = useAppSettingHelper(); const { appSettings, updateSettings } = useAppSettingHelper();
const { toggleAutoCheck, toggleAutoDownload } = useAppUpdater(); const { toggleAutoCheck, toggleAutoDownload } = useAppUpdater();
const channel = runtimeConfig.appBuildType; const channel = BUILD_CONFIG.appBuildType;
const appIcon = appIconMap[channel]; const appIcon = appIconMap[channel];
const appName = appNames[channel]; const appName = appNames[channel];
@@ -63,14 +63,14 @@ export const AboutAffine = () => {
<SettingWrapper title={t['com.affine.aboutAFFiNE.version.title']()}> <SettingWrapper title={t['com.affine.aboutAFFiNE.version.title']()}>
<SettingRow <SettingRow
name={appName} name={appName}
desc={runtimeConfig.appVersion} desc={BUILD_CONFIG.appVersion}
className={styles.appImageRow} className={styles.appImageRow}
> >
<img src={appIcon} alt={appName} width={56} height={56} /> <img src={appIcon} alt={appName} width={56} height={56} />
</SettingRow> </SettingRow>
<SettingRow <SettingRow
name={t['com.affine.aboutAFFiNE.version.editor.title']()} name={t['com.affine.aboutAFFiNE.version.editor.title']()}
desc={runtimeConfig.editorVersion} desc={BUILD_CONFIG.editorVersion}
/> />
{environment.isElectron ? ( {environment.isElectron ? (
<> <>
@@ -100,7 +100,7 @@ export const AboutAffine = () => {
desc={t['com.affine.aboutAFFiNE.changelog.description']()} desc={t['com.affine.aboutAFFiNE.changelog.description']()}
style={{ cursor: 'pointer' }} style={{ cursor: 'pointer' }}
onClick={() => { onClick={() => {
popupWindow(runtimeConfig.changelogUrl); popupWindow(BUILD_CONFIG.changelogUrl);
}} }}
> >
<ArrowRightSmallIcon /> <ArrowRightSmallIcon />
@@ -98,7 +98,7 @@ export const AppearanceSettings = () => {
/> />
</SettingRow> </SettingRow>
) : null} ) : null}
{runtimeConfig.enableNewSettingUnstableApi && environment.isElectron ? ( {BUILD_CONFIG.enableNewSettingUnstableApi && environment.isElectron ? (
<SettingRow <SettingRow
name={t['com.affine.appearanceSettings.windowFrame.title']()} name={t['com.affine.appearanceSettings.windowFrame.title']()}
desc={t['com.affine.appearanceSettings.windowFrame.description']()} desc={t['com.affine.appearanceSettings.windowFrame.description']()}
@@ -118,11 +118,11 @@ export const AppearanceSettings = () => {
/> />
</SettingRow> </SettingRow>
) : null} ) : null}
{runtimeConfig.enableThemeEditor ? <ThemeEditorSetting /> : null} {BUILD_CONFIG.enableThemeEditor ? <ThemeEditorSetting /> : null}
</SettingWrapper> </SettingWrapper>
{/* // TODO(@JimmFly): remove Page component when stable release */} {/* // TODO(@JimmFly): remove Page component when stable release */}
<Page /> <Page />
{runtimeConfig.enableNewSettingUnstableApi ? ( {BUILD_CONFIG.enableNewSettingUnstableApi ? (
<SettingWrapper title={t['com.affine.appearanceSettings.date.title']()}> <SettingWrapper title={t['com.affine.appearanceSettings.date.title']()}>
<SettingRow <SettingRow
name={t['com.affine.appearanceSettings.dateFormat.title']()} name={t['com.affine.appearanceSettings.dateFormat.title']()}
@@ -107,7 +107,7 @@ export const useGeneralSettingList = (): GeneralSettingList => {
} }
} }
if (runtimeConfig.enableExperimentalFeature) { if (BUILD_CONFIG.enableExperimentalFeature) {
settings.push({ settings.push({
key: 'experimental-features', key: 'experimental-features',
title: t['com.affine.settings.workspace.experimental-features'](), title: t['com.affine.settings.workspace.experimental-features'](),
@@ -24,7 +24,7 @@ export const StarAFFiNEModal = () => {
onOpenChange={setOpen} onOpenChange={setOpen}
description={t['com.affine.star-affine.description']()} description={t['com.affine.star-affine.description']()}
cancelText={t['com.affine.star-affine.cancel']()} cancelText={t['com.affine.star-affine.cancel']()}
to={runtimeConfig.githubUrl} to={BUILD_CONFIG.githubUrl}
confirmButtonOptions={{ confirmButtonOptions={{
variant: 'primary', variant: 'primary',
}} }}
@@ -89,22 +89,22 @@ const BlockSuiteEditorImpl = ({
// provide image proxy endpoint to blocksuite // provide image proxy endpoint to blocksuite
editor.host?.std.clipboard.use( editor.host?.std.clipboard.use(
customImageProxyMiddleware(runtimeConfig.imageProxyUrl) customImageProxyMiddleware(BUILD_CONFIG.imageProxyUrl)
); );
ImageBlockService.setImageProxyURL(runtimeConfig.imageProxyUrl); ImageBlockService.setImageProxyURL(BUILD_CONFIG.imageProxyUrl);
// provide link preview endpoint to blocksuite // provide link preview endpoint to blocksuite
BookmarkBlockService.setLinkPreviewEndpoint( BookmarkBlockService.setLinkPreviewEndpoint(
runtimeConfig.linkPreviewUrl BUILD_CONFIG.linkPreviewUrl
); );
EmbedGithubBlockService.setLinkPreviewEndpoint( EmbedGithubBlockService.setLinkPreviewEndpoint(
runtimeConfig.linkPreviewUrl BUILD_CONFIG.linkPreviewUrl
); );
EmbedYoutubeBlockService.setLinkPreviewEndpoint( EmbedYoutubeBlockService.setLinkPreviewEndpoint(
runtimeConfig.linkPreviewUrl BUILD_CONFIG.linkPreviewUrl
); );
EmbedLoomBlockService.setLinkPreviewEndpoint( EmbedLoomBlockService.setLinkPreviewEndpoint(
runtimeConfig.linkPreviewUrl BUILD_CONFIG.linkPreviewUrl
); );
return editor.host?.updateComplete; return editor.host?.updateComplete;
@@ -2,7 +2,7 @@ import { AffineCanvasTextFonts, FontConfigExtension } from '@blocksuite/blocks';
export function getFontConfigExtension() { export function getFontConfigExtension() {
return FontConfigExtension( return FontConfigExtension(
runtimeConfig.isSelfHosted BUILD_CONFIG.isSelfHosted
? AffineCanvasTextFonts.map(font => ({ ? AffineCanvasTextFonts.map(font => ({
...font, ...font,
// self-hosted fonts are served from /assets // self-hosted fonts are served from /assets
@@ -304,16 +304,13 @@ export const PageHeaderMenuButton = ({
)} )}
<MenuSeparator /> <MenuSeparator />
<MenuItem
{runtimeConfig.enableInfoModal && ( prefixIcon={<InformationIcon />}
<MenuItem data-testid="editor-option-menu-info"
prefixIcon={<InformationIcon />} onSelect={openInfoModal}
data-testid="editor-option-menu-info" >
onSelect={openInfoModal} {t['com.affine.page-properties.page-info.view']()}
> </MenuItem>
{t['com.affine.page-properties.page-info.view']()}
</MenuItem>
)}
{currentMode === 'page' ? ( {currentMode === 'page' ? (
<MenuItem <MenuItem
prefixIcon={<TocIcon />} prefixIcon={<TocIcon />}
@@ -173,11 +173,9 @@ export const PageOperationCell = ({
? t['com.affine.favoritePageOperation.remove']() ? t['com.affine.favoritePageOperation.remove']()
: t['com.affine.favoritePageOperation.add']()} : t['com.affine.favoritePageOperation.add']()}
</MenuItem> </MenuItem>
{runtimeConfig.enableInfoModal ? ( <MenuItem onClick={onOpenInfoModal} prefixIcon={<InformationIcon />}>
<MenuItem onClick={onOpenInfoModal} prefixIcon={<InformationIcon />}> {t['com.affine.page-properties.page-info.view']()}
{t['com.affine.page-properties.page-info.view']()} </MenuItem>
</MenuItem>
) : null}
<MenuItem onClick={onOpenInNewTab} prefixIcon={<OpenInNewIcon />}> <MenuItem onClick={onOpenInNewTab} prefixIcon={<OpenInNewIcon />}>
{t['com.affine.workbench.tab.page-menu-open']()} {t['com.affine.workbench.tab.page-menu-open']()}
@@ -77,7 +77,7 @@ export const HelpIsland = () => {
<StyledIconWrapper <StyledIconWrapper
data-testid="right-bottom-change-log-icon" data-testid="right-bottom-change-log-icon"
onClick={() => { onClick={() => {
popupWindow(runtimeConfig.changelogUrl); popupWindow(BUILD_CONFIG.changelogUrl);
}} }}
> >
<NewIcon /> <NewIcon />
@@ -176,7 +176,7 @@ export const RootAppSidebar = (): ReactElement => {
</SidebarContainer> </SidebarContainer>
<SidebarScrollableContainer> <SidebarScrollableContainer>
<ExplorerFavorites /> <ExplorerFavorites />
{runtimeConfig.enableOrganize && <ExplorerOrganize />} <ExplorerOrganize />
<ExplorerMigrationFavorites /> <ExplorerMigrationFavorites />
<ExplorerCollections /> <ExplorerCollections />
<ExplorerTags /> <ExplorerTags />
@@ -36,7 +36,7 @@ export const AddWorkspace = ({
className={styles.ItemContainer} className={styles.ItemContainer}
> >
<div className={styles.ItemText}> <div className={styles.ItemText}>
{runtimeConfig.allowLocalWorkspace {BUILD_CONFIG.allowLocalWorkspace
? t['com.affine.workspaceList.addWorkspace.create']() ? t['com.affine.workspaceList.addWorkspace.create']()
: t['com.affine.workspaceList.addWorkspace.create-cloud']()} : t['com.affine.workspaceList.addWorkspace.create-cloud']()}
</div> </div>
@@ -88,7 +88,7 @@ const UserWithWorkspaceListInner = ({
}, [setOpenSignIn]); }, [setOpenSignIn]);
const onNewWorkspace = useCallback(() => { const onNewWorkspace = useCallback(() => {
if (!isAuthenticated && !runtimeConfig.allowLocalWorkspace) { if (!isAuthenticated && !BUILD_CONFIG.allowLocalWorkspace) {
return openSignInModal(); return openSignInModal();
} }
track.$.navigationPanel.workspaceList.createWorkspace(); track.$.navigationPanel.workspaceList.createWorkspace();
@@ -95,9 +95,7 @@ export function useRegisterBlocksuiteEditorCommands(editor: Editor) {
registerAffineCommand({ registerAffineCommand({
id: `editor:${mode}-view-info`, id: `editor:${mode}-view-info`,
preconditionStrategy: () => preconditionStrategy: () =>
PreconditionStrategy.InPaperOrEdgeless && PreconditionStrategy.InPaperOrEdgeless && !trash,
!trash &&
runtimeConfig.enableInfoModal,
category: `editor:${mode}`, category: `editor:${mode}`,
icon: mode === 'page' ? <PageIcon /> : <EdgelessIcon />, icon: mode === 'page' ? <PageIcon /> : <EdgelessIcon />,
label: t['com.affine.page-properties.page-info.view'](), label: t['com.affine.page-properties.page-info.view'](),
@@ -177,7 +177,7 @@ export const useAppUpdater = () => {
const openChangelog = useAsyncCallback(async () => { const openChangelog = useAsyncCallback(async () => {
track.$.navigationPanel.bottomButtons.openChangelog(); track.$.navigationPanel.bottomButtons.openChangelog();
popupWindow(runtimeConfig.changelogUrl); popupWindow(BUILD_CONFIG.changelogUrl);
await setChangelogUnread(true); await setChangelogUnread(true);
}, [setChangelogUnread]); }, [setChangelogUnread]);
@@ -32,10 +32,10 @@ function createMixpanel() {
const wrapped = { const wrapped = {
init() { init() {
mixpanel.register({ mixpanel.register({
appVersion: runtimeConfig.appVersion, appVersion: BUILD_CONFIG.appVersion,
environment: runtimeConfig.appBuildType, environment: BUILD_CONFIG.appBuildType,
editorVersion: runtimeConfig.editorVersion, editorVersion: BUILD_CONFIG.editorVersion,
isSelfHosted: Boolean(runtimeConfig.isSelfHosted), isSelfHosted: Boolean(BUILD_CONFIG.isSelfHosted),
isDesktop: environment.isElectron, isDesktop: environment.isElectron,
}); });
}, },
@@ -6,7 +6,7 @@ import { BackendError, NetworkError } from '../error';
export function getAffineCloudBaseUrl(): string { export function getAffineCloudBaseUrl(): string {
if (environment.isElectron) { if (environment.isElectron) {
return runtimeConfig.serverUrlPrefix; return BUILD_CONFIG.serverUrlPrefix;
} }
const { protocol, hostname, port } = window.location; const { protocol, hostname, port } = window.location;
return `${protocol}//${hostname}${port ? `:${port}` : ''}`; return `${protocol}//${hostname}${port ? `:${port}` : ''}`;
@@ -35,7 +35,7 @@ interface NameWorkspaceContentProps extends ConfirmModalProps {
) => void; ) => void;
} }
const shouldEnableCloud = !runtimeConfig.allowLocalWorkspace; const shouldEnableCloud = !BUILD_CONFIG.allowLocalWorkspace;
const NameWorkspaceContent = ({ const NameWorkspaceContent = ({
loading, loading,
@@ -146,7 +146,7 @@ const NameWorkspaceContent = ({
{shouldEnableCloud ? ( {shouldEnableCloud ? (
<a <a
className={styles.cloudTips} className={styles.cloudTips}
href={runtimeConfig.downloadUrl} href={BUILD_CONFIG.downloadUrl}
target="_blank" target="_blank"
rel="noreferrer" rel="noreferrer"
> >
@@ -213,7 +213,7 @@ const CreateWorkspaceDialog = () => {
// this will be the last step for web for now // this will be the last step for web for now
// fix me later // fix me later
if (runtimeConfig.enablePreloading) { if (BUILD_CONFIG.enablePreloading) {
const { meta, defaultDocId } = await buildShowcaseWorkspace( const { meta, defaultDocId } = await buildShowcaseWorkspace(
workspacesService, workspacesService,
workspaceFlavour, workspaceFlavour,
@@ -154,21 +154,17 @@ export const useExplorerDocNodeOperations = (
/> />
), ),
}, },
...(runtimeConfig.enableInfoModal {
? [ index: 50,
{ view: (
index: 50, <MenuItem
view: ( prefixIcon={<InformationIcon />}
<MenuItem onClick={handleOpenInfoModal}
prefixIcon={<InformationIcon />} >
onClick={handleOpenInfoModal} {t['com.affine.page-properties.page-info.view']()}
> </MenuItem>
{t['com.affine.page-properties.page-info.view']()} ),
</MenuItem> },
),
},
]
: []),
{ {
index: 99, index: 99,
view: ( view: (
@@ -11,7 +11,7 @@ export const useCustomTheme = (target: HTMLElement) => {
const { resolvedTheme } = useTheme(); const { resolvedTheme } = useTheme();
useEffect(() => { useEffect(() => {
if (!runtimeConfig.enableThemeEditor) return; if (!BUILD_CONFIG.enableThemeEditor) return;
if (_provided) return; if (_provided) return;
_provided = true; _provided = true;
@@ -36,7 +36,7 @@ export class UserDBDocServer implements DocServer {
await this.socket.emitWithAck('space:join', { await this.socket.emitWithAck('space:join', {
spaceType: 'userspace', spaceType: 'userspace',
spaceId: this.userId, spaceId: this.userId,
clientVersion: runtimeConfig.appVersion, clientVersion: BUILD_CONFIG.appVersion,
}); });
} }
@@ -166,7 +166,7 @@ export class CloudAwarenessConnection implements AwarenessConnection {
spaceType: 'workspace', spaceType: 'workspace',
spaceId: this.workspaceId, spaceId: this.workspaceId,
docId: this.workspaceId, docId: this.workspaceId,
clientVersion: runtimeConfig.appVersion, clientVersion: BUILD_CONFIG.appVersion,
}, },
(res: any) => { (res: any) => {
logger.debug('awareness handshake finished', res); logger.debug('awareness handshake finished', res);
@@ -37,7 +37,7 @@ export class CloudDocEngineServer implements DocServer {
await this.socket.emitWithAck('space:join', { await this.socket.emitWithAck('space:join', {
spaceType: 'workspace', spaceType: 'workspace',
spaceId: this.workspaceId, spaceId: this.workspaceId,
clientVersion: runtimeConfig.appVersion, clientVersion: BUILD_CONFIG.appVersion,
}); });
} }
@@ -139,7 +139,7 @@ export function NormalPageHeader({ page, workspace }: PageHeaderProps) {
{hideCollect ? null : ( {hideCollect ? null : (
<> <>
<FavoriteButton pageId={page?.id} /> <FavoriteButton pageId={page?.id} />
{runtimeConfig.enableInfoModal ? <InfoButton /> : null} <InfoButton />
</> </>
)} )}
<PageHeaderMenuButton <PageHeaderMenuButton
+2 -2
View File
@@ -1,8 +1,8 @@
export function popupWindow(target: string) { export function popupWindow(target: string) {
const url = new URL(runtimeConfig.serverUrlPrefix + '/redirect-proxy'); const url = new URL(BUILD_CONFIG.serverUrlPrefix + '/redirect-proxy');
target = /^https?:\/\//.test(target) target = /^https?:\/\//.test(target)
? target ? target
: runtimeConfig.serverUrlPrefix + target; : BUILD_CONFIG.serverUrlPrefix + target;
url.searchParams.set('redirect_uri', target); url.searchParams.set('redirect_uri', target);
return window.open(url, '_blank', `noreferrer noopener`); return window.open(url, '_blank', `noreferrer noopener`);
} }
+1 -1
View File
@@ -8,7 +8,7 @@ interface AppUrlOptions {
export function buildAppUrl(path: string, opts: AppUrlOptions = {}) { export function buildAppUrl(path: string, opts: AppUrlOptions = {}) {
// TODO(@EYHN): should use server base url // TODO(@EYHN): should use server base url
const webBase = runtimeConfig.serverUrlPrefix; const webBase = BUILD_CONFIG.serverUrlPrefix;
// TODO(@pengx17): how could we know the corresponding app schema in web environment // TODO(@pengx17): how could we know the corresponding app schema in web environment
if (opts.desktop && appInfo?.schema) { if (opts.desktop && appInfo?.schema) {
const urlCtor = new URL(path, webBase); const urlCtor = new URL(path, webBase);
+1 -1
View File
@@ -11,7 +11,7 @@ setupGlobal();
export function getBaseUrl(): string { export function getBaseUrl(): string {
if (environment.isElectron) { if (environment.isElectron) {
return runtimeConfig.serverUrlPrefix; return BUILD_CONFIG.serverUrlPrefix;
} }
if (typeof window === 'undefined') { if (typeof window === 'undefined') {
// is nodejs // is nodejs
+6 -8
View File
@@ -1,14 +1,12 @@
import { getRuntimeConfig } from '@affine/cli/src/webpack/runtime-config'; import { getRuntimeConfig } from '@affine/cli/src/webpack/runtime-config';
import { setupGlobal } from '@affine/env/global'; import { setupGlobal } from '@affine/env/global';
process.env.RUNTIME_CONFIG = JSON.stringify( globalThis.BUILD_CONFIG = getRuntimeConfig({
getRuntimeConfig({ distribution: 'web',
distribution: 'web', mode: 'development',
mode: 'development', channel: 'canary',
channel: 'canary', static: false,
static: false, });
})
);
if (typeof window !== 'undefined') { if (typeof window !== 'undefined') {
window.location.search = '?prefixUrl=http://127.0.0.1:3010/'; window.location.search = '?prefixUrl=http://127.0.0.1:3010/';
+2 -2
View File
@@ -1,4 +1,4 @@
import type { Environment, RuntimeConfig } from '@affine/env/global'; import type { BUILD_CONFIG_TYPE, Environment } from '@affine/env/global';
declare global { declare global {
// eslint-disable-next-line no-var // eslint-disable-next-line no-var
@@ -8,7 +8,7 @@ declare global {
// eslint-disable-next-line no-var // eslint-disable-next-line no-var
var environment: Environment; var environment: Environment;
// eslint-disable-next-line no-var // eslint-disable-next-line no-var
var runtimeConfig: RuntimeConfig; var BUILD_CONFIG: BUILD_CONFIG_TYPE;
// eslint-disable-next-line no-var // eslint-disable-next-line no-var
var $AFFINE_SETUP: boolean | undefined; var $AFFINE_SETUP: boolean | undefined;
/** /**
+9 -5
View File
@@ -1,7 +1,7 @@
import { join } from 'node:path'; import { join } from 'node:path';
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
import type { RuntimeConfig } from '@affine/env/global'; import type { BUILD_CONFIG_TYPE } from '@affine/env/global';
import { PerfseePlugin } from '@perfsee/webpack'; import { PerfseePlugin } from '@perfsee/webpack';
import ReactRefreshWebpackPlugin from '@pmmmwh/react-refresh-webpack-plugin'; import ReactRefreshWebpackPlugin from '@pmmmwh/react-refresh-webpack-plugin';
import { sentryWebpackPlugin } from '@sentry/webpack-plugin'; import { sentryWebpackPlugin } from '@sentry/webpack-plugin';
@@ -89,8 +89,8 @@ export const getPublicPath = (buildFlags: BuildFlags) => {
export const createConfiguration: ( export const createConfiguration: (
cwd: string, cwd: string,
buildFlags: BuildFlags, buildFlags: BuildFlags,
runtimeConfig: RuntimeConfig buildConfig: BUILD_CONFIG_TYPE
) => webpack.Configuration = (cwd, buildFlags, runtimeConfig) => { ) => webpack.Configuration = (cwd, buildFlags, buildConfig) => {
const blocksuiteBaseDir = buildFlags.localBlockSuite; const blocksuiteBaseDir = buildFlags.localBlockSuite;
const config = { const config = {
name: 'affine', name: 'affine',
@@ -350,8 +350,12 @@ export const createConfiguration: (
process.env.MIXPANEL_TOKEN process.env.MIXPANEL_TOKEN
), ),
'process.env.DEBUG_JOTAI': JSON.stringify(process.env.DEBUG_JOTAI), 'process.env.DEBUG_JOTAI': JSON.stringify(process.env.DEBUG_JOTAI),
'process.env.RUNTIME_CONFIG': JSON.stringify( ...Object.entries(buildConfig).reduce(
JSON.stringify(runtimeConfig) (def, [k, v]) => {
def[`BUILD_CONFIG.${k}`] = JSON.stringify(v);
return def;
},
{} as Record<string, string>
), ),
}), }),
buildFlags.distribution === 'admin' buildFlags.distribution === 'admin'
+4 -12
View File
@@ -1,10 +1,10 @@
import type { RuntimeConfig } from '@affine/env/global'; import type { BUILD_CONFIG_TYPE } from '@affine/env/global';
import packageJson from '../../package.json' assert { type: 'json' }; import packageJson from '../../package.json' assert { type: 'json' };
import type { BuildFlags } from '../config'; import type { BuildFlags } from '../config';
export function getRuntimeConfig(buildFlags: BuildFlags): RuntimeConfig { export function getRuntimeConfig(buildFlags: BuildFlags): BUILD_CONFIG_TYPE {
const buildPreset: Record<BuildFlags['channel'], RuntimeConfig> = { const buildPreset: Record<BuildFlags['channel'], BUILD_CONFIG_TYPE> = {
get stable() { get stable() {
return { return {
distribution: buildFlags.distribution, distribution: buildFlags.distribution,
@@ -21,13 +21,10 @@ export function getRuntimeConfig(buildFlags: BuildFlags): RuntimeConfig {
enableExperimentalFeature: true, enableExperimentalFeature: true,
allowLocalWorkspace: allowLocalWorkspace:
buildFlags.distribution === 'desktop' ? true : false, buildFlags.distribution === 'desktop' ? true : false,
enableOrganize: true, enableThemeEditor: false,
enableInfoModal: true,
// CAUTION(@forehalo): product not ready, do not enable it // CAUTION(@forehalo): product not ready, do not enable it
enableNewSettingUnstableApi: false, enableNewSettingUnstableApi: false,
enableEnhanceShareMode: false,
enableThemeEditor: false,
}; };
}, },
get beta() { get beta() {
@@ -53,8 +50,6 @@ export function getRuntimeConfig(buildFlags: BuildFlags): RuntimeConfig {
appBuildType: 'canary' as const, appBuildType: 'canary' as const,
serverUrlPrefix: 'https://affine.fail', serverUrlPrefix: 'https://affine.fail',
changelogUrl: 'https://github.com/toeverything/AFFiNE/releases', changelogUrl: 'https://github.com/toeverything/AFFiNE/releases',
enableInfoModal: true,
enableOrganize: true,
enableThemeEditor: true, enableThemeEditor: true,
}; };
}, },
@@ -76,9 +71,6 @@ export function getRuntimeConfig(buildFlags: BuildFlags): RuntimeConfig {
enableNewSettingUnstableApi: process.env.ENABLE_NEW_SETTING_UNSTABLE_API enableNewSettingUnstableApi: process.env.ENABLE_NEW_SETTING_UNSTABLE_API
? process.env.ENABLE_NEW_SETTING_UNSTABLE_API === 'true' ? process.env.ENABLE_NEW_SETTING_UNSTABLE_API === 'true'
: currentBuildPreset.enableNewSettingUnstableApi, : currentBuildPreset.enableNewSettingUnstableApi,
enableEnhanceShareMode: process.env.ENABLE_ENHANCE_SHARE_MODE
? process.env.ENABLE_ENHANCE_SHARE_MODE === 'true'
: currentBuildPreset.enableEnhanceShareMode,
allowLocalWorkspace: process.env.ALLOW_LOCAL_WORKSPACE allowLocalWorkspace: process.env.ALLOW_LOCAL_WORKSPACE
? process.env.ALLOW_LOCAL_WORKSPACE === 'true' ? process.env.ALLOW_LOCAL_WORKSPACE === 'true'
: buildFlags.mode === 'development' : buildFlags.mode === 'development'