npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

drill-widgets

v2.7.17

Published

Easily embed powerful workflow building and running capabilities into your web applications with Lit-based web components. Includes HTML export for server-side PDF generation.

Readme

✨ Drill Widgets ✨

Easily embed powerful workflow building and running capabilities into your web applications!

Drill 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

npm install drill-widgets

Key Features & Benefits

  • 🚀 Rapid Integration: Embed complex workflow UIs with just a few lines of JavaScript using createBuilder and createRunner.
  • 🧩 Focused Builder (builder-widget):
    • Clean, intuitive interface to create workflow templates with steps and form elements
    • 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
    • Support for multiple question types and content elements
  • 🏃‍♂️ Smooth Runner (runner-widget):
    • Self-contained: Runs entirely from a single Instance object snapshot
    • Multiple execution modes: Default, Preview, Admin, View-Only, and Print modes for different use cases
    • Guides users step-by-step with clear progress indication
    • Includes comprehensive validation for required fields
    • Provides clear event hooks (onInstanceUpdated, onSignatureCaptured, onFileUploaded) for saving progress and final results
    • Responsive design that adapts to different screen sizes
  • 🏗️ 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 create Workflow templates with a focused, clean interface.
  • Runner: The component (<runner-widget>) used to execute an Instance, presenting the steps and elements to the user.

Runner Modes

The Runner widget supports different distinct modes for different use cases:

Default Mode

Purpose: Standard workflow execution with full functionality.

Configuration:

createRunner("runner-container", {
  instance: instanceData, // Required: Instance object
  mode: "default", // Optional: Default if not specified
  // ... other options
});

Features:

  • Data Persistence: Form data is automatically saved to localStorage
  • Validation: Required field validation runs on each step
  • Step Completion Tracking: Progress is tracked and steps are marked as completed
  • Callbacks: All callbacks fire (signature capture, file upload, etc.)
  • Smart Navigation: Next button progresses through assigned steps only
  • Transparent Unassigned Steps: Clickable sidebar access to view unassigned steps in read-only mode
  • Assignment-Based Interaction: Full editing for assigned steps, read-only viewing for unassigned steps
  • Next/Submit Buttons: Visible only when viewing assigned steps

Use Cases:

  • Production workflow execution
  • User onboarding processes
  • Approval workflows
  • Collaborative workflows where users need transparency into other steps
  • Any scenario requiring data persistence, validation, and step-based assignments

Default Mode: Transparent Unassigned Step Viewing

In default mode, users can now click on any step in the sidebar for full workflow transparency:

Assigned Steps (Full Mode):

  • Full interaction: Edit, validate, save, and progress through workflow
  • Navigation buttons: Next/Save/Submit buttons are visible
  • Data persistence: Changes are saved and callbacks fire
  • 🎯 Badge shows: "Assigned"

Unassigned Steps (Read-Only Mode):

  • 👁️ View-only access: Can see existing responses and form structure
  • No interaction: All inputs are disabled and read-only
  • No buttons: Next/Save/Submit buttons are hidden
  • No data changes: Cannot modify or save any data
  • 🏷️ Badge shows: "Not Assigned"

Next Button Behavior:

  • The Next button still progresses through assigned steps only
  • Clicking unassigned steps is for viewing/transparency only
  • Users can freely navigate back to their assigned workflow

This provides complete workflow transparency while maintaining assignment boundaries and data integrity.

Preview Mode

Purpose: Interactive preview of workflow templates without data persistence.

Configuration:

createRunner("runner-container", {
  workflow: workflowData, // Required: Workflow object (not Instance)
  mode: "preview", // Required: Must be explicitly set
  // ... other options
});

Features:

  • Interactive Inputs: Users can interact with all form elements
  • No Data Saving: Form data is not persisted (no localStorage usage)
  • No Validation: Required field validation is disabled
  • Free Navigation: Users can click any step in the sidebar to navigate freely
  • No Callbacks: Signature and file upload callbacks are disabled
  • No Navigation Buttons: Next/Submit buttons are hidden
  • Same Visual Layout: Identical appearance to default mode

Use Cases:

  • Workflow template preview
  • User experience testing
  • Stakeholder demonstrations
  • Template review and approval processes

Admin Mode

Purpose: Administrative access for workflow management with unrestricted navigation and step-by-step saving.

Configuration:

createRunner("runner-container", {
  instance: instanceData, // Required: Instance object
  mode: "admin", // Required: Must be explicitly set
  currentUser: userData, // Required: User with admin access
  // ... other options
});

