sandpack icon indicating copy to clipboard operation
sandpack copied to clipboard

Feature request: load external sandbox

Open danilowoz opened this issue 3 years ago • 5 comments

What is this feature?

Implement the ability to load external sandbox from CodeSandbox directly on Sandpack. The API would looks something like this:

<Sandpack template={{ sandboxId: "SANDBOXID" }} />

Main challenges:

  • Find out a decent way to merge the payload from endpoint and custom setup?
  • How to trigger new changes (componentDidMount) and still keep the payload from the endpoint?
  • Sandpack needs to "understand" it's in a loading state;

Working in progress:

  /**
   * @hidden
   */
  fetchSandbox = async (
    sandboxId: string,
    onDone: () => void
  ): Promise<void> => {
    const payload: SandboxTemplate & { is_sse: boolean } = await fetch(
      `https://codesandbox.io/api/v1/sandboxes/csb-id-${sandboxId}/sandpack`
    )
      .then((data) => data.json())
      .catch(() => {
        console.error(
          `Something went wrong while fetching \`${sandboxId}\` sandbox`
        );
      });

    if (payload.is_sse) {
      throw Error("Sandpack doesn't support sandboxes that runs on server.");
    }

    this.setState({ externalSandboxPayload: payload }, onDone);
  };

  componentDidMount(): void {
    if (this.props.template && typeof this.props.template !== "string") {
      this.fetchSandbox(
        this.props.template.sandboxId,
        this.initializeSandpackIframe
      );
    } else {
      this.initializeSandpackIframe();
    }
  }

  // sandpackUtils.test.ts
 /**
   * Template
   */
  test("it defaults to a default template, when `template` is an external sandbox", () => {
    const setup = getSandpackStateFromProps({
      template: { sandboxId: "SANDBOX_ID" },
    });

    expect(setup.files).toEqual({
      ...VANILLA_TEMPLATE.files,
      "/package.json": {
        code: `{
  "name": "sandpack-project",
  "main": "/src/index.js",
  "dependencies": {},
  "devDependencies": {}
}`,
      },
    });
  });

danilowoz avatar Feb 01 '22 17:02 danilowoz

Code Hike is currently using the https://codesandbox.io/api/v1/sandboxes/${csbid}/sandpack endpoint at build time (inside a remark plugin).

It would be nice if the fetchSandbox function is exposed from @codesandbox/sandpack-client so I could keep doing the same but abstracting away the URL.

pomber avatar Feb 03 '22 10:02 pomber

This feature will land soon on the next major Sandpack release 🚀

danilowoz avatar Dec 19 '22 09:12 danilowoz

Is this still coming in the next major release?

zachmerrill avatar Jan 30 '23 16:01 zachmerrill

a year is over still wating...

rahathosen avatar Jan 08 '24 08:01 rahathosen

How can I preview a Nextjs app that uses app router not pages? How can I preview this sandbox specifically https://codesandbox.io/api/v1/sandboxes/csb-id-jyfdkf/sandpack?

Any chance you could help @danilowoz @pomber

cameronking4 avatar Mar 01 '24 08:03 cameronking4