1.0.1 • Published 3 months ago

@stackblitz-react/sdk v1.0.1

Weekly downloads
-
License
ISC
Repository
github
Last release
3 months ago

StackBlitz SDK React Wrapper

Versão em Português

A unofficial React wrapper for the StackBlitz SDK that makes it easy to embed interactive code editors in React applications.

Table of Contents

Installation

npm install @stackblitz-react/sdk

Then, import the wrapper in your components:

import {stackBlitz} from '@stackblitz-react/sdk';

Overview

This wrapper provides a React interface for the StackBlitz SDK, allowing you to easily:

  • Embed GitHub projects in your application
  • Create projects with custom files
  • Embed existing StackBlitz projects using their ID
  • Interact with the editor in real-time through the VM API

Components

Editor

Component to embed GitHub projects in your application.

Props

PropTypeDefaultDescription
embedIdstring'stackblitz-container'ID of the element where the editor will be embedded
githubstring-GitHub repository in the format 'user/repository'
openFilestring/booleanfalseFile to be initially opened
hideNavigationbooleanfalseWhether to hide navigation
hideExplorerbooleanfalseWhether to hide the file explorer
viewstring'both'View type ('preview', 'editor', 'both')
heightstring/number500Editor height
widthstring/number'100%'Editor width
optionsobject{}Additional configuration options
onLoadfunctionnullCallback called when the VM is loaded

Example

<stackBlitz.Editor
  embedId="github-editor-example"
  github="user/repository"
  openFile="README.md"
  height="400px"
  width="100%"
  view="editor"
  onLoad={(vm) => console.log('VM loaded', vm)}
/>

ProjectEditor

Component to create projects with custom files.

Props

PropTypeDefaultDescription
embedIdstring'stackblitz-project-editor'ID of the element where the editor will be embedded
templatestring'javascript'Project type (javascript, node, react, etc.)
titlestring'StackBlitz Project'Project title
descriptionstring''Project description
filesobject{}Object with project files and their contents
openFilestring/booleanfalseFile to be initially opened
hideNavigationbooleanfalseWhether to hide navigation
hideExplorerbooleanfalseWhether to hide the file explorer
viewstring'editor'View type ('preview', 'editor', 'both')
heightstring/number500Editor height
widthstring/number'100%'Editor width
optionsobject{}Additional configuration options
onLoadfunctionnullCallback called when the VM is loaded

Example

<stackBlitz.ProjectEditor
  embedId="custom-editor-example"
  template="node"
  title="Node.js Example"
  files={{
    'index.js': 'console.log("Hello from StackBlitz!");',
    'package.json': JSON.stringify({
      name: "node-starter",
      version: "0.0.0",
      private: true,
      scripts: {
        start: "node index.js"
      }
    }, null, 2)
  }}
  height="400px"
  width="100%"
  view="editor"
  onLoad={(vm) => console.log('VM loaded', vm)}
/>

ProjectIdEditor

Component to embed existing StackBlitz projects using their ID.

Props

PropTypeDefaultDescription
embedIdstring'stackblitz-project-id-editor'ID of the element where the editor will be embedded
projectIdstring-StackBlitz project ID to be embedded
openFilestring-File to be initially opened
hideNavigationbooleanfalseWhether to hide navigation
hideExplorerbooleanfalseWhether to hide the file explorer
viewstring'editor'View type ('preview', 'editor', 'both')
heightstring/number500Editor height
widthstring/number'100%'Editor width
optionsobject{}Additional configuration options
onLoadfunctionnullCallback called when the VM is loaded

Example

<stackBlitz.ProjectIdEditor
  embedId="project-id-editor-example"
  projectId="sdk-example-project"
  openFile="index.js"
  height="500px"
  width="100%"
  view="both"
  onLoad={(vm) => console.log('VM loaded', vm)}
/>

Helper Functions

The wrapper also provides helper functions to open projects in new tabs or embed them directly without React components.

openGithubProject

Opens a GitHub project in a new tab.

