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

@decaf-ts/ui-decorators

v0.6.4

Published

Extension of decorator validation to ui elements to allow for web integration

Readme

Banner

User Interface Decorators

A TypeScript library that provides a declarative approach to UI rendering through model decorators. It extends the functionality of @decaf-ts/decorator-validation by adding UI rendering capabilities to models, allowing them to be automatically rendered as UI components with proper validation and styling.

The library offers a flexible rendering engine architecture that can be extended to support different UI frameworks (React, Angular, HTML5, etc.) while maintaining a consistent model-driven approach to UI development. It bridges the gap between data models and their visual representation, enabling developers to define UI behavior directly on their domain models.

Licence GitHub language count GitHub top language

Build & Test CodeQLSnyk Analysis Pages builder .github/workflows/release-on-tag.yaml

Open Issues Closed Issues Pull Requests Maintained

Forks Stars Watchers

Node Version NPM Version

Documentation available here

Description

The UI Decorators library is an extension of @decaf-ts/decorator-validation and @decaf-ts/db-decorators that provides a comprehensive framework for automatic model rendering in user interfaces. It enables a declarative approach to UI development by allowing developers to define how their data models should be rendered directly on the model classes and properties.

Core Functionality

  • Model Rendering: Extends the Model class with the ability to render itself as a UI component
  • Flexible Rendering Engine: Provides an abstract RenderingEngine class that can be implemented for different UI frameworks
  • Validation Integration: Automatically applies validation rules from @decaf-ts/decorator-validation to UI elements
  • CRUD Operation Support: Controls element visibility and behavior based on the current CRUD operation (Create, Read, Update, Delete)
  • List Rendering: Special support for rendering collections of models as lists with customizable item templates

Class Decorators

  • @uimodel(tag?, props?): Marks a class as a UI model and specifies how it should be rendered, including the HTML tag to use and additional properties
  • @renderedBy(engine): Specifies which rendering engine implementation should be used for a particular model
  • @uilistmodel(tag?, props?): Defines how a model should be rendered when it appears as an item in a list

Property Decorators

  • @uiprop(propName?, stringify?): Maps a model property to a UI component property, optionally with a different name or stringified
  • @uielement(tag, props?, serialize?): Maps a model property to a specific UI element with custom properties
  • @uilistprop(propName?, props?): Maps a model property containing a list to a list container component
  • @hideOn(...operations): Hides a property during specific CRUD operations
  • @hidden(): Completely hides a property in all UI operations

Rendering Engine

The abstract RenderingEngine class provides the foundation for implementing rendering strategies for different UI frameworks:

  • Type Translation: Converts between model types and HTML input types
  • Validation Handling: Applies validation rules from the model to UI elements
  • Field Definition Generation: Converts model metadata into UI field definitions
  • Engine Management: Registers and retrieves rendering engine implementations
  • Extensibility: Can be extended to support any UI framework or rendering strategy

Integration with Validation

The library seamlessly integrates with the validation system from @decaf-ts/decorator-validation, automatically applying validation rules to UI elements:

  • Required fields
  • Minimum and maximum values
  • Minimum and maximum length
  • Pattern matching
  • Type-specific validation (email, URL, date, password)
  • Custom validation rules

This integration ensures that UI components not only display data correctly but also enforce the same validation rules defined in the model.

How to Use

Basic Usage

Creating a UI Model

The most basic usage involves decorating a model class with @uimodel to make it renderable:

import { Model, attribute } from '@decaf-ts/decorator-validation';
import { uimodel, uielement } from '@decaf-ts/ui-decorators';

@uimodel()
class UserProfile extends Model {
  @attribute()
  @uielement('input', { type: 'text', placeholder: 'Enter your name' })
  name: string;

  @attribute()
  @uielement('input', { type: 'email', placeholder: 'Enter your email' })
  email: string;
}

// Create an instance
const user = new UserProfile();
user.name = 'John Doe';
user.email = '[email protected]';

// Render the model (the actual rendering depends on the registered rendering engine)
const renderedUI = user.render();

Customizing UI Model Rendering

You can customize how a model is rendered by providing a tag and properties to the @uimodel decorator:

import { Model, attribute } from '@decaf-ts/decorator-validation';
import { uimodel, uielement } from '@decaf-ts/ui-decorators';

@uimodel('div', { class: 'user-card', style: 'border: 1px solid #ccc; padding: 16px;' })
class UserCard extends Model {
  @attribute()
  @uielement('h2', { class: 'user-name' })
  name: string;

  @attribute()
  @uielement('p', { class: 'user-bio' })
  bio: string;
}

Specifying a Rendering Engine

You can specify which rendering engine to use for a particular model:

