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

Extract Devtools component from function datasource for reuse in fetch #740

Merged
merged 1 commit into from
Aug 5, 2022
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
55 changes: 55 additions & 0 deletions packages/toolpad-app/src/components/Devtools.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import * as React from 'react';
import { TabPanel, TabContext, TabList } from '@mui/lab';
import { Box, styled, SxProps, Tab } from '@mui/material';
import { Har } from 'har-format';
import Console, { LogEntry } from './Console';
import lazyComponent from '../utils/lazyComponent';

const HarViewer = lazyComponent(() => import('./HarViewer'), {});

const DebuggerTabPanel = styled(TabPanel)({ padding: 0, flex: 1, minHeight: 0 });

export interface DevtoolsProps {
log?: LogEntry[];
onLogChange?: (newLog: LogEntry[]) => void;
har?: Har;
sx?: SxProps;
}

export default function Devtools({ sx, log, onLogChange, har }: DevtoolsProps) {
const [activeTab, setActiveTab] = React.useState(() => {
if (log) {
return 'console';
}
if (har) {
return 'network';
}
return '';
});
const handleDebuggerTabChange = (event: React.SyntheticEvent, newValue: string) => {
setActiveTab(newValue);
};

return (
<Box sx={{ ...sx, display: 'flex', flexDirection: 'column' }}>
<TabContext value={activeTab}>
<Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
<TabList onChange={handleDebuggerTabChange} aria-label="Debugger">
{log ? <Tab label="Console" value="console" /> : null}
{har ? <Tab label="Network" value="network" /> : null}
</TabList>
</Box>
{log ? (
<DebuggerTabPanel value="console">
<Console sx={{ flex: 1 }} value={log} onChange={onLogChange} />
</DebuggerTabPanel>
) : null}
{har ? (
<DebuggerTabPanel value="network">
<HarViewer har={har} />
</DebuggerTabPanel>
) : null}
</TabContext>
</Box>
);
}
8 changes: 8 additions & 0 deletions packages/toolpad-app/src/server/applyTransform.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import evalExpression from './evalExpression';

