Skip to content

Commit 8613469

Browse files
feat: FIT-14: LabelStudio Playground 2.0 (#7521)
Co-authored-by: Yousif Yassi <yousif@heartex.com>
1 parent 2ba08a7 commit 8613469

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

44 files changed

+3210
-33
lines changed

web/apps/labelstudio/src/pages/CreateProject/Config/Config.jsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import { Preview } from "./Preview";
1313
import { DEFAULT_COLUMN, EMPTY_CONFIG, isEmptyConfig, Template } from "./Template";
1414
import { TemplatesList } from "./TemplatesList";
1515

16-
import tags from "./schema.json";
16+
import tags from "@humansignal/core/lib/utils/schema/tags.json";
1717
import { UnsavedChanges } from "./UnsavedChanges";
1818
import { Checkbox, CodeEditor, Select } from "@humansignal/ui";
1919
import { toSnakeCase } from "strman";

web/apps/playground/.babelrc

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
{
2+
"presets": [
3+
[
4+
"@nx/react/babel",
5+
{
6+
"runtime": "automatic"
7+
}
8+
]
9+
],
10+
"plugins": []
11+
}

web/apps/playground/README.mdc

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
---
2+
description:
3+
globs:
4+
alwaysApply: false
5+
---
6+
# Playground
7+
8+
## Overview
9+
The LabelStudio Playground is a standalone, embeddable React application for editing and previewing LabelStudio XML labeling configurations. It is designed to be embedded via iframe in documentation or external web applications, providing a focused environment for working with XML-based labeling configs and live previewing the LabelStudio interface.
10+
11+
## Main Features
12+
13+
- **Live XML Config Editing:** Edit Label Studio XML configs in real time and instantly preview the result.
14+
- **Sample Data Generation:** Automatically generates sample data for all supported media types (image, audio, video, PDF, website, CSV, OCR, etc.) using public domain URLs (primarily from Wikimedia Commons). This ensures copyright-safe, always-accessible previews.
15+
- **Live Annotation Output:** The preview panel displays the current annotation as a live-updating JSON string, reflecting user interactions in real time.
16+
- **Sticky Bottom Panel:** The right preview panel ensures the bottom panel (annotation controls) is always visible and sticky, with the main preview area scrollable.
17+
- **Resizable Panels:** The left (editor) and right (preview) panels are resizable and fully responsive.
18+
- **Robust Error Handling:** Displays clear error messages for invalid configs, network issues, or MobX State Tree (MST) errors. All async and MST errors are handled gracefully to avoid UI crashes.
19+
20+
## Main Components
21+
22+
### 1. `PlaygroundApp`
23+
- **Location:** `src/components/PlaygroundApp.tsx`
24+
- **Role:** The main application component. Handles:
25+
- UI rendering and atom wiring only; all state is managed via Jotai atoms.
26+
- Reads and writes config, loading, error, interfaces state via atoms.
27+
- Uses utility functions for parsing URL parameters and interface options.
28+
- Renders the code editor and preview panels side by side using Tailwind CSS for layout.
29+
30+
### 2. `PlaygroundPreview`
31+
- **Location:** `src/components/PlaygroundPreview.tsx`
32+
- **Role:** Renders the live LabelStudio preview panel.
33+
- Receives all state as props (from atoms in PlaygroundApp).
34+
- Dynamically loads the `@humansignal/editor` package and instantiates a LabelStudio instance with the current config and interface options.
35+
- Handles cleanup of the LabelStudio instance on config/interface changes or unmount.
36+
- Observes MST annotation changes and updates a Jotai atom or local state with the serialized annotation JSON, which is displayed below the preview.
37+
- Displays loading and error states using Tailwind classes.
38+
39+
### 3. `main.tsx`
40+
- **Role:** Entry point. Mounts the `PlaygroundApp` to the DOM.
41+
42+
## State Management
43+
- All application state (config, loading, error, interfaces, annotation, sample task) is managed using Jotai atoms, defined in `src/atoms/configAtoms.ts`.
44+
- Components use the `useAtom` hook to read and write state.
45+
- This ensures a strict separation of state logic from UI, and enables easy extension and testing.
46+
47+
## Utility Functions
48+
- All logic for parsing URL parameters and interface options is placed in strict utility functions in `src/utils/query.ts`.
49+
- Sample data generation is handled in `src/utils/generateSampleTask.ts`.
50+
- Components import and use these utilities for all non-UI logic.
51+
52+
## Data Flow
53+
- On load, `PlaygroundApp` uses utility functions to parse URL parameters:
54+
- `?config` (base64-encoded XML config)
55+
- `?configUrl` (URL to fetch XML config)
56+
- `?interfaces` (comma-separated list of LabelStudio interface options)
57+
- The config, loading, error, interfaces, annotation, and sample task state are set via Jotai atoms.
58+
- The code editor is a controlled component, updating the config atom on change.
59+
- The preview panel receives the current config and interface options as props and re-renders the LabelStudio instance accordingly.
60+
- Annotation changes in the preview are observed and the serialized annotation is displayed live below the preview.
61+
62+
## MobX State Tree (MST) Integration
63+
- All MST model mutations (including cleanup) are performed via MST actions to avoid protection errors.
64+
- The annotation model includes a `cleanup` action for safe teardown, which is called from React cleanup.
65+
- Only plain objects (not MST models) are stored in React state or Jotai atoms.
66+
67+
## Underlying Libraries
68+
69+
### React
70+
- The app is built with React (function components, hooks, strict mode).
71+
- State and effects are managed with Jotai atoms and hooks.
72+
73+
### Jotai
74+
- Used for all state management (config, loading, error, interfaces, annotation, sample task).
75+
- Atoms are defined in `src/atoms/configAtoms.ts`.
76+
- Components use `useAtom` for state access and updates.
77+
78+
### Tailwind CSS
79+
- All layout, spacing, color, and typography is handled with Tailwind utility classes.
80+
- Only semantic and token-based Tailwind classes are used, following project rules.
81+
82+
### @humansignal/ui
83+
- Provides the `CodeEditor` component for XML editing.
84+
- Ensures consistent UI and design token usage across the app.
85+
86+
### @humansignal/editor
87+
- Provides the LabelStudio labeling interface for live preview.
88+
- Dynamically imported in the preview panel for performance and to avoid loading unnecessary code until needed.
89+
- The LabelStudio instance is created with the current config and interface options, and is destroyed/cleaned up on changes.
90+
91+
## URL-based API
92+
- The app can be configured via URL parameters:
93+
- `?config` (base64-encoded XML config string)
94+
- `?configUrl` (URL to fetch XML config)
95+
- `?interfaces` (comma-separated list of LabelStudio interface options)
96+
- This allows external documentation or apps to embed the playground with preloaded configs and custom preview options.
97+
98+
## Embeddability
99+
- The app is fully responsive and designed to be embedded via iframe.
100+
- All UI is self-contained and does not require authentication or external state.
101+
102+
## Extensibility
103+
- Components are split into single-file-per-component for maintainability, and all live under `src/components/`.
104+
- All state is managed via Jotai atoms in `src/atoms/`.
105+
- All logic is placed in strict utility functions in `src/utils/`.
106+
- The code editor and preview logic are decoupled, allowing for future enhancements (e.g., validation, additional preview options, custom data, etc).
107+
- The app can be extended to support more URL parameters, additional LabelStudio features, or integration with other HumanSignal libraries.
108+
- To add new sample data types, update `generateSampleTask.ts` with new logic and public domain URLs.
109+
- To customize annotation output, update the preview logic to observe and display additional MST state as needed.
110+
111+
## Directory Structure
112+
113+
```
114+
web/apps/playground/
115+
├── src/
116+
│ ├── atoms/ # Jotai atoms for state management
117+
│ ├── components/ # React components
118+
│ │ ├── BottomPanel/ # Data Input/Output Bottom panel component
119+
│ │ ├── EditorPanel/ # Labelling Config Editor panel component
120+
│ │ ├── PlaygroundApp/ # Main app component
121+
│ │ └── PreviewPanel/ # Labelling Preview panel component
122+
│ ├── utils/ # Utility functions
123+
│ ├── index.html # Entry HTML file
124+
│ └── main.tsx # Entry point
125+
├── .babelrc # Babel configuration
126+
├── jest.config.ts # Jest configuration
127+
├── project.json # Nx project configuration
128+
├── tsconfig.json # TypeScript configuration
129+
├── tsconfig.app.json # App-specific TypeScript configuration
130+
└── tsconfig.spec.json # Test-specific TypeScript configuration
131+
```
132+
133+
## Summary
134+
The Playground app is a modern, modular, and embeddable tool for experimenting with and sharing LabelStudio configs. It leverages the HumanSignal UI and editor libraries, is styled with Tailwind, uses Jotai for state, and is designed for easy integration into documentation and external web applications. It now features robust sample data generation, live annotation output, and safe MobX State Tree integration for a seamless developer experience.

web/apps/playground/jest.config.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
/* eslint-disable */
2+
export default {
3+
displayName: "playground",
4+
preset: "../../jest.preset.js",
5+
transform: {
6+
"^(?!.*\\.(js|jsx|ts|tsx|css|json)$)": "@nx/react/plugins/jest",
7+
"^.+\\.[tj]sx?$": ["babel-jest", { presets: ["@nx/react/babel"] }],
8+
},
9+
moduleFileExtensions: ["ts", "tsx", "js", "jsx"],
10+
moduleNameMapper: {
11+
"^apps/playground/(.*)$": "<rootDir>/$1",
12+
},
13+
coverageDirectory: "../../coverage/apps/playground",
14+
};

web/apps/playground/project.json

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
{
2+
"name": "playground",
3+
"$schema": "../../node_modules/nx/schemas/project-schema.json",
4+
"sourceRoot": "apps/playground/src",
5+
"projectType": "application",
6+
"targets": {
7+
"build": {
8+
"executor": "@nx/webpack:webpack",
9+
"outputs": ["{options.outputPath}"],
10+
"defaultConfiguration": "production",
11+
"options": {
12+
"compiler": "babel",
13+
"outputPath": "dist/apps/playground",
14+
"index": "apps/playground/src/index.html",
15+
"baseHref": "/",
16+
"main": "apps/playground/src/main.tsx",
17+
"tsConfig": "apps/playground/tsconfig.app.json",
18+
"assets": [],
19+
"styles": [],
20+
"scripts": [],
21+
"isolatedConfig": true,
22+
"webpackConfig": "webpack.config.js"
23+
},
24+
"configurations": {
25+
"development": {
26+
"extractLicenses": false,
27+
"optimization": false,
28+
"sourceMap": true,
29+
"vendorChunk": true
30+
},
31+
"production": {
32+
"fileReplacements": [
33+
{
34+
"replace": "apps/playground/src/environments/environment.ts",
35+
"with": "apps/playground/src/environments/environment.prod.ts"
36+
}
37+
],
38+
"optimization": true,
39+
"sourceMap": false,
40+
"namedChunks": false,
41+
"extractLicenses": true,
42+
"vendorChunk": false
43+
}
44+
}
45+
},
46+
"serve": {
47+
"executor": "@nx/webpack:dev-server",
48+
"defaultConfiguration": "development",
49+
"options": {
50+
"buildTarget": "playground:build",
51+
"port": 4200,
52+
"hmr": true
53+
},
54+
"configurations": {
55+
"development": {
56+
"buildTarget": "playground:build:development"
57+
},
58+
"production": {
59+
"buildTarget": "playground:build:production",
60+
"hmr": false
61+
}
62+
}
63+
},
64+
"serve-static": {
65+
"executor": "@nx/web:file-server",
66+
"options": {
67+
"buildTarget": "playground:build"
68+
}
69+
},
70+
"unit": {
71+
"executor": "@nx/jest:jest",
72+
"outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
73+
"options": {
74+
"jestConfig": "apps/playground/jest.config.ts",
75+
"passWithNoTests": true
76+
},
77+
"configurations": {
78+
"ci": {
79+
"ci": true,
80+
"codeCoverage": true
81+
}
82+
}
83+
}
84+
},
85+
"tags": []
86+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { atom } from "jotai";
2+
3+
export const defaultConfig = "<View>\n <!-- Paste your XML config here -->\n</View>";
4+
5+
export const configAtom = atom<string>(defaultConfig);
6+
export const loadingAtom = atom<boolean>(false);
7+
export const errorAtom = atom<string | null>(null);
8+
export const interfacesAtom = atom<string[]>(["side-column"]);
9+
export const showPreviewAtom = atom<boolean>(true);
10+
export const sampleTaskAtom = atom<any>({});
11+
export const annotationAtom = atom<any>([]);
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import type React from "react";
2+
import { forwardRef } from "react";
3+
import { useAtomValue } from "jotai";
4+
import { IconCollapseSmall, IconExpandSmall } from "@humansignal/icons";
5+
import { cnm } from "@humansignal/ui/utils/utils";
6+
import { annotationAtom, sampleTaskAtom } from "../../atoms/configAtoms";
7+
8+
export type BottomPanelRef = {
9+
handleAnnotationUpdate: (annotation: any) => void;
10+
};
11+
12+
interface BottomPanelProps {
13+
isCollapsed: boolean;
14+
setIsCollapsed: React.Dispatch<React.SetStateAction<boolean>>;
15+
}
16+
17+
const HEADER_HEIGHT = 33;
18+
19+
export const BottomPanel = forwardRef<BottomPanelRef, BottomPanelProps>(({ isCollapsed, setIsCollapsed }, ref) => {
20+
const currentAnnotation = useAtomValue(annotationAtom);
21+
const sampleTask = useAtomValue(sampleTaskAtom);
22+
23+
return (
24+
<div
25+
className={cnm("flex flex-col transition-all duration-200 min-h-0 min-w-0 h-full", {
26+
"border-t border-neutral-border": isCollapsed,
27+
})}
28+
>
29+
{/* Header (always visible, 33px) */}
30+
<div
31+
className="relative h-[33px] flex flex-row items-center bg-neutral-surface select-none"
32+
style={{ minHeight: HEADER_HEIGHT, maxHeight: HEADER_HEIGHT }}
33+
>
34+
<div className="flex flex-row w-full">
35+
<div className="flex-1 flex items-center font-semibold text-body-small px-4">Data Input</div>
36+
<div className="w-[1px] h-[33px] bg-neutral-border" />
37+
<div className="flex-1 flex items-center font-semibold text-body-small px-4">Data Output</div>
38+
</div>
39+
{/* Floating collapse/expand button */}
40+
<button
41+
type="button"
42+
aria-label={isCollapsed ? "Expand" : "Collapse"}
43+
onClick={() => setIsCollapsed(!isCollapsed)}
44+
className="lsf-button lsf-button_look_ lsf-collapsible-bottom-panel-toggle absolute right-[5px] top-1/2 -translate-y-1/2 !h-6 !w-6 !p-0 flex items-center justify-center !bg-transparent !border-none"
45+
style={{ zIndex: 10 }}
46+
>
47+
{isCollapsed ? <IconExpandSmall /> : <IconCollapseSmall />}
48+
</button>
49+
</div>
50+
{/* Panel content (only when not collapsed) */}
51+
{!isCollapsed && (
52+
<div className="flex flex-1 min-h-0">
53+
{/* Sample Data Panel */}
54+
<div className="flex-1 border-r border-neutral-border p-4 overflow-auto">
55+
<pre className="text-body-small whitespace-pre-wrap">{JSON.stringify(sampleTask.data, null, 2)}</pre>
56+
</div>
57+
{/* Annotation Output Panel */}
58+
<div className="flex-1 p-4 overflow-auto">
59+
<pre className="text-body-small whitespace-pre-wrap">
60+
{JSON.stringify(currentAnnotation || {}, null, 2)}
61+
</pre>
62+
</div>
63+
</div>
64+
)}
65+
</div>
66+
);
67+
});
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export { BottomPanel } from "./BottomPanel";

0 commit comments

Comments
 (0)