stackBlitz.openGithubProject('user/repository', {
  openFile: 'README.md'
});

openProject

Opens a custom project in a new tab.

stackBlitz.openProject({
  template: 'node',
  title: 'Example Node.js Project',
  description: 'A simple Node.js project',
  files: {
    'index.js': 'console.log("Hello from StackBlitz!");',
    'package.json': JSON.stringify({
      name: "node-starter",
      version: "0.0.0",
      private: true,
      scripts: {
        start: "node index.js"
      }
    }, null, 2)
  }
});

openProjectId

Opens a StackBlitz project by ID in a new tab.

stackBlitz.openProjectId('sdk-example-project', {
  openFile: 'index.html',
  view: 'both'
});

embedGithubProject

Embeds a GitHub project in a DOM element.

stackBlitz.embedGithubProject('element-id', 'user/repository', {
  openFile: 'README.md',
  height: 500
}).then(vm => {
  console.log('VM loaded', vm);
});

embedProject

Embeds a custom project in a DOM element.

stackBlitz.embedProject('element-id', {
  template: 'node',
  title: 'Node.js Project',
  files: {
    'index.js': 'console.log("Hello from StackBlitz!");'
  }
}, {
  height: 500
}).then(vm => {
  console.log('VM loaded', vm);
});

embedProjectId

Embeds a StackBlitz project by ID in a DOM element.

stackBlitz.embedProjectId('element-id', 'sdk-example-project', {
  openFile: 'index.js',
  height: 500
}).then(vm => {
  console.log('VM loaded', vm);
});

Usage Examples

Embedding a GitHub editor

import React, { useCallback, useState } from 'react';
import stackBlitz from '../stackblitzEditor';

export default function GithubEditorExample() {
  const [log, setLog] = useState([]);
  
  const handleVmReady = useCallback((vm) => {
    setLog(prev => [...prev, 'VM successfully initialized!']);
    
    // Example of interacting with the VM
    vm.editor.openFile('README.md');
  }, []);
  
  return (
    <div>
      <h1>GitHub Editor</h1>
      <stackBlitz.Editor
        embedId="github-editor-example"
        github="user/repository"
        openFile="README.md"
        height="400px"
        width="100%"
        view="editor"
        onLoad={handleVmReady}
      />
      <div>
        {log.map((entry, index) => <div key={index}>{entry}</div>)}
      </div>
    </div>
  );
}

Creating a project with custom files

import React from 'react';
import stackBlitz from '../stackblitzEditor';

export default function CustomProjectExample() {
  return (
    <div>
      <h1>Custom Project</h1>
      <stackBlitz.ProjectEditor
        embedId="custom-editor-example"
        template="node"
        title="Node.js Example"
        files={{
          'index.js': 'console.log("Hello from StackBlitz!");',
          'package.json': JSON.stringify({
            name: "node-starter",
            version: "0.0.0",
            private: true,
            scripts: {
              start: "node index.js"
            }
          }, null, 2)
        }}
        height="400px"
        width="100%"
        view="editor"
      />
    </div>
  );
}

StackBlitz VM API

When you use the onLoad callback, you get access to the StackBlitz VM API, which allows you to interact with the editor in real-time.

Main VM methods

applyFsDiff

Applies changes to the file system.

vm.applyFsDiff({
  create: {
    'newFile.js': 'console.log("New file");'
  },
  destroy: ['oldFile.js']
});

getFsSnapshot

Gets a current snapshot of the file system.

vm.getFsSnapshot().then(files => {
  console.log('Available files:', Object.keys(files));
});

editor.openFile

Opens a specific file in the editor.

vm.editor.openFile('index.js');

preview.getUrl

Gets the preview URL.

vm.preview.getUrl().then(url => {
  console.log('Preview URL:', url);
});

Limitations and Considerations

  • The StackBlitz SDK only works in modern browsers.
  • Large projects may take longer to load.

Contribution

Feel free to contribute to this wrapper by creating issues or pull requests.

License

MIT

1.0.1

3 months ago

1.0.0

3 months ago