Features:

  • Unrestricted Navigation: Access any step regardless of assignment or completion status
  • Step-by-Step Saving: "Save" button (instead of "Next") allows saving progress without advancing
  • All Callbacks Active: Signature capture, file upload, and instance update callbacks fire normally
  • Assignment Bypass: Can view and edit steps not assigned to current user
  • Data Persistence: Form data is saved to localStorage
  • Post-Submission Access: Can still navigate and edit after workflow submission
  • Validation Active: Required field validation still applies

Use Cases:

  • Workflow administration and troubleshooting
  • Helping users complete stuck workflows
  • Data correction and updates
  • Workflow testing and QA
  • Support team assistance

View-Only Mode

Purpose: Read-only viewing of completed workflow data with pre-filled responses displayed as non-editable content.

Configuration:

createRunner("runner-container", {
  instance: completedInstanceData, // Required: Instance with responses
  mode: "view-only", // Required: Must be explicitly set
  currentUser: userData, // Optional: For display purposes
  // ... other options
});

Features:

  • Free Navigation: Navigate to any step freely (like admin mode)
  • Pre-filled Display: All form inputs show existing response data
  • All Inputs Disabled: No editing possible - purely read-only
  • File/Signature Links: File uploads and signatures display as clickable links
  • No Action Buttons: No Next/Save/Submit buttons visible
  • No Data Persistence: No localStorage usage or data saving
  • No Callbacks: Callbacks are disabled (read-only mode)
  • Post-Submission View: Perfect for viewing submitted/completed workflows

Use Cases:

  • Viewing completed workflow submissions
  • Audit trails and compliance documentation
  • Historical workflow data review
  • Sharing completed forms with stakeholders
  • Read-only workflow previews for approval

Print Mode

Purpose: Print-optimized display of completed workflow data with all steps shown on one continuous page.

Configuration:

createRunner("runner-container", {
  instance: completedInstanceData, // Required: Instance with responses
  mode: "print", // Required: Must be explicitly set
  currentUser: userData, // Optional: For display purposes
  // ... other options
});

Features:

  • Single Page Layout: All workflow steps displayed continuously on one page
  • No Sidebar: Clean layout without step navigation for optimal printing
  • Pre-filled Display: All form inputs show existing response data
  • All Inputs Disabled: No editing possible - purely read-only
  • Detailed File Information: File uploads show filename, size, type, and modification date
  • Print-Optimized Styling: Special CSS for clean printing with proper page breaks
  • No Action Buttons: No interactive elements that don't work in print
  • No Data Persistence: No localStorage usage or data saving
  • No Callbacks: Callbacks are disabled (read-only mode)

File Display Enhancement:

  • File Info Objects: Shows detailed metadata (filename, size, type, date)
  • URL References: Extracts filename and type from URLs automatically
  • Print-Friendly: No non-functional buttons or links

Use Cases:

  • Generating PDF documents of completed workflows
  • Physical document printing for records
  • Compliance documentation requiring paper copies
  • Executive summaries and reports
  • Archival purposes

Mode Comparison

| Feature | Default Mode | Preview Mode | Admin Mode | View-Only Mode | Print Mode | | -------------------------- | -------------------------------------------------------- | --------------------- | ---------------------- | -------------------------------- | -------------------------------- | | Data Source | Instance object | Workflow object | Instance object | Instance object (with responses) | Instance object (with responses) | | Data Persistence | ✅ localStorage | ❌ None | ✅ localStorage | ❌ None | ❌ None | | Validation | ✅ Required fields | ❌ Disabled | ✅ Required fields | ❌ N/A (read-only) | ❌ N/A (read-only) | | Step Navigation | 🔄 Smart (assigned: restricted, unassigned: view-only) | ✅ Free (any step) | ✅ Free (any step) | ✅ Free (any step) | ❌ Single page view | | Input Editing | 🔄 Conditional (assigned: enabled, unassigned: disabled) | ✅ Enabled | ✅ Enabled | ❌ Disabled (read-only) | ❌ Disabled (read-only) | | Callbacks | ✅ All callbacks fire (assigned steps only) | ❌ Callbacks disabled | ✅ All callbacks fire | ❌ Callbacks disabled | ❌ Callbacks disabled | | Navigation Buttons | 🔄 Conditional (visible for assigned steps only) | ❌ Hidden | ✅ Save button visible | ❌ Hidden | ❌ Hidden | | Assignment Checks | ✅ Enforced | ❌ Bypassed | ❌ Bypassed | ❌ Bypassed | ❌ Bypassed | | Post-Submission Access | ❌ Blocked | ✅ Always available | ✅ Always available | ✅ Always available | ✅ Always available | | File/Signature Display | Form inputs | Form inputs | Form inputs | 🔗 Clickable links | 📄 Detailed info display | | Layout | Sidebar + single step | Sidebar + single step | Sidebar + single step | Sidebar + single step | 📄 All steps on one page | | Primary Use Case | Production execution | Template preview | Admin management | Completed data viewing | Document printing |

