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

feat: restore documentation examples #321

Merged
merged 18 commits into from
Oct 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
d6a1bdd
feat: split messageHandlers method and implement store diagram
stone-lyl Oct 16, 2024
ad1b985
feat: adjust types and implement getDiagram and updateDiagram methods
stone-lyl Oct 16, 2024
9ae68a0
fix: resolve issue in the playground demo
stone-lyl Oct 16, 2024
54557c7
feat: add getDiagram method to WorkspaceApiClient
stone-lyl Oct 16, 2024
b276917
fix: address issue with not receiving subscribed content before post …
stone-lyl Oct 16, 2024
da920f0
feat: add eventManager to updateDiagram method
stone-lyl Oct 17, 2024
3d6f081
feat: add getDiagram in SocketServer
stone-lyl Oct 17, 2024
1f39f7d
feat: replace onGetDirtyFileContent with getDiagram
stone-lyl Oct 18, 2024
a27339d
fix: resolve diagram type error in updateDiagram function
stone-lyl Oct 18, 2024
fe33a0a
feat: remove the `fileUri` variable
stone-lyl Oct 18, 2024
9d5e5af
feat: remove the "SAVE_SUCCESS" toast and save button
stone-lyl Oct 18, 2024
b89d1d9
fix: resolve node server coul not auto restart
stone-lyl Oct 18, 2024
a9c0288
fix: resolve issue where diagram did not exist in localStorage
stone-lyl Oct 18, 2024
d459720
fix: resolve the "playground not found" issue in e2e tests
stone-lyl Oct 18, 2024
207a457
feat: Rename `handle` prefix to `init` in WorkspaceApiClientBase class
stone-lyl Oct 18, 2024
2abb78a
fix: need to call the listener handler synchronously, as the data fro…
stone-lyl Oct 21, 2024
37a42b2
feat: rename initExecutionUpdateHandler to initExecutionUpdates
stone-lyl Oct 21, 2024
3afb229
feat: implement default value for `getDiagram` method in `ds-ext`
stone-lyl Oct 21, 2024
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
1 change: 1 addition & 0 deletions cypress/e2e/Playground.cy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ describe('add console.log node to playground', () => {
});