import { Model, attribute } from '@decaf-ts/decorator-validation';
import { uimodel, renderedBy, uielement } from '@decaf-ts/ui-decorators';

@uimodel()
@renderedBy('react')
class ReactComponent extends Model {
  @attribute()
  @uielement('input', { type: 'text' })
  title: string;
}

Mapping Properties to UI Elements

The @uielement decorator maps a model property to a specific UI element:

import { Model, attribute, required, minLength, maxLength } from '@decaf-ts/decorator-validation';
import { uimodel, uielement } from '@decaf-ts/ui-decorators';

@uimodel('form')
class LoginForm extends Model {
  @attribute()
  @required()
  @minLength(3)
  @maxLength(50)
  @uielement('input', { 
    type: 'text', 
    placeholder: 'Username', 
    class: 'form-control' 
  })
  username: string;

  @attribute()
  @required()
  @minLength(8)
  @uielement('input', { 
    type: 'password', 
    placeholder: 'Password', 
    class: 'form-control' 
  })
  password: string;

  @attribute()
  @uielement('button', { 
    type: 'submit', 
    class: 'btn btn-primary' 
  })
  submitButton: string = 'Login';
}

Mapping Properties to Component Properties

The @uiprop decorator maps a model property to a UI component property:

import { Model, attribute } from '@decaf-ts/decorator-validation';
import { uimodel, uiprop } from '@decaf-ts/ui-decorators';

@uimodel('user-profile-component')
class UserProfile extends Model {
  @attribute()
  @uiprop() // Will be passed as 'fullName' to the component
  fullName: string;

  @attribute()
  @uiprop('userEmail') // Will be passed as 'userEmail' to the component
  email: string;

  @attribute()
  @uiprop('userData', true) // Will be passed as stringified JSON
  userData: Record<string, any>;
}

Controlling Property Visibility

You can control when properties are visible using the @hideOn and @hidden decorators:

import { Model } from '@decaf-ts/decorator-validation';
import { uimodel, uielement, hideOn, hidden } from '@decaf-ts/ui-decorators';
import { OperationKeys } from '@decaf-ts/db-decorators';

@uimodel()
class User extends Model {
  @uielement('input', { type: 'text' })
  username: string;

  @uielement('input', { type: 'password' })
  @hideOn(OperationKeys.READ) // Hide during READ operations
  password: string;

  @uielement('input', { type: 'text' })
  @hidden() // Completely hidden in all operations
  internalId: string;
}

Rendering Lists of Models

You can render lists of models using the @uilistmodel and @uilistprop decorators:

import { Model, list } from '@decaf-ts/decorator-validation';
import { uimodel, uilistmodel, uilistprop, uielement } from '@decaf-ts/ui-decorators';

// Define a list item model
@uimodel()
@uilistmodel('li', { class: 'todo-item' })
class TodoItem extends Model {
  @uielement('span', { class: 'todo-text' })
  text: string;

  @uielement('input', { type: 'checkbox' })
  completed: boolean;
}

// Define a list container model
@uimodel('div', { class: 'todo-app' })
class TodoList extends Model {
  @uielement('h1')
  title: string = 'My Todo List';

  @list(TodoItem)
  @uilistprop('items', { class: 'todo-items-container' })
  items: TodoItem[];
}

// Usage
const todoList = new TodoList();
todoList.items = [
  new TodoItem({ text: 'Learn TypeScript', completed: true }),
  new TodoItem({ text: 'Build a UI with decorators', completed: false })
];

const renderedList = todoList.render();

Creating a Custom Rendering Engine

To implement a custom rendering engine for a specific UI framework, you need to extend the RenderingEngine abstract class:

import { Model } from '@decaf-ts/decorator-validation';
import { RenderingEngine, FieldDefinition } from '@decaf-ts/ui-decorators';

// Define the output type for your rendering engine
type ReactElement = any; // Replace with actual React element type

// Create a custom rendering engine for React
class ReactRenderingEngine extends RenderingEngine<ReactElement> {
  constructor() {
    super('react'); // Specify the engine flavor
  }

  // Initialize the engine (required abstract method)
  async initialize(...args: any[]): Promise<void> {
    // Import React or perform any other initialization
    this.initialized = true;
  }

  // Implement the render method (required abstract method)
  render<M extends Model>(
    model: M,
    globalProps: Record<string, unknown> = {},
    ...args: any[]
  ): ReactElement {
    // Convert the model to a field definition
    const fieldDef = this.toFieldDefinition(model, globalProps);

    // Convert the field definition to a React element
    return this.createReactElement(fieldDef);
  }