Supported Elements

Question Elements (Form Inputs)

| Type | Description | Features | | ------------- | ---------------------- | ------------------------------------------------------ | | text_input | Single-line text input | Placeholder text, validation | | textarea | Multi-line text area | Resizable, placeholder text | | select | Dropdown selection | Multiple options, placeholder | | number | Numeric input | Number validation | | radio | Radio button group | Multiple options, single selection | | checkbox | Checkbox input | Single checkbox or checkbox group | | date | Date picker | Date validation | | file_upload | File upload | File selection, 5MB limit, client callback | | signature | Digital signature pad | SVG output, responsive canvas, callback on next/submit |

Content Elements (Display Only)

| Type | Description | Features | | ---------- | ------------------ | -------------------------- | | text | Plain text content | Simple text display | | markdown | Markdown content | Headers, lists, formatting | | html | HTML content | Custom HTML rendering | | divider | Visual separator | Optional caption | | image | Image display | URL, alt text, caption | | video | Video display | URL, caption | | file | File display | URL, caption |

Features

  • Validation: Required field validation for all question types
  • Responsive Design: All elements adapt to different screen sizes
  • Accessibility: Proper ARIA labels and keyboard navigation
  • Type Safety: Full TypeScript support for all element types
  • Digital Signatures: Responsive signature pad with SVG output and data URL generation. Signature callbacks are triggered when users click "Next" or "Submit" to capture the final signature data.
  • Multiple Signatures: Support for multiple signature elements on the same form
  • File Uploads: File selection with 5MB limit. File upload callbacks are triggered immediately when a file is selected.
  • Progress Tracking: Real-time progress updates and completion tracking

Getting Started

Prerequisites

  • Node.js (v18+ recommended)
  • npm

Installation & Setup

  1. Clone: git clone <your-repo-url> && cd drill-widgets
  2. 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:

  1. TypeScript Compilation: tsc compiles source files
  2. Bundle Creation: vite build creates the UMD bundle
  3. HTML Processing: scripts/build-html.js converts the HTML to use the UMD bundle

Quick Usage Example

From npm (Recommended)

npm install drill-widgets
import { createBuilder, createRunner } from "drill-widgets";