it('trigger addNodeModal', () => {
cy.wait(500);
getEl('add-node-button').click();

cy.wait(1000);
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@
"husky": "^8.0.0",
"kill-port": "^2.0.1",
"lint-staged": "^15.0.2",
"nodemon": "^3.1.4",
"pm2": "^5.4.2",
"postcss-cli": "^11.0.0",
"release-it": "^17.0.0",
"start-server-and-test": "^2.0.3",
Expand Down
5 changes: 5 additions & 0 deletions packages/docs/components/splash/CustomizeJSClient.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { ClientRunParams, createJSClient, WorkspaceApiClient, WorkspaceApiClient
export class CustomizeJSClient implements WorkspaceApiClient {
private nodeDescriptions: NodeDescription[];
private app: Application;
private diagram: Diagram;

constructor({ diagram, app, nodeDescriptions }: {
app: Application,
Expand All @@ -12,6 +13,7 @@ export class CustomizeJSClient implements WorkspaceApiClient {
}) {
this.nodeDescriptions = nodeDescriptions || [];
this.app = app;
this.diagram = diagram;
}

getNodeDescriptions = async({ path }) => {
Expand All @@ -23,4 +25,7 @@ export class CustomizeJSClient implements WorkspaceApiClient {
jsClient.run(params);
};

getDiagram = async({ path }) => {
return this.diagram;
};
}
16 changes: 6 additions & 10 deletions packages/ds-ext/src/DiagramEditorProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { MessageHandler } from './MessageHandler';
import { onRun } from './messageHandlers/onRun';
import { onGetNodeDescriptions } from './messageHandlers/onGetNodeDescriptions';
import { onUpdateDiagram } from './messageHandlers/onUpdateDiagram';
import { onGetDirtyFileContent } from './messageHandlers/onGetDirtyFileContent';
import { getDiagram } from './messageHandlers/getDiagram';
import { onToast } from './messageHandlers/onToast';

export class DiagramEditorProvider implements vscode.CustomEditorProvider<DiagramDocument> {
Expand Down Expand Up @@ -55,13 +55,15 @@ export class DiagramEditorProvider implements vscode.CustomEditorProvider<Diagra
run: onRun,
getNodeDescriptions: onGetNodeDescriptions,
updateDiagram: onUpdateDiagram,
getDirtyFileContent: onGetDirtyFileContent,
getDiagram: getDiagram,
toast: onToast,
};

const handler = handlers[event.type];
if(!handler) throw Error(`No handler found for event type: ${event.type}. Available handlers: ${Object.keys(handlers).join(', ')}`);

if (!handler) {
console.error(`No handler found for event type: ${event.type}. Available handlers: ${Object.keys(handlers).join(', ')}`);
return;
}
handler({ webviewPanel, event, document });
});
}
Expand All @@ -75,9 +77,6 @@ export class DiagramEditorProvider implements vscode.CustomEditorProvider<Diagra
vscode.Uri.file(mainScript)
ajthinking marked this conversation as resolved.
Show resolved Hide resolved
);

// Inject file URI and diagram data into the window object
const fileUri = webview.asWebviewUri(document.uri);

// Return HTML content for the Webview
return `
<!DOCTYPE html>
Expand All @@ -93,9 +92,6 @@ export class DiagramEditorProvider implements vscode.CustomEditorProvider<Diagra
<script>
// Provide the VS Code API and initial data (file URI and diagram content)
window.vscode = acquireVsCodeApi();
window.initialData = {
fileUri: "${fileUri}", // Pass file URI
};
</script>
</body>
</html>
Expand Down
53 changes: 4 additions & 49 deletions packages/ds-ext/src/app/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,58 +5,13 @@ import { VsCodeToast } from './VsCodeToast';
import { onDrop } from './onDrop';
ajthinking marked this conversation as resolved.
Show resolved Hide resolved
import { createVsCodeClient } from './createVsCodeClient';

export const fileUri = window.initialData.fileUri;

export default function App() {
const [diagram, setDiagram] = useState<Diagram | undefined>();

useEffect(() => {
if (window.vscode) {
window.vscode.postMessage({
type: 'getDirtyFileContent',
});
}

const handleMessage = (event: any) => {
const message = event.data;

if (message.type === 'dirtyFileContent') {
setDiagram(
message.fileContent
? new Diagram(JSON.parse(message.fileContent))
: new Diagram()
);
}
};

window.addEventListener('message', handleMessage);

// Cleanup the listener on unmount
return () => {
window.removeEventListener('message', handleMessage);
};
}, []);

const client = createVsCodeClient(window.vscode);
const handleChange = useCallback(
debounce(async (diagram: Diagram) => {
// Construct the message payload with updated diagram data
const updatedData = {
type: 'updateDiagram',
fileUri, // Include the file URI to specify the target file
diagram: JSON.stringify(diagram),
};

// Send the message to VS Code extension
window.vscode.postMessage(updatedData);
client!.updateDiagram?.(diagram);
}, 100), // Debounced with 100ms delay
[fileUri]
);

const client = createVsCodeClient(window.vscode);
// Only render DataStory if diagramData is available
if (!diagram) {
return <div>Loading diagram...</div>;
}
[client]);

return (
<div style={{ width: '100%', height: '100vh' }}>
Expand All @@ -66,9 +21,9 @@ export default function App() {
hideActivityBar={true}
initSidebarKey={undefined}
key={'abc'}
initDiagram={diagram}
onChange={handleChange}
onDrop={onDrop}
hideControls={['save']}
/>
<VsCodeToast postMessage={window.vscode.postMessage} />
</div>
Expand Down
4 changes: 2 additions & 2 deletions packages/ds-ext/src/app/VsCodeToast.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export function VsCodeToast({ postMessage }: {
info.status = 'error';
break;
case DataStoryEvents.SAVE_SUCCESS:
info.message = 'Diagram saved successfully!';
// info.message = 'Diagram saved successfully!';
break;
case DataStoryEvents.SAVE_ERROR:
console.error(event.payload);
Expand All @@ -40,4 +40,4 @@ export function VsCodeToast({ postMessage }: {
return (
<div></div>
);
}
}
16 changes: 16 additions & 0 deletions packages/ds-ext/src/messageHandlers/getDiagram.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Diagram } from '@data-story/core';
import { MessageHandler } from '../MessageHandler';

export const getDiagram: MessageHandler = async ({ event, webviewPanel, document }) => {
const diagramData = new TextDecoder().decode(document.data);
let diagram = new Diagram();
if(diagramData) {
diagram = JSON.parse(diagramData);
}

webviewPanel.webview.postMessage({
...event,
type: 'getDiagram',
diagram: diagram,
});
};
8 changes: 0 additions & 8 deletions packages/ds-ext/src/messageHandlers/onGetDirtyFileContent.ts

This file was deleted.

2 changes: 1 addition & 1 deletion packages/ds-ext/src/messageHandlers/onUpdateDiagram.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@ export const onUpdateDiagram: MessageHandler = async ({
event,
document,
}) => {
document.update(new TextEncoder().encode(event.diagram));
document.update(new TextEncoder().encode(JSON.stringify(event.diagram)));
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is quite a change, might be related to section "Vscode broken"?

Copy link
Collaborator Author

@stone-lyl stone-lyl Oct 21, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I've standardized the data format returned by the various servers (jsServer, socketServer, and vscodeServer). Therefore, we need to recreate the .diagram.json file in ds-ext 😂

await document.save();
};
6 changes: 0 additions & 6 deletions packages/nodejs/nodemon.json

This file was deleted.

2 changes: 1 addition & 1 deletion packages/nodejs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"test": "yarn run -T vitest",
"build": "tsc",
"release": "yarn run -T release-it",
"watch:server": "nodemon"
"watch:server": "pm2 start ./test-server.ts --watch --no-daemon"
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Worked great 👍

},
"release-it": {
"git": false,
Expand Down
5 changes: 4 additions & 1 deletion packages/nodejs/src/server/SocketServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,10 @@ export class SocketServer {
const parsed: { type: string } & Record<string, any> = JSON.parse(message);

const handler = this.messageHandlers[parsed.type];
if (!handler) throw new Error('Unknown message type (server): ' + parsed.type);
if (!handler) {
console.warn('Unknown message type (server): ' + parsed.type);
return;
}

await handler(ws, parsed, this.app, storage);
}
Expand Down
20 changes: 20 additions & 0 deletions packages/nodejs/src/server/messageHandlers/getDiagram.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Diagram } from '@data-story/core';
import WebSocket from 'ws';
import { MessageHandler } from '../MessageHandler';

interface GetDiagramMessage {
type: 'getDiagram';
msgId: string;
}

export const getDiagram: MessageHandler<GetDiagramMessage> = async(
ws: WebSocket,
data: GetDiagramMessage,
) => {
const diagram = new Diagram();
ws.send(JSON.stringify({
...data,
type: 'getDiagram',
diagram,
}));
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import WebSocket from 'ws';

export type DescribeMessage = {
type: 'getNodeDescriptions',
id: string,
msgId: string;
}

export const getNodeDescriptions: MessageHandler<DescribeMessage> = async (
Expand Down
1 change: 1 addition & 0 deletions packages/nodejs/src/server/messageHandlers/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export { getNodeDescriptions } from './getNodeDescriptions'
export { getItems } from './getItems'
export { run } from './run'
export { getDiagram } from './getDiagram'
1 change: 0 additions & 1 deletion packages/nodejs/src/server/messageHandlers/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ export const run: MessageHandler<RunMessage> = async(

const execution = executor.execute()

console.log('sendMsg', sendMsg);
try {
for await(const update of execution) {
ws.send(JSON.stringify({
Expand Down
24 changes: 15 additions & 9 deletions packages/ui/src/components/DataStory/DataStory.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ import { DataStoryCanvasProvider } from './store/store';
import { DataStoryCanvas } from './DataStoryCanvas';
import { useRequest } from 'ahooks';
import { LoadingMask } from './common/loadingMask';
import { Diagram, } from '@data-story/core';
import { LocalStorageKey } from './common/method';

function handleRequestError(requestError?: Error): void {
if (requestError) console.error(`Error fetching : ${requestError?.message}`);
Expand All @@ -23,24 +21,32 @@ export const DataStoryComponent = (
const [selectedNode, setSelectedNode] = useState<ReactFlowNode>();
const [isSidebarClose, setIsSidebarClose] = useState(!!props.hideSidebar);
const partialStoreRef = useRef<Partial<StoreSchema>>(null);
const [diagram] = useState<Diagram | null>(initDiagram || new Diagram());
const [sidebarKey, setSidebarKey] = useState(() => {
// If initDiagram isn't provided, default to 'addNode' to show the sidebar
const defaultKey = initDiagram ? '' : 'addNode';
return initSidebarKey ?? defaultKey;
return initSidebarKey ?? '';
});

const {
data: nodeDescriptions,
loading: nodeDescriptionsLoading,
error: getNodeDescriptionsError
} = useRequest(async() => {
return client.getNodeDescriptions({ path: LocalStorageKey })
return client.getNodeDescriptions({})
}, {
refreshDeps: [client], // Will re-fetch if client changes
});
handleRequestError(getNodeDescriptionsError);

const {
data: diagramData,
loading: diagramDataLoading,
error: diagramDataError
} = useRequest(async() => {
return client.getDiagram?.({});
}, {
refreshDeps: [client], // Will re-fetch if client changes
});
handleRequestError(diagramDataError);

useEffect(() => {
if (sidebarKey !== 'node') {
setSelectedNode(undefined);
Expand All @@ -66,7 +72,7 @@ export const DataStoryComponent = (
<div className="relative h-full w-full">
{children}
{
(false) // TODO isLoading?
(diagramDataLoading || nodeDescriptionsLoading) // TODO isLoading?
? <LoadingMask/>
: <Allotment className='h-full border-0.5 relative'>
{/*The Allotment.Pane will recalculate the width and height of the child components.*/}
Expand All @@ -76,7 +82,7 @@ export const DataStoryComponent = (
{...props}
onSave={client.updateDiagram}
key={'data-story-canvas'}
initDiagram={diagram}
initDiagram={diagramData}
ref={partialStoreRef}
setSidebarKey={setSidebarKey}
sidebarKey={sidebarKey}
Expand Down
4 changes: 1 addition & 3 deletions packages/ui/src/components/DataStory/DataStoryCanvas.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import { onDropDefault } from './onDropDefault';
import type { NodeTypes } from '@xyflow/react/dist/esm/types';
import { HotkeyManager, useHotkeys } from './useHotkeys';
import { useEscapeKey } from './hooks/useEscapeKey';
import { Placeholder } from './common/placeholder';

const nodeTypes = {
commentNodeComponent: CommentNodeComponent,
Expand All @@ -25,12 +24,11 @@ const nodeTypes = {

const DataStoryCanvasComponent = forwardRef((props: DataStoryCanvasProps, ref) => {
useGetStore(ref);
const showPlaceholder = !props.initDiagram;

return (
<>
<ReactFlowProvider>
{showPlaceholder ? <Placeholder content={'No diagram found'}/> : <Flow {...props}/>}
<Flow {...props}/>
</ReactFlowProvider>
</>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Diagram, NodeDescription } from '@data-story/core';

export interface WorkspaceApiClient {
run(params: ClientRunParams): void;
getNodeDescriptions: ({ path }: { path: string}) => Promise<NodeDescription[]>
getNodeDescriptions: ({ path }: { path?: string}) => Promise<NodeDescription[]>
updateDiagram?: (diagram: Diagram) => Promise<void>;

getDiagram?: ({ path }: { path?: string}) => Promise<Diagram>;
}
Loading