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

Reroute "open in editor" link in app preview #3207

Merged
merged 5 commits into from
Feb 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
7 changes: 2 additions & 5 deletions packages/toolpad-app/src/exports/editor.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
import * as React from 'react';
import ToolpadEditor from '../toolpad/Toolpad';
import { ToolpadEditor } from '../toolpad/Toolpad';

export default function ToolpadEditorVite({ basename }: { basename: string }) {
return <ToolpadEditor basename={`${basename}/editor`} appUrl={basename} />;
}
export default ToolpadEditor;
38 changes: 26 additions & 12 deletions packages/toolpad-app/src/runtime/PreviewHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
popoverClasses,
} from '@mui/material';
import EditIcon from '@mui/icons-material/Edit';
import { useMatch } from 'react-router-dom';
import { Link, useMatch } from 'react-router-dom';
import ContentCopyIcon from '@mui/icons-material/ContentCopy';
import { useNonNullableContext } from '@mui/toolpad-utils/react';
import { PREVIEW_HEADER_HEIGHT } from './constants';
Expand Down Expand Up @@ -106,7 +106,10 @@ function CodeView({ children }: CodeViewProps) {
);
}

function OpenInEditorButton({ children = 'Open in editor', ...props }: ButtonProps) {
function OpenInEditorButton<C extends React.ElementType>({
children = 'Open in editor',
...props
}: ButtonProps<C>) {
return (
<Button color="inherit" size="small" startIcon={<EditIcon />} {...props}>
{children}
Expand Down Expand Up @@ -182,6 +185,26 @@ export default function PreviewHeader({ basename }: PreviewHeaderProps) {

const appContext = useNonNullableContext(AppHostContext);

let action: React.ReactNode = null;

if (process.env.EXPERIMENTAL_INLINE_CANVAS) {
action = (
<OpenInEditorButton
component={Link}
to={activePage ? `/editor/app/pages/${activePage}` : '/editor/app'}
/>
);
} else if (appContext) {
action = appContext.isCustomServer ? (
<CustomServerInstructions basename={basename} />
) : (
<OpenInEditorButton
component="a"
href={activePage ? `/_toolpad/app/pages/${activePage}` : '/_toolpad/app'}
/>
);
}

return appContext ? (
<Box
sx={{
Expand All @@ -196,16 +219,7 @@ export default function PreviewHeader({ basename }: PreviewHeaderProps) {
sx={{
borderRadius: 0,
}}
action={
appContext.isCustomServer ? (
<CustomServerInstructions basename={basename} />
) : (
<OpenInEditorButton
component="a"
href={activePage ? `/_toolpad/app/pages/${activePage}` : '/_toolpad/app'}
/>
)
}
action={action}
>
<Typography variant="body2">
This is a preview version of the application, not suitable for production.
Expand Down
87 changes: 51 additions & 36 deletions packages/toolpad-app/src/runtime/ToolpadApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,7 @@ import {
JsExpressionAttrValue,
ComponentConfig,
} from '@mui/toolpad-core';
import {
createGlobalState,
useAssertedContext,
useNonNullableContext,
} from '@mui/toolpad-utils/react';
import { useAssertedContext, useNonNullableContext } from '@mui/toolpad-utils/react';
import { mapProperties, mapValues } from '@mui/toolpad-utils/collections';
import { set as setObjectPath } from 'lodash-es';
import { QueryClientProvider, useMutation } from '@tanstack/react-query';
Expand Down Expand Up @@ -97,14 +93,12 @@ import { AuthContext, useAuth, AuthSession } from './useAuth';
import { RequireAuthorization } from './auth';
import SignInPage from './SignInPage';
import { AppHost, AppHostContext } from './AppHostContext';
import { componentsStore, pageComponentsStore } from './globalState';

const browserJsRuntime = getBrowserRuntime();

export type PageComponents = Partial<Record<string, React.ComponentType>>;

export const componentsStore = createGlobalState<ToolpadComponents>({});
export const pageComponentsStore = createGlobalState<PageComponents>({});

const Pre = styled('pre')(({ theme }) => ({
margin: 0,
fontFamily: theme.fontFamilyMonospaced,
Expand Down Expand Up @@ -1672,34 +1666,32 @@ export function ToolpadAppProvider({
return (
<RuntimeApiContext.Provider value={runtimeApi}>
<UseDataProviderContext.Provider value={useDataProvider}>
<AppThemeProvider dom={dom}>
<CssBaseline enableColorScheme />
{showPreviewHeader ? <PreviewHeader basename={basename} /> : null}
<AppRoot
ref={rootRef}
sx={{
paddingTop: showPreviewHeader ? `${PREVIEW_HEADER_HEIGHT}px` : 0,
}}
>
<ComponentsContextProvider value={components}>
<DomContext.Provider value={dom}>
<ErrorBoundary FallbackComponent={AppError}>
<ResetNodeErrorsKeyProvider value={resetNodeErrorsKey}>
<React.Suspense fallback={<AppLoading />}>
<QueryClientProvider client={queryClient}>
<AuthContext.Provider value={authContext}>{children}</AuthContext.Provider>
{showDevtools ? (
<ReactQueryDevtoolsProduction initialIsOpen={false} />
) : null}
</QueryClientProvider>
</React.Suspense>
</ResetNodeErrorsKeyProvider>
</ErrorBoundary>
</DomContext.Provider>
</ComponentsContextProvider>
<EditorOverlay ref={canvasHooks.overlayRef} id={HTML_ID_EDITOR_OVERLAY} />
</AppRoot>
</AppThemeProvider>
<QueryClientProvider client={queryClient}>
<ComponentsContextProvider value={components}>
<DomContext.Provider value={dom}>
<AuthContext.Provider value={authContext}>
<ResetNodeErrorsKeyProvider value={resetNodeErrorsKey}>
<AppThemeProvider dom={dom}>
<CssBaseline enableColorScheme />
{showPreviewHeader ? <PreviewHeader basename={basename} /> : null}
<AppRoot
ref={rootRef}
sx={{
paddingTop: showPreviewHeader ? `${PREVIEW_HEADER_HEIGHT}px` : 0,
}}
>
<ErrorBoundary FallbackComponent={AppError}>
<React.Suspense fallback={<AppLoading />}>{children}</React.Suspense>
</ErrorBoundary>
<EditorOverlay ref={canvasHooks.overlayRef} id={HTML_ID_EDITOR_OVERLAY} />
</AppRoot>
</AppThemeProvider>
</ResetNodeErrorsKeyProvider>
</AuthContext.Provider>
{showDevtools ? <ReactQueryDevtoolsProduction initialIsOpen={false} /> : null}
</DomContext.Provider>
</ComponentsContextProvider>
</QueryClientProvider>
</UseDataProviderContext.Provider>
</RuntimeApiContext.Provider>
);
Expand All @@ -1712,6 +1704,29 @@ export interface ToolpadAppProps {
apiUrl?: string;
}

export function ToolpadAppRoutes(props: ToolpadAppProps) {
return (
<Routes>
<Route
path="/"
element={
<ToolpadAppProvider {...props}>
<Outlet />
</ToolpadAppProvider>
}
>
<Route path="/signin" Component={SignInPage} />
<Route path="/" Component={PagesLayoutRoute}>
<Route path="/pages/:pageName" Component={PageRoute} />
<Route path="/pages" Component={DefaultPageRoute} />
<Route path="/" Component={DefaultPageRoute} />
<Route path="*" Component={PageNotFound} />
</Route>
</Route>
</Routes>
);
}

export default function ToolpadApp(props: ToolpadAppProps) {
return (
<BrowserRouter basename={props.basename}>
Expand Down
6 changes: 6 additions & 0 deletions packages/toolpad-app/src/runtime/globalState.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { ToolpadComponents } from '@mui/toolpad-core';
import { createGlobalState } from '@mui/toolpad-utils/react';
import { type PageComponents } from './ToolpadApp';

export const componentsStore = createGlobalState<ToolpadComponents>({});
export const pageComponentsStore = createGlobalState<PageComponents>({});
10 changes: 3 additions & 7 deletions packages/toolpad-app/src/runtime/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,9 @@ export function createRemoteFunction(functionFile: string, functionName: string)
};
}

export {
default as ToolpadApp,
RenderedPage,
componentsStore,
pageComponentsStore,
type ToolpadAppProps,
} from './ToolpadApp';
export { default as ToolpadApp, RenderedPage, type ToolpadAppProps } from './ToolpadApp';

export { componentsStore, pageComponentsStore } from './globalState';

export { AppHostContext, type AppHost } from './AppHostContext';

Expand Down
4 changes: 2 additions & 2 deletions packages/toolpad-app/src/server/appServerWorker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import invariant from 'invariant';
import type { Plugin } from 'vite';
import { createRpcClient } from '@mui/toolpad-utils/workerRpc';
import type * as appDom from '@mui/toolpad-core/appDom';
import { getAppHtmlContent, createViteConfig, getEditorHtmlContent } from './toolpadAppBuilder';
import { createViteConfig, getAppHtmlContent, getEditorHtmlContent } from './toolpadAppBuilder';
import type { RuntimeConfig } from '../types';
import type { ComponentEntry, PagesManifest } from './localMode';
import createRuntimeState from '../runtime/createRuntimeState';
Expand Down Expand Up @@ -46,7 +46,7 @@ function devServerPlugin({ config }: ToolpadAppDevServerParams): Plugin {
try {
const dom = await loadDom();

const template = req.url.startsWith('/editor')
const template = process.env.EXPERIMENTAL_INLINE_CANVAS
? getEditorHtmlContent()
: getAppHtmlContent();

Expand Down
14 changes: 11 additions & 3 deletions packages/toolpad-app/src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -399,9 +399,6 @@ export interface RunEditorOptions {
}

export async function runEditor(appUrl: string, options: RunEditorOptions = {}) {
// eslint-disable-next-line no-console
console.log(`${chalk.blue('info')} - starting Toolpad editor...`);

let appRootUrl;
try {
appRootUrl = await fetchAppUrl(appUrl);
Expand All @@ -416,6 +413,17 @@ export async function runEditor(appUrl: string, options: RunEditorOptions = {})
process.exit(1);
}

if (process.env.EXPERIMENTAL_INLINE_CANVAS) {
// eslint-disable-next-line no-console
console.log(
`${chalk.yellow('warn')} - The editor command is deprecated and will be removed in the future, please visit ${chalk.cyan(`${appRootUrl}/editor`)}`,
);
return;
}

// eslint-disable-next-line no-console
console.log(`${chalk.blue('info')} - starting Toolpad editor...`);

const app = express();

const editorBasename = '/_toolpad';
Expand Down
15 changes: 12 additions & 3 deletions packages/toolpad-app/src/server/toolpadAppBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -325,15 +325,24 @@ if (import.meta.hot) {
},
{
find: MAIN_ENTRY,
replacement: dev ? 'virtual:toolpad-files:dev.tsx' : 'virtual:toolpad-files:main.tsx',
// eslint-disable-next-line no-nested-ternary
replacement: process.env.EXPERIMENTAL_INLINE_CANVAS
? 'virtual:toolpad-files:main.tsx'
: dev
? 'virtual:toolpad-files:dev.tsx'
: 'virtual:toolpad-files:main.tsx',
},
{
find: EDITOR_ENTRY,
replacement: 'virtual:toolpad-files:editor.tsx',
},
{
find: '@mui/toolpad',
replacement: path.resolve(currentDirectory, '../exports'),
replacement: toolpadDevMode
? // load source
path.resolve(currentDirectory, '../../src/exports')
: // load compiled
path.resolve(currentDirectory, '../exports'),
},
],
},
Expand All @@ -349,7 +358,7 @@ if (import.meta.hot) {
appType: 'custom',
logLevel: 'info',
root: currentDirectory,
plugins: [virtualToolpadFiles, react(), toolpadVitePlugin(), ...plugins],
plugins: [toolpadVitePlugin(), virtualToolpadFiles, react(), ...plugins],
base,
define: {
'process.env.NODE_ENV': `'${mode}'`,
Expand Down
28 changes: 23 additions & 5 deletions packages/toolpad-app/src/toolpad/Toolpad.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ import AppProvider, { AppState, useAppStateContext } from './AppState';
import { FEATURE_FLAG_GLOBAL_FUNCTIONS } from '../constants';
import { ProjectProvider } from '../project';
import AppAuthorizationDialog from './AppEditor/AppAuthorizationEditor';
import { ToolpadAppRoutes } from '../runtime/ToolpadApp';
import { RuntimeState } from '../runtime';

const Centered = styled('div')({
height: '100%',
Expand Down Expand Up @@ -146,11 +148,11 @@ const queryClient = new QueryClient({
},
});

interface ToolpadEditorContentProps {
export interface ToolpadEditorRoutesProps {
appUrl: string;
}

function ToolpadEditorContent({ appUrl }: ToolpadEditorContentProps) {
export function ToolpadEditorRoutes({ appUrl }: ToolpadEditorRoutesProps) {
return (
<ThemeProvider>
{/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
Expand Down Expand Up @@ -180,15 +182,31 @@ function ToolpadEditorContent({ appUrl }: ToolpadEditorContentProps) {
);
}

export interface ToolpadProps {
export interface ToolpadEditorProps {
basename: string;
state: RuntimeState;
}

export function ToolpadEditor({ basename, state }: ToolpadEditorProps) {
return (
<BrowserRouter basename={basename}>
<Routes>
<Route path="/editor/*" element={<ToolpadEditorRoutes appUrl={basename} />} />
<Route path="/*" element={<ToolpadAppRoutes basename={basename} state={state} />} />
</Routes>
</BrowserRouter>
);
}

export interface ToolpadEditorLegacyProps {
basename: string;
appUrl: string;
}

export default function ToolpadEditor({ basename, appUrl }: ToolpadProps) {
export default function ToolpadEditorLegacy({ basename, appUrl }: ToolpadEditorLegacyProps) {
return (
<BrowserRouter basename={basename}>
<ToolpadEditorContent appUrl={appUrl} />
<ToolpadEditorRoutes appUrl={appUrl} />
</BrowserRouter>
);
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
Box,
ToggleButton,
ToggleButtonGroup,
Typography,
Expand Down Expand Up @@ -30,7 +31,7 @@ function SelectPropEditor({ label, propType, value, onChange, disabled }: Editor

return (
<PropertyControl propType={propType}>
<div>
<Box sx={{ my: 0.5 }}>
<Typography variant="body2">{label}</Typography>
<PropControlToggleButtonGroup
color="primary"
Expand All @@ -46,7 +47,7 @@ function SelectPropEditor({ label, propType, value, onChange, disabled }: Editor
</ToggleButton>
))}
</PropControlToggleButtonGroup>
</div>
</Box>
</PropertyControl>
);
}
Expand Down
Loading
Loading