Hooks

useWorkspace

A React hook for managing workspace state and code compilation.

useWorkspace is a React hook that provides reactive access to workspace state, including files, compilation results, and the workspace instance. It handles code analysis, compilation, and state synchronization automatically.

import { useWorkspace } from '@codespark/react';

Basic Usage

When used inside a CodesparkProvider, simply call useWorkspace() to access the workspace from context. All returned properties (files, compiled, currentFile, etc.) are reactive - your component will automatically re-render when the workspace state changes.

import { , ,  } from '@codespark/react';

function () {
  // All returned values are reactive and will trigger re-renders on change
  const { , , , ,  } = ();

  // Update a file - this will trigger recompilation and re-render
  const  = () => {
    .('./App.tsx', 'export default () => <div>Updated!</div>');
  };

  if () {
    return (
      < ="space-y-2 text-center">
        <>Current file: {.}</>
        <>Error: {.}</>
        < ={} ="rounded-lg bg-black px-2 py-1 text-white">
          Update Code
        </>
      </>
    );
  }

  return < />;
}

export default function () {
  return (
    <>
      < />
    </>
  );
}

Standalone Usage

You can also use useWorkspace outside of CodesparkProvider by passing a WorkspaceInit config. This is useful when you need to create a workspace and pass it to CodesparkProvider. All the workspace methods still work in this way:

import { , , ,  } from '@codespark/react';
import {  } from 'react';

export default function () {
  // Create workspace outside of Provider
  const { ,  } = ({
    : './App.tsx',
    : {
      './App.tsx': 'export default () => <div>Hello</div>'
    }
  });

  const  = () => {
    // you can use workspace methods here
    .('...');
  };

  (() => {
    // trigger every time when compiled code updated
    .('compiled code:', );
  }, []);

  return (
    < ={}>
      < />
      < />
    </>
  );
}

Parameters

init

Workspace initialization config or an existing Workspace instance. Optional when used inside CodesparkProvider.

TypeDefault
WorkspaceInit | WorkspaceContext workspace
import { ,  } from '@codespark/react';

// 1. No parameters - use workspace from CodesparkProvider context
const  = ();

// 2. Using WorkspaceInit config - create new workspace
const  = ({
  : './App.tsx',
  : { './App.tsx': '...' }
});

// 3. Using existing Workspace instance
const  = new ({
  : './App.tsx',
  : { './App.tsx': '...' }
});
const  = ();

Return Value

The hook returns an object with the following properties:

files

Current files in the workspace.

TypeSince
Record<string, string>v1.0.0
import {  } from '@codespark/react';

function () {
  const {  } = ({ : './App.tsx', : { './App.tsx': '...' } });

  // Access file content
  .(['./App.tsx']);
}

currentFile

Currently active file in the editor.

TypeSince
FileNodev1.0.0
interface FileNode {
  type: 'file';
  name: string;      // File name (e.g., 'App.tsx')
  path: string;      // Full path (e.g., './App.tsx')
  code: string;      // File content
  language?: string; // Language identifier
}

compiled

Compiled code string ready for execution in the preview iframe.

TypeSince
stringv1.0.0

compileError

Compilation error if the code failed to compile, null otherwise.

TypeSince
Error | nullv1.0.0
import {  } from '@codespark/react';

function () {
  const { ,  } = ({ : './App.tsx', : { './App.tsx': '...' } });

  if () {
    return <>Error: {.}</>;
  }

  return <>{}</>;
}

fileTree

Hierarchical file tree structure for rendering file explorer.

TypeSince
FileTreeNode[]v1.0.0
type FileTreeNode = FileNode | FolderNode;

interface FolderNode {
  type: 'folder';
  name: string;
  path: string;
  children?: FileTreeNode[];
}

vendor

Vendor resources extracted from the compilation process.

TypeSince
{ modules, styles, scripts, imports }v1.0.0
interface Vendor {
  modules: Output<LoaderType.ESModule>[];  // ES modules
  styles: Output<LoaderType.Style>[];      // Style resources
  scripts: Output<LoaderType.Script>[];    // Script resources
  imports: Record<string, string>;         // Import map
}

workspace

The Workspace instance for programmatic control.

TypeSince
Workspacev1.0.0
import {  } from '@codespark/react';

function () {
  const {  } = ({ : './App.tsx', : { './App.tsx': '...' } });

  // Programmatically update a file
  const  = () => {
    .('./App.tsx', 'export default () => <div>Updated</div>');
  };

  // Listen to events
  .('compiled', () => {
    .('Compiled:', );
  });
}

Types

interface UseWorkspaceReturn {
  files: Record<string, string>;
  currentFile: FileNode;
  fileTree: FileTreeNode[];
  compiled: string;
  compileError: Error | null;
  vendor: {
    modules: Output<LoaderType.ESModule>[];
    styles: Output<LoaderType.Style>[];
    scripts: Output<LoaderType.Script>[];
    imports: Record<string, string>;
  };
  workspace: Workspace;
}

Last updated on