Package Exports
- begin-widgets
- begin-widgets/types
Readme
✨ Begin Widgets ✨
Easily embed powerful workflow building and running capabilities into your web applications!
Begin Widgets provides Lit-based web components that let you:
- Visually build workflow templates with custom forms and steps.
- Run instances of those workflows, guiding users through steps.
- Integrate seamlessly into your existing application with a simple JavaScript API.
Perfect for onboarding flows, request processes, checklists, approvals, and any task requiring structured, sequential steps.
Installation
From npm (Recommended)
npm install begin-widgetsFrom CDN
<script src="https://unpkg.com/begin-widgets/dist/begin-widgets.umd.js"></script>Key Features & Benefits
- 🚀 Rapid Integration: Embed complex workflow UIs with just a few lines of JavaScript using
createBuilderandcreateRunner. - 🧩 Focused Builder (
builder-widget):- Clean, intuitive interface to create workflow templates with steps and form elements (questions, content, etc.).
- Drag-and-drop step reordering for easy workflow organization.
- Step-by-step template creation with title, description, and elements.
- Modern UI design with proper form validation and user feedback.
- 🏃♂️ Smooth Runner (
runner-widget):- Self-contained: Runs entirely from a single
Instanceobject snapshot. - Guides users step-by-step with clear progress indication (progress bar!).
- Includes basic validation for required fields.
- Provides clear event hooks (
onInstanceUpdated,onInstanceCompleted) for saving progress and final results.
- Self-contained: Runs entirely from a single
- 🏗️ Modern Web Components: Built with Lit for encapsulated, reusable, and framework-agnostic components.
- 🔒 Consistent Runs: Instances are snapshots of the workflow at creation time, ensuring that changes to the main workflow template don't break in-progress tasks.
- 🔌 Event-Driven: Easily hook into the workflow lifecycle using callbacks to save data to your backend, trigger notifications, or update your UI.
Core Concepts
- Workflow: The reusable blueprint or template for a process, containing steps and elements (form questions and content blocks).
- Instance: A specific, runnable execution of a Workflow, captured as a snapshot. It includes the exact steps/elements from the Workflow at the time of creation, plus current progress and any instance-specific details.
- Builder: The component (
<builder-widget>) used to createWorkflowtemplates with a focused, clean interface. - Runner: The component (
<runner-widget>) used to execute anInstance, presenting the steps and elements to the user.
Getting Started
Prerequisites
- Node.js (v18+ recommended)
- npm
Installation & Setup
- Clone:
git clone <your-repo-url> && cd begin-widgets - Install:
npm install
Development Workflow
This project supports two distinct modes for different use cases:
🔧 Development Mode
For active development with hot reload and fast iteration:
npm run dev- URL: http://localhost:5173/
- Features: Hot module replacement, TypeScript compilation, ES modules
- Use case: Active development, debugging, adding features
- How it works: Vite serves source files directly using ES modules
🚀 Production Preview Mode
For testing the built library as it would be distributed:
npm run build
npm run preview- URL: http://localhost:4173/
- Features: Optimized UMD bundle, production-ready assets
- Use case: Testing final builds, integration testing, demo purposes
- How it works: Creates a UMD bundle and serves the optimized HTML
Key Differences
| Aspect | Development (npm run dev) |
Production (npm run preview) |
|---|---|---|
| Loading | ES modules from /src/ |
UMD bundle from /dist/ |
| Speed | Fast startup, HMR | Slower startup, no HMR |
| Files | Source TypeScript files | Compiled JavaScript bundle |
| Debugging | Source maps, readable code | Minified bundle |
| Use Cases | Development, debugging | Final testing, demos |
Demo Features
Both modes include a demo with:
- Builder Tab: Create workflow templates with steps and form elements (questions, content, etc.) using an intuitive interface
- Runner Tab: Execute workflow instances with step-by-step progression
- Sample Data: Pre-loaded workflows and instances for testing
Build Process Details
The build process includes a custom script that:
- TypeScript Compilation:
tsccompiles source files - Bundle Creation:
vite buildcreates the UMD bundle - HTML Processing:
scripts/build-html.jsconverts the HTML to use the UMD bundle
Quick Usage Example
From npm (Recommended)
npm install begin-widgetsimport { createBuilder, createRunner } from "begin-widgets";
// Initialize Builder
createBuilder("workflow-builder", {
onWorkflowCreated: (workflowData) => {
console.log("New workflow template created:", workflowData);
// Save the workflow template to your backend
saveWorkflowTemplate(workflowData);
},
onWorkflowDeleted: (workflowId) => {
console.log("Workflow deleted:", workflowId);
},
onWorkflowUpdated: (workflowData) => {
console.log("Workflow updated:", workflowData);
},
});
// Initialize Runner
const instanceData = await fetchInstanceFromBackend("instance-id-123");
if (instanceData && instanceData.steps) {
createRunner("workflow-runner", {
instance: instanceData,
onInstanceUpdated: (detail) => {
console.log("Progress Update:", detail.data);
// Optionally save partial progress
savePartialInstanceProgress(detail.instanceId, detail.data);
},
onInstanceCompleted: (detail) => {
console.log("Workflow Complete:", detail.data);
// Save the final, complete instance data
saveCompletedInstance(detail.instanceId, detail.data);
},
});
}From CDN (UMD Bundle)
Include Script:
<script src="https://unpkg.com/begin-widgets/dist/begin-widgets.umd.js"></script>
Add Mount Points:
<div id="workflow-builder"></div> <div id="workflow-runner"></div>
Initialize with JavaScript:
document.addEventListener('DOMContentLoaded', () => { // --- Initialize Builder --- if (Begin.createBuilder) { Begin.createBuilder('workflow-builder', { // Callback when a workflow template is saved onSave: (workflowData) => { console.log('New workflow template created:', workflowData); // Save the workflow template to your backend saveWorkflowTemplate(workflowData); }, onCancel: () => { console.log('Template creation cancelled'); // Handle cancellation (e.g., redirect to workflows list) } }); } // --- Initialize Runner --- if (Begin.createRunner) { // Fetch a specific instance object from your backend. // This instance object MUST contain the 'steps' array. const instanceData = await fetchInstanceFromBackend('instance-id-123'); if (instanceData && instanceData.steps) { Begin.createRunner('workflow-runner', { instance: instanceData, onInstanceUpdated: (detail) => { console.log('Progress Update:', detail.data); // Optionally save partial progress savePartialInstanceProgress(detail.instanceId, detail.data); }, onInstanceCompleted: (detail) => { console.log('Workflow Complete:', detail.data); // Save the final, complete instance data saveCompletedInstance(detail.instanceId, detail.data); } }); } else { console.error("Failed to load instance or instance missing steps."); } } // Placeholder functions for backend interaction async function fetchInstanceFromBackend(id) { /* ... */ return {}; } async function saveWorkflowTemplate(data) { /* ... */ } async function savePartialInstanceProgress(id, data) { /* ... */ } async function saveCompletedInstance(id, data) { /* ... */ } });
For ES Module Projects
If you're integrating into a modern build system that supports ES modules:
import { createBuilder, createRunner } from "./src/lib.ts";
// Use createBuilder and createRunner directly
createBuilder("builder-container", {
onSave: (workflowData) => console.log("Template saved:", workflowData),
onCancel: () => console.log("Template creation cancelled"),
});
createRunner("runner-container", { instance: instanceData });TypeScript Support
Begin Widgets includes comprehensive TypeScript definitions for full type safety and developer experience.
Installing Types
When you install begin-widgets from npm, the TypeScript declaration files are automatically included:
npm install begin-widgetsImporting Types
Option 1: Import Types with Functions (Recommended)
import {
createBuilder,
createRunner,
type Workflow,
type Instance,
type Step,
type StepElement,
type QuestionElement,
type ContentElement,
} from "begin-widgets";
// Use the types for type safety
const myWorkflow: Workflow = {
id: "my-workflow",
name: "My Workflow",
steps: [],
};
const myInstance: Instance = {
id: "my-instance",
workflowId: "my-workflow",
name: "My Instance",
status: "active",
createdAt: new Date(),
updatedAt: new Date(),
steps: [],
completedSteps: [],
};Option 2: Import Types Only
import type {
Workflow,
Instance,
Step,
StepElement,
QuestionElement,
ContentElement,
QuestionResponse,
StepAssignment,
BuilderConfig,
RunnerConfig,
} from "begin-widgets";Option 3: Dedicated Types Entry Point
import type {
Workflow,
Instance,
StepElement,
QuestionElement,
ContentElement,
BuilderConfig,
RunnerConfig,
} from "begin-widgets/types";Available Types
| Type | Description |
|---|---|
Workflow |
Complete workflow template definition |
Instance |
Workflow instance with data and progress |
Step |
Individual workflow step |
StepElement |
Union of all possible step elements |
QuestionElement |
Form question element |
ContentElement |
Content/display element |
Question |
(Deprecated) Legacy question type |
QuestionResponse |
User's answer to a question |
StepAssignment |
Who a step is assigned to |
StepStatus |
Current status of a step |
BuilderConfig |
Configuration for the builder widget |
RunnerConfig |
Configuration for the runner widget |
Note:
Questionis deprecated and only included for legacy support. UseQuestionElementfor all new development.
JavaScript Projects with JSDoc
For JavaScript projects, you can still get type hints using JSDoc:
/**
* @typedef {import('begin-widgets').Workflow} Workflow
* @typedef {import('begin-widgets').Instance} Instance
*/
/**
* @param {Workflow} workflow
* @param {Instance} instance
*/
function processWorkflow(workflow, instance) {
// Full intellisense and type checking here
console.log(workflow.name);
console.log(instance.status);
}UMD Bundle with Types
When using the UMD bundle directly in the browser, you can still import types separately for TypeScript projects:
<!-- Runtime: UMD bundle -->
<script src="https://unpkg.com/begin-widgets/dist/begin-widgets.umd.js"></script>
<script>
// Runtime usage
const { createBuilder, createRunner } = Begin;
</script>// Types: Import separately in TypeScript files
import type { Workflow, Instance } from "begin-widgets";Type Safety Benefits
- Intellisense: Full autocomplete in VS Code, WebStorm, and other IDEs
- Compile-time Checking: Catch errors before runtime
- Documentation: Types serve as inline documentation
- Refactoring: Safe refactoring with type checking
- Zero Runtime Cost: Types are compile-time only, no bundle size impact
Project Structure
begin-widgets/
├── src/
│ ├── models.ts # TypeScript interfaces
│ ├── lib.ts # Main library API
│ ├── builder-widget.ts # Workflow template builder component
│ ├── runner-widget.ts # Workflow runner component
│ ├── styles/ # Organized CSS styles for components
│ │ ├── base-styles.ts
│ │ ├── form-styles.ts
│ │ ├── section-styles.ts
│ │ ├── step-styles.ts
│ │ ├── modal-styles.ts
│ │ └── index.ts
│ └── main.ts # Entry point for development
├── scripts/
│ └── build-html.js # Build script for production HTML
├── dist/ # Generated files (after build)
│ ├── begin-widgets.umd.js
│ └── index.html
├── index.html # Development HTML (ES modules)
├── vite.config.js # Vite configuration
└── package.jsonDevelopment Commands
# Start development server with hot reload
npm run dev
# Build the production bundle
npm run build
# Preview the production build
npm run preview
# Run tests (placeholder)
npm testTroubleshooting
"Begin library not found" Error
- In Development: Make sure you're using
npm run dev, notnpm run preview - In Production: Make sure you ran
npm run buildbeforenpm run preview
Module Loading Issues
- Development mode uses ES modules and requires a modern browser
- Production mode uses UMD bundle and works in older browsers
Build Errors
- Ensure TypeScript compiles without errors:
npx tsc --noEmit - Check that all imports are correctly typed and available
Let Begin Widgets streamline your application's workflows!