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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@danchin/direct-component

v0.1.0

Published

JSON-driven React UI compiler

Readme

direct-component

direct-component — экспериментальный JSON-driven React-компилятор UI. Он принимает декларативное описание дерева компонентов, подставляет параметры и состояние через шаблоны, валидирует структуру и рендерит готовый React-интерфейс.

Проект содержит библиотечный код в src/direct-component/ и showcase-приложение на Vite в src/App.tsx с примерами из src/examples/.

Быстрый старт

npm ci
npm run dev

Основные команды:

  • npm run dev — запустить Vite dev server.
  • npm run build — проверить TypeScript и собрать проект.
  • npm run lint — запустить ESLint.
  • npm run preview — открыть собранную версию локально.

Использование Compiler

Базовый сценарий — передать плоский список узлов, связи и внешние параметры:

import { Compiler } from "@danchin/direct-component";
import "@danchin/direct-component/styles.css";

import nodes from "./nodes.json";
import hierarchy from "./hierarchy.json";
import params from "./params.json";

export function Screen() {
  return <Compiler nodes={nodes} hierarchy={hierarchy} params={params} />;
}

Альтернатива — передать уже собранное дерево через spec:

<Compiler
  spec={{
    type: "vbox",
    children: [{ type: "title", text: "Hello" }],
  }}
/>

Формат JSON

Для экранов в плоском формате используются три файла:

  • nodes.json — массив узлов с уникальным id и type; остальные поля становятся props компонента.
  • hierarchy.json — массив связей [parentId, childId]; порядок связей задает порядок детей.
  • params.json — внешние данные для шаблонов.

Пример:

[
  { "id": "root", "type": "margin", "top": 16 },
  { "id": "main", "type": "vbox", "gap": 12 },
  { "id": "title", "type": "title", "text": "Профиль {{ userName }}" }
]
[
  ["root", "main"],
  ["main", "title"]
]

Компилятор проверяет, что у каждого узла есть уникальный id, все связи указывают на существующие узлы, в дереве есть ровно один корень и нет циклов.

Шаблоны, состояние и handlers

Шаблоны пишутся в строках через {{ ... }}. Значения по умолчанию берутся из params, а внутреннее состояние доступно через var:.

{
  "id": "label",
  "type": "label",
  "text": "Имя: {{ userName | var:name | def:\"Гость\" }}"
}

Поддерживаются pipe-фильтры для текста, чисел, дат, массивов, объектов и логики. Свои фильтры можно добавить через registerFilter.

Внешние обработчики передаются через handlers. Внешнее React-состояние можно связать через states, где ключ превращается в параметр и handler-сеттер:

<Compiler
  nodes={nodes}
  hierarchy={hierarchy}
  params={{ title: "Анкета" }}
  handlers={{ onReset: () => setName("Гость") }}
  states={{ name: [name, setName] }}
/>

Внутренние defaults объявляются узлом state, а изменение внутренних vars выполняется через stateBind.

Типы узлов

Доступные группы узлов:

  • layout: margin, panel, card, hbox, vbox, grid, scroll, tabs, group, fieldset, formRow.
  • display: label, text, title, hint, badge, status, iconText, progress, image.
  • input/action: button, input, textarea, select, checkbox, radioGroup, switch, slider, dateInput, numberInput, stateBind.
  • flow/data: branch, repeat, switchCase, case, fallback, state, computed, debugVars, debugParams.

Общие поля: class, style, visible, disabled, expandH, expandV, expandHWeight, expandVWeight.

Темы

Compiler принимает theme как имя пресета (default, compact, soft) или объект overrides:

<Compiler
  nodes={nodes}
  hierarchy={hierarchy}
  theme={{
    button: { className: "primary-button" },
    "button:hover": { className: "primary-button-hover" },
  }}
/>

Базовые стили находятся в src/direct-component/styles/direct-component.css.

Структура проекта

  • src/direct-component/ — библиотека: компилятор, registry, компоненты, шаблоны, фильтры, тема и валидация.
  • src/examples/ — JSON-примеры для showcase.
  • src/App.tsx — демо-приложение с переключением примеров и тем.
  • src/controls/ и src/template/ — ранняя/параллельная реализация, не основная публичная точка входа.
  • .cursor/rules/ — контекст и правила для Cursor Agent.

Публичный API экспортируется из src/direct-component/index.ts.