  // Helper method to create React elements
  private createReactElement(fieldDef: FieldDefinition<ReactElement>): ReactElement {
    // Implementation would use React.createElement or JSX
    // This is just a placeholder
    return {
      type: fieldDef.tag,
      props: {
        ...fieldDef.props,
        children: fieldDef.children?.map(child => this.createReactElement(child))
      }
    };
  }
}

// Register the custom rendering engine
new ReactRenderingEngine();

// Now models can specify to use this engine
@uimodel()
@renderedBy('react')
class ReactComponent extends Model {
  // ...
}

Integration with Validation

The UI decorators library automatically integrates with the validation system from @decaf-ts/decorator-validation:

import { Model, required, email, minLength, pattern } from '@decaf-ts/decorator-validation';
import { uimodel, uielement } from '@decaf-ts/ui-decorators';

@uimodel('form', { class: 'registration-form' })
class RegistrationForm extends Model {
  @required()
  @minLength(3)
  @uielement('input', { type: 'text', placeholder: 'Username' })
  username: string;

  @required()
  @email()
  @uielement('input', { type: 'email', placeholder: 'Email' })
  email: string;

  @required()
  @minLength(8)
  @pattern(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).*$/) // Requires lowercase, uppercase, and digit
  @uielement('input', { type: 'password', placeholder: 'Password' })
  password: string;

  // Validation will be automatically applied to the rendered UI elements
}

Complete Example

Here's a complete example showing how to use the UI decorators library to create a user registration form:

import { Model, attribute, required, email, minLength, maxLength, pattern } from '@decaf-ts/decorator-validation';
import { uimodel, uielement, renderedBy } from '@decaf-ts/ui-decorators';

@uimodel('form', { class: 'registration-form', id: 'user-registration' })
@renderedBy('html5') // Use the HTML5 rendering engine
class UserRegistration extends Model {
  @required()
  @minLength(2)
  @maxLength(50)
  @uielement('input', { 
    type: 'text', 
    placeholder: 'First Name',
    class: 'form-control'
  })
  firstName: string;

  @required()
  @minLength(2)
  @maxLength(50)
  @uielement('input', { 
    type: 'text', 
    placeholder: 'Last Name',
    class: 'form-control'
  })
  lastName: string;

  @required()
  @email()
  @uielement('input', { 
    type: 'email', 
    placeholder: 'Email Address',
    class: 'form-control'
  })
  email: string;

  @required()
  @minLength(8)
  @pattern(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/)
  @uielement('input', { 
    type: 'password', 
    placeholder: 'Password (min 8 chars, include uppercase, lowercase, number, and special char)',
    class: 'form-control'
  })
  password: string;

  @required()
  @uielement('select', { class: 'form-control' })
  country: string;

  @attribute()
  @uielement('textarea', { 
    placeholder: 'Tell us about yourself',
    class: 'form-control',
    rows: 4
  })
  bio: string;

  @uielement('input', { 
    type: 'checkbox',
    class: 'form-check-input'
  })
  acceptTerms: boolean = false;

  @uielement('button', { 
    type: 'submit',
    class: 'btn btn-primary'
  })
  submitButton: string = 'Register';
}

// Create an instance
const registration = new UserRegistration();

// Render the form
const form = registration.render();

// Check for validation errors
const errors = registration.hasErrors();
if (errors) {
  console.error('Validation errors:', errors);
}

This example demonstrates how to create a complete registration form with various input types and validation rules, all defined declaratively using decorators.

Coding Principles

  • group similar functionality in folders (analog to namespaces but without any namespace declaration)
  • one class per file;
  • one interface per file (unless interface is just used as a type);
  • group types as other interfaces in a types.ts file per folder;
  • group constants or enums in a constants.ts file per folder;
  • group decorators in a decorators.ts file per folder;
  • always import from the specific file, never from a folder or index file (exceptions for dependencies on other packages);
  • prefer the usage of established design patters where applicable:
    • Singleton (can be an anti-pattern. use with care);
    • factory;
    • observer;
    • strategy;
    • builder;
    • etc;

Related

decaf-ts decorator-validation db-decorators

Social

LinkedIn

Languages

TypeScript JavaScript NodeJS ShellScript

Getting help

If you have bug reports, questions or suggestions please create a new issue.

Contributing

I am grateful for any contributions made to this project. Please read this to get started.

Supporting

The first and easiest way you can support it is by Contributing. Even just finding a typo in the documentation is important.

Financial support is always welcome and helps keep both me and the project alive and healthy.

So if you can, if this project in any way. either by learning something or simply by helping you save precious time, please consider donating.

License

This project is licensed under the Mozilla Public License 2.0 (MPL-2.0). See ./LICENSE.md for a Fair Usage Addendum that explains when AGPL-3.0 applies (automated AI/Decaf MCP code generation and non-deterministic UI generation).

By developers, for developers...