export default async function applyTransform(transform: string, data: any): Promise<any> {
const transformFn = `(data) => {${transform}}`;
return {
data: await evalExpression(`${transformFn}(${JSON.stringify(data)})`),
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ const LEGACY_DATASOURCE_QUERY_EDITOR_LAYOUT = new Set([
'movies',
]);

const EMPTY_OBJECT = {};

export interface ConnectionSelectProps extends WithControlledProp<NodeId | null> {
dataSource?: string;
sx?: SxProps;
Expand Down Expand Up @@ -182,28 +184,46 @@ function QueryNodeEditorDialog<Q, P>({

const connectionId = appDom.deref(input.attributes.connectionId.value);
const connection = appDom.getMaybeNode(dom, connectionId, 'connection');
const inputParams = input.params || EMPTY_OBJECT;
const dataSourceId = input.attributes.dataSource?.value;
const dataSource = (dataSourceId && dataSources[dataSourceId]) || null;

const handleConnectionChange = React.useCallback((newConnectionId: NodeId | null) => {
const connectionParams = connection?.attributes.params.value;

const queryModel = React.useMemo(
() => ({
query: input.attributes.query.value,
params: inputParams,
}),
[input.attributes.query.value, inputParams],
);

const handleQueryModelChange = React.useCallback((model: QueryEditorModel<Q>) => {
setInput((existing) =>
update(existing, {
attributes: update(existing.attributes, {
connectionId: newConnectionId
? appDom.createConst(appDom.ref(newConnectionId))
: undefined,
query: appDom.createConst(model.query),
}),
params: model.params,
}),
);
}, []);

const handleQueryChange = React.useCallback((model: QueryEditorModel<Q>) => {
const { pageState } = usePageEditorState();

const liveParams = useEvaluateLiveBindings({
input: inputParams,
globalScope: pageState,
});

const handleConnectionChange = React.useCallback((newConnectionId: NodeId | null) => {
setInput((existing) =>
update(existing, {
attributes: update(existing.attributes, {
query: appDom.createConst(model.query),
connectionId: newConnectionId
? appDom.createConst(appDom.ref(newConnectionId))
: undefined,
}),
params: model.params,
}),
);
}, []);
Expand Down Expand Up @@ -272,13 +292,6 @@ function QueryNodeEditorDialog<Q, P>({
[],
);

const { pageState } = usePageEditorState();

const liveParams = useEvaluateLiveBindings({
input: input.params || {},
globalScope: pageState,
});

const handleSave = React.useCallback(() => {
onSave(input);
}, [onSave, input]);
Expand Down Expand Up @@ -420,13 +433,10 @@ function QueryNodeEditorDialog<Q, P>({
>
{/* This is the exact same element as below */}
<dataSource.QueryEditor
connectionParams={connection?.attributes.params.value}
value={{
query: input.attributes.query.value,
params: input.params,
}}
connectionParams={connectionParams}
value={queryModel}
liveParams={liveParams}
onChange={handleQueryChange}
onChange={handleQueryModelChange}
globalScope={pageState}
/>

Expand Down Expand Up @@ -539,13 +549,10 @@ function QueryNodeEditorDialog<Q, P>({
</SplitPane>
) : (
<dataSource.QueryEditor
connectionParams={connection?.attributes.params.value}
value={{
query: input.attributes.query.value,
params: input.params,
}}
connectionParams={connectionParams}
value={queryModel}
liveParams={liveParams}
onChange={handleQueryChange}
onChange={handleQueryModelChange}
globalScope={pageState}
/>
)}
Expand Down
38 changes: 10 additions & 28 deletions packages/toolpad-app/src/toolpadDataSources/function/client.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import * as React from 'react';
import { Box, Button, Skeleton, Stack, styled, Tab, Toolbar, Typography } from '@mui/material';
import { Box, Button, Skeleton, Stack, Toolbar, Typography } from '@mui/material';
import { BindableAttrValue, BindableAttrValues, LiveBinding } from '@mui/toolpad-core';

import { LoadingButton, TabContext, TabList, TabPanel } from '@mui/lab';
import { LoadingButton } from '@mui/lab';
import PlayArrowIcon from '@mui/icons-material/PlayArrow';
import { Controller, useForm } from 'react-hook-form';
import { ClientDataSource, ConnectionEditorProps, QueryEditorProps } from '../../types';
Expand All @@ -19,14 +19,11 @@ import { useConnectionContext, usePrivateQuery } from '../context';
import client from '../../api';
import JsonView from '../../components/JsonView';
import ErrorAlert from '../../toolpad/AppEditor/PageEditor/ErrorAlert';
import Console, { LogEntry } from '../../components/Console';
import { LogEntry } from '../../components/Console';
import MapEntriesEditor from '../../components/MapEntriesEditor';
import { Maybe } from '../../utils/types';
import { isSaveDisabled } from '../../utils/forms';

const HarViewer = lazyComponent(() => import('../../components/HarViewer'), {});

const DebuggerTabPanel = styled(TabPanel)({ padding: 0, flex: 1, minHeight: 0 });
import Devtools from '../../components/Devtools';

const EVENT_INTERFACE_IDENTIFIER = 'ToolpadFunctionEvent';

Expand Down Expand Up @@ -180,11 +177,6 @@ function QueryEditor({
return [{ content, filePath: 'file:///node_modules/@mui/toolpad/index.d.ts' }];
}, [params, secretsKeys]);

const [debuggerTab, setDebuggerTab] = React.useState('console');
const handleDebuggerTabChange = (event: React.SyntheticEvent, newValue: string) => {
setDebuggerTab(newValue);
};

return (
<SplitPane split="vertical" size="50%" allowResize>
<SplitPane split="horizontal" size={85} primary="second" allowResize>
Expand Down Expand Up @@ -223,22 +215,12 @@ function QueryEditor({
)}
</Box>

<TabContext value={debuggerTab}>
<Box sx={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column' }}>
<Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
<TabList onChange={handleDebuggerTabChange} aria-label="Debugger">
<Tab label="Console" value="console" />
<Tab label="Network" value="network" />
</TabList>
</Box>
<DebuggerTabPanel value="console">
<Console sx={{ flex: 1 }} value={previewLogs} onChange={setPreviewLogs} />
</DebuggerTabPanel>
<DebuggerTabPanel value="network">
<HarViewer har={preview?.har} />
</DebuggerTabPanel>
</Box>
</TabContext>
<Devtools
sx={{ width: '100%', height: '100%' }}
log={previewLogs}
onLogChange={setPreviewLogs}
har={preview?.har}
/>
</SplitPane>
</SplitPane>
);
Expand Down
39 changes: 39 additions & 0 deletions packages/toolpad-app/src/toolpadDataSources/useQueryPreview.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import * as React from 'react';
import { useConnectionContext } from './context';
import client from '../api';

export interface UseQueryPreviewOptions<R> {
onPreview?: (result: R) => void;
}

export default function useQueryPreview<PQ, R>(
privateQuery: PQ,
{ onPreview = () => {} }: UseQueryPreviewOptions<R> = {},
) {
const { appId, connectionId } = useConnectionContext();
const [preview, setPreview] = React.useState<R | null>(null);

const cancelRunPreview = React.useRef<(() => void) | null>(null);
const runPreview = React.useCallback(() => {
let canceled = false;

cancelRunPreview.current?.();
cancelRunPreview.current = () => {
canceled = true;
};

client.query
.dataSourceFetchPrivate(appId, connectionId, privateQuery)
.then((result) => {
if (!canceled) {
setPreview(result);
onPreview?.(result);
}
})
.finally(() => {
cancelRunPreview.current = null;
});
}, [appId, connectionId, privateQuery, onPreview]);

return { preview, runPreview };
}