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

fix(client): avoid concurrent compile step and init #946

Merged
merged 4 commits into from
May 26, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
refactor(node): improve client status management
  • Loading branch information
danilowoz committed May 26, 2023
commit d32696de33123da94138bf75fe8af6bca90201a4
2 changes: 2 additions & 0 deletions sandpack-client/src/clients/base.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { dequal as deepEqual } from "dequal";

import type { ClientStatus } from "..";
import type {
ClientOptions,
SandboxSetup,
Expand All @@ -20,6 +21,7 @@ export class SandpackClient {
*/
iframe!: HTMLIFrameElement;
iframeSelector: string | HTMLIFrameElement;
status: ClientStatus = "idle";

constructor(
iframeSelector: string | HTMLIFrameElement,
Expand Down
18 changes: 15 additions & 3 deletions sandpack-client/src/clients/node/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,9 @@ export class SandpackNode extends SandpackClient {
iframe: this.emulatorIframe,
runtimeUrl: this.options.bundlerURL,
});

// Trigger initial compile
this.updateSandbox(sandboxInfo);
}

// Initialize nodebox, should only ever be called once
Expand All @@ -88,6 +91,7 @@ export class SandpackNode extends SandpackClient {
private async compile(files: FilesMap): Promise<void> {
try {
// 1. Init
this.status = "initializing";
this.dispatch({ type: "start", firstLoad: true });
if (!this._initPromise) {
this._initPromise = this._init(files);
Expand Down Expand Up @@ -154,6 +158,8 @@ export class SandpackNode extends SandpackClient {
},
});

this.status = "installing-dependencies";

return;
}

Expand Down Expand Up @@ -228,6 +234,7 @@ export class SandpackNode extends SandpackClient {
* consumer that the bundler is ready without any error
*/
private dispatchDoneMessage(): void {
this.status = "done";
this.dispatch({ type: "done", compilatonError: false });

if (this.iframePreviewUrl) {
Expand Down Expand Up @@ -356,11 +363,11 @@ export class SandpackNode extends SandpackClient {
/**
* PUBLIC Methods
*/

public async restartShellProcess(): Promise<void> {
if (this.emulatorShellProcess && this.emulatorCommand) {
// 1. Set the loading state and clean the URL
this.dispatch({ type: "start", firstLoad: true });
this.status = "initializing";

// 2. Exit shell
await this.emulatorShellProcess.kill();
Expand All @@ -371,12 +378,13 @@ export class SandpackNode extends SandpackClient {
}
}

public updateSandbox(setup: SandboxSetup): any {
public updateSandbox(setup: SandboxSetup): void {
const modules = fromBundlerFilesToFS(setup.files);

/**
* Update file changes
*/

if (this.emulatorShellProcess?.state === "running") {
Object.entries(modules).forEach(([key, value]) => {
if (
Expand All @@ -400,7 +408,11 @@ export class SandpackNode extends SandpackClient {
type: "compile",
});

// Add modules to cache, this will ensure uniqueness changes
/**
* Add modules to cache, this will ensure uniqueness changes
*
* Keep it after the compile action, in order to update the cache at the right moment
*/
Object.entries(modules).forEach(([key, value]) => {
this._modulesCache.set(key, writeBuffer(value));
});
Expand Down
6 changes: 4 additions & 2 deletions sandpack-client/src/clients/runtime/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { createError } from "../..";
import type {
BundlerState,
ClientOptions,
ClientStatus,
ListenerFunction,
Modules,
SandboxSetup,
Expand Down Expand Up @@ -40,7 +39,6 @@ export class SandpackRuntime extends SandpackClient {
bundlerURL: string;
bundlerState?: BundlerState;
errors: SandpackError[];
status: ClientStatus;

selector!: string;
element: Element;
Expand Down Expand Up @@ -144,6 +142,10 @@ export class SandpackRuntime extends SandpackClient {
}
break;
}
case "done": {
this.status = "done";
break;
}
case "state": {
this.bundlerState = mes.state;
break;
Expand Down
17 changes: 9 additions & 8 deletions sandpack-client/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,14 +165,6 @@ export interface BundlerState {
transpiledModules: Record<string, TranspiledModule>;
}

export type ClientStatus =
| "initializing"
| "installing-dependencies"
| "transpiling"
| "evaluating"
| "running-tests"
| "idle";

export type SandpackMessage = SandpackRuntimeMessage | SandpackNodeMessage;

export type ListenerFunction = (msg: SandpackMessage) => void;
Expand Down Expand Up @@ -203,6 +195,15 @@ export interface SandpackErrorMessage {
};
}

export type ClientStatus =
| "initializing"
| "installing-dependencies"
| "transpiling"
| "evaluating"
| "running-tests"
| "idle"
| "done";

export type SandpackMessageConsoleMethods =
| "log"
| "debug"
Expand Down
24 changes: 22 additions & 2 deletions sandpack-react/src/Issues.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { useState } from "react";
import React, { useEffect, useState } from "react";

import { SandpackPreview } from "./components";
import { useSandpack } from "./hooks";
import { REACT_TEMPLATE } from "./templates";

import {
Expand All @@ -15,6 +17,18 @@ export default {
title: "Bug reports/Issues",
};

const SandpackLog = () => {
const { listen } = useSandpack();

useEffect(() => {
const unsubs = listen(console.log);

return unsubs;
}, []);

return null;
};

export const Issue944 = (): JSX.Element => {
const [files, setFiles] = useState(REACT_TEMPLATE["files"]);

Expand All @@ -41,7 +55,13 @@ export default function App() {
>
2
</button>
<Sandpack files={files} template="react" />
<SandpackProvider template="vite-react">
<SandpackLayout>
<SandpackLog />
<SandpackCodeEditor />
<SandpackPreview />
</SandpackLayout>
</SandpackProvider>
</>
);
};
Expand Down
6 changes: 1 addition & 5 deletions sandpack-react/src/components/Preview/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -120,16 +120,12 @@ export const SandpackPreview = React.forwardRef<
const [iframeComputedHeight, setComputedAutoHeight] = React.useState<
number | null
>(null);
const { status, errorScreenRegisteredRef, loadingScreenRegisteredRef } =
sandpack;
const { status } = sandpack;
const { refresh } = useSandpackNavigation(clientId);
const { restart } = useSandpackShell(clientId);

const classNames = useClassNames();

errorScreenRegisteredRef.current = true;
loadingScreenRegisteredRef.current = true;

React.useEffect(() => {
const unsubscribe = listen((message: SandpackMessage) => {
if (message.type === "resize") {
Expand Down
38 changes: 20 additions & 18 deletions sandpack-react/src/contexts/utils/useClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,6 @@ export interface UseClientOperations {
) => UnsubscribeFunction;
dispatchMessage: (message: SandpackMessage, clientId?: string) => void;
lazyAnchorRef: React.RefObject<HTMLDivElement>;
loadingScreenRegisteredRef: React.MutableRefObject<boolean>;
errorScreenRegisteredRef: React.MutableRefObject<boolean>;
unsubscribeClientListenersRef: React.MutableRefObject<
Record<string, Record<string, UnsubscribeFunction>>
>;
Expand Down Expand Up @@ -109,8 +107,6 @@ export const useClient: UseClient = (
Record<string, Record<string, ListenerFunction>>
>({ global: {} });
const debounceHook = useRef<number | undefined>();
const loadingScreenRegisteredRef = useRef<boolean>(true);
const errorScreenRegisteredRef = useRef<boolean>(true);
const prevEnvironment = useRef(filesState.environment);

/**
Expand Down Expand Up @@ -165,8 +161,8 @@ export const useClient: UseClient = (
skipEval: options.skipEval ?? false,
logLevel: options.logLevel,
showOpenInCodeSandbox: false,
showErrorScreen: errorScreenRegisteredRef.current,
showLoadingScreen: loadingScreenRegisteredRef.current,
showErrorScreen: true,
showLoadingScreen: false,
reactDevTools: state.reactDevTools,
customNpmRegistries: customSetup?.npmRegistries,
teamId: teamId,
Expand Down Expand Up @@ -473,8 +469,6 @@ export const useClient: UseClient = (
return;
}

console.log(recompileMode, filesState);

/**
* When the environment changes, Sandpack needs to make sure
* to create a new client and the proper bundler
Expand All @@ -489,10 +483,15 @@ export const useClient: UseClient = (

if (recompileMode === "immediate") {
Object.values(clients.current).forEach((client) => {
client.updateSandbox({
files: filesState.files,
template: filesState.environment,
});
/**
* Avoid concurrency
*/
if (client.status === "done") {
client.updateSandbox({
files: filesState.files,
template: filesState.environment,
});
}
});
}

Expand All @@ -502,10 +501,15 @@ export const useClient: UseClient = (
window.clearTimeout(debounceHook.current);
debounceHook.current = window.setTimeout(() => {
Object.values(clients.current).forEach((client) => {
client.updateSandbox({
files: filesState.files,
template: filesState.environment,
});
/**
* Avoid concurrency
*/
if (client.status === "done") {
client.updateSandbox({
files: filesState.files,
template: filesState.environment,
});
}
});
}, recompileDelay);
}
Expand Down Expand Up @@ -567,8 +571,6 @@ export const useClient: UseClient = (
registerReactDevTools,
addListener,
dispatchMessage,
loadingScreenRegisteredRef,
errorScreenRegisteredRef,
lazyAnchorRef,
unsubscribeClientListenersRef: unsubscribeClientListeners,
queuedListenersRef: queuedListeners,
Expand Down
7 changes: 0 additions & 7 deletions sandpack-react/src/hooks/useErrorMessage.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import * as React from "react";

import { useSandpack } from "./useSandpack";

/**
Expand All @@ -9,10 +7,5 @@ export const useErrorMessage = (): string | null => {
const { sandpack } = useSandpack();
const { error } = sandpack;

React.useEffect(() => {
sandpack.errorScreenRegisteredRef.current = true;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

return error?.message ?? null;
};
2 changes: 0 additions & 2 deletions sandpack-react/src/hooks/useLoadingOverlayState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,6 @@ export const useLoadingOverlayState = (
* Sandpack listener
*/
React.useEffect(() => {
sandpack.loadingScreenRegisteredRef.current = true;

const unsubscribe = listen((message) => {
if (message.type === "start" && message.firstLoad === true) {
setState("LOADING");
Expand Down
8 changes: 0 additions & 8 deletions sandpack-react/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -599,14 +599,6 @@ export interface SandpackState {
*/
lazyAnchorRef: React.RefObject<HTMLDivElement>;

/**
* eg: error screen - if no component registers this, the bundler needs to show the custom error screen
* When the value is boolean, we only care if the components have the responsibility to render the elements,
* we don't need the actual element reference
*/
errorScreenRegisteredRef: React.MutableRefObject<boolean>;
loadingScreenRegisteredRef: React.MutableRefObject<boolean>;

unsubscribeClientListenersRef: React.MutableRefObject<
Record<string, Record<string, UnsubscribeFunction>>
>;
Expand Down