// Initialize Builder
createBuilder("workflow-builder", {
  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 (Default Mode)
const instanceData = await fetchInstanceFromBackend("instance-id-123");

if (instanceData && instanceData.steps) {
  createRunner("workflow-runner", {
    instance: instanceData,
    mode: "default", // Optional: Default if not specified
    onInstanceUpdated: (detail) => {
      console.log("Progress Update:", detail);
      // Save progress data (for both step updates and final submission)
      saveInstanceProgress(detail.instanceId, detail);

      // Check if this is the final submission (no current step)
      if (!detail.currentStep) {
        console.log("Workflow Complete!");
      }
    },
    onSignatureCaptured: (detail) => {
      console.log("Signature captured:", detail.questionId);
      console.log("Instance ID:", detail.instanceId);
      console.log("Step ID:", detail.stepId);
      console.log("SVG Data:", detail.svgData);
      console.log("Data URL:", detail.dataURL);
      // Save signature data to your backend
      // Note: This callback is triggered when user clicks "Next" or "Submit"
      saveSignatureData(detail.instanceId, detail.questionId, detail.svgData, detail.dataURL);
    },
    onFileUploaded: (detail) => {
      console.log("File uploaded:", detail.questionId);
      console.log("Instance ID:", detail.instanceId);
      console.log("Step ID:", detail.stepId);
      console.log("File name:", detail.fileName);
      console.log("File size:", detail.fileSize);
      console.log("File type:", detail.fileType);
      console.log("File object:", detail.file);
      // Handle file upload to your backend/storage
      // Note: This callback is triggered immediately when a file is selected
      handleFileUpload(detail.instanceId, detail.questionId, detail.file);
    },
  });
}

// Initialize Runner (Preview Mode)
const workflowData = await fetchWorkflowFromBackend("workflow-id-456");

if (workflowData && workflowData.steps) {
  createRunner("workflow-preview", {
    workflow: workflowData, // Note: workflow, not instance
    mode: "preview", // Required for preview mode
    onSignatureCaptured: (detail) => {
      console.log("Preview: Signature captured:", detail.questionId);
      console.log("Preview: Instance ID:", detail.instanceId);
      console.log("Preview: Step ID:", detail.stepId);
      // Callbacks are disabled in preview mode, but still available for logging
    },
    onFileUploaded: (detail) => {
      console.log("Preview: File uploaded:", detail.questionId);
      console.log("Preview: Instance ID:", detail.instanceId);
      console.log("Preview: Step ID:", detail.stepId);
      console.log("Preview: File name:", detail.fileName);
      // Callbacks are disabled in preview mode, but still available for logging
    },
  });
}

Loading State

The Runner widget supports a loading state that can be used with any mode to show a loading indicator and disable user interaction while data is being processed or fetched.

Configuration:

const runnerWidget = createRunner("runner-container", {
  instance: instanceData,
  mode: "default",
  isLoading: true, // Shows loading spinner and disables step navigation
  currentUser: userData,
  onInstanceUpdated: (detail) => {
    console.log("Progress:", detail);
  },
});

// Update loading state dynamically
runnerWidget.isLoading = false; // Hide loading spinner and re-enable navigation

Features:

  • Loading Spinner: Displays an animated spinner with "Loading..." text
  • Disabled Navigation: All step navigation (sidebar and mobile) is disabled
  • Visual Overlay: Semi-transparent overlay covers the entire widget
  • Dynamic Control: Can be toggled on/off programmatically at any time
  • Mode Compatible: Works with all runner modes (default, preview, admin, view-only, print)

Use Cases:

  • Loading workflow data from backend
  • Processing form submissions
  • Saving progress to external systems
  • Waiting for validation responses
  • Any asynchronous operation that requires user to wait

View-Only Mode: File and Signature Links

In view-only mode, file uploads and signatures are displayed as clickable links instead of form inputs. This allows users to view and download the actual files and signatures that were submitted:

Print Mode: Enhanced File and Signature Display

In print mode, file uploads and signatures are displayed with detailed information instead of interactive elements, making them perfect for printed documents:

File Upload Display:

  • File Info Objects: Shows complete metadata including filename, size (human-readable), file type, and modification date
  • URL References: Automatically extracts filename and file type from URLs when only URL is available
  • Print-Friendly Format: Clean, structured display without any interactive elements

Signature Display:

  • Embedded Images: Signatures are displayed as images directly in the document
  • Fallback Handling: Graceful handling of missing or corrupted signature data
  • No Interactive Elements: Pure display mode suitable for printing

Example Print Mode File Display:

📎 File: contract_agreement.pdf
📏 Size: 2.3 MB
📄 Type: PDF Document
📅 Modified: 12/15/2024, 2:30:15 PM
// Example: Instance with file upload and signature responses
const completedInstanceData = {
  id: "inst-123",
  workflowId: "wf-onboarding",
  name: "John Doe Onboarding",
  status: "completed",
  steps: [
    {
      id: "step-1",
      title: "Document Upload",
      responses: [
        {
          elementId: "resume-upload",
          value: "https://storage.example.com/files/john-doe-resume.pdf", // File URL
          answeredAt: new Date("2024-01-15T10:30:00Z"),
        },
        {
          elementId: "signature-pad",
          value: "https://storage.example.com/signatures/john-doe-sig.svg", // Signature URL directly in value
          answeredAt: new Date("2024-01-15T10:35:00Z"),
        },
      ],
      elements: [
        {
          id: "resume-upload",
          type: "file_upload",
          label: "Upload Resume",
          required: true,
        },
        {
          id: "signature-pad",
          type: "signature",
          label: "Digital Signature",
          required: true,
        },
      ],
    },
  ],
  completedSteps: ["step-1"],
};

// When rendered in view-only mode:
// - File upload shows: "📎 filename.pdf" (clickable link that opens file in new tab)
// - Signature shows: embedded signature image (same as print mode)

HTML Export Utility

Drill Widgets includes a powerful HTML export utility that generates print-ready HTML from workflow instances. This is perfect for server-side PDF generation, email reports, and documentation.

Overview

The generateInstanceHTML() function takes a workflow Instance object and produces complete HTML that matches the appearance of the runner widget's print mode exactly. By default, it renders only the workflow steps and elements (just like print mode). Optionally, you can add metadata headers with instance information.

Basic Usage

import { generateInstanceHTML } from "drill-widgets";

const result = generateInstanceHTML(myInstance);
console.log(result.html); // Complete HTML string ready for PDF generation

With Options

const result = generateInstanceHTML(myInstance, {
  title: "Employee Onboarding Report",
  showTimestamps: true, // Add metadata header (not in print mode)
  customCSS: `
    .print-layout { 
      font-family: 'Times New Roman', serif; 
    }
  `,
});

PDF Generation Example

const puppeteer = require("puppeteer");

async function generatePDF(instance) {
  const result = generateInstanceHTML(instance, {
    title: "Workflow Report",
    showTimestamps: true,
  });

  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  await page.setContent(result.html, { waitUntil: "networkidle0" });
  await page.pdf({
    path: "./report.pdf",
    format: "A4",
    printBackground: true,
    margin: { top: "20mm", right: "20mm", bottom: "20mm", left: "20mm" },
  });

  await browser.close();
}

Server-Side Usage

const express = require("express");
const { generateInstanceHTML } = require("drill-widgets");

app.get("/report/:instanceId", async (req, res) => {
  const instance = await getInstanceFromDatabase(req.params.instanceId);

  const result = generateInstanceHTML(instance, {
    title: `Report: ${instance.name}`,
    showTimestamps: true,
  });

  res.setHeader("Content-Type", "text/html");
  res.send(result.html);
});

Features

  • Exact Print Mode Replica - Matches runner widget print mode exactly
  • All Question Types - Text, select, radio, checkbox, file uploads, signatures
  • File Metadata - Shows filename, size, type, modification dates
  • Signature Images - Embedded signatures from provided URLs
  • PDF-Ready - Print media queries, page breaks, embedded CSS
  • Server-Side Compatible - No browser dependencies, works in Node.js
  • Zero Dependencies - Pure HTML/CSS output

API Reference

interface HTMLExportOptions {
  title?: string; // Custom document title (default: instance.name)
  includeStyles?: boolean; // Include embedded CSS (default: true)
  customCSS?: string; // Additional CSS to inject
  showTimestamps?: boolean; // Show instance metadata header (default: false)
}

interface HTMLExportResult {
  html: string; // Complete HTML document
  title: string; // Document title used
  generatedAt: Date; // Generation timestamp
}

TypeScript Support

Drill Widgets includes comprehensive TypeScript definitions for full type safety and developer experience.

Installing Types

When you install drill-widgets from npm, the TypeScript declaration files are automatically included:

npm install drill-widgets

Importing Types

Option 1: Import Types with Functions (Recommended)

import {
  createBuilder,
  createRunner,
  type Workflow,
  type Instance,
  type Step,
  type StepElement,
  type QuestionElement,
  type ContentElement,
} from "drill-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",
  steps: [],
  completedSteps: [],
};

Option 2: Import Types Only

import type {
  Workflow,
  Instance,
  Step,
  StepElement,
  QuestionElement,
  ContentElement,
  QuestionResponse,
  StepAssignment,
  BuilderConfig,
  RunnerConfig,
} from "drill-widgets";

Option 3: Dedicated Types Entry Point

import type {
  Workflow,
  Instance,
  StepElement,
  QuestionElement,
  ContentElement,
  BuilderConfig,
  RunnerConfig,
} from "drill-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 | | 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 | | Visibility | Element visibility rules | | VisibilityRule | Individual visibility condition |

Note: The Question type is deprecated and only included for legacy support. Use QuestionElement for all new development.

JavaScript Projects with JSDoc

For JavaScript projects, you can still get type hints using JSDoc:

/**
 * @typedef {import('drill-widgets').Workflow} Workflow
 * @typedef {import('drill-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);
}

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

drill-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)
│   ├── drill-widgets.umd.js
│   └── index.html
├── index.html             # Development HTML (ES modules)
├── vite.config.js         # Vite configuration
└── package.json

Development 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 test

Troubleshooting

"Drill library not found" Error

  • In Development: Make sure you're using npm run dev, not npm run preview
  • In Production: Make sure you ran npm run build before npm 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 Drill Widgets streamline your application's workflows!