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

@alexgyver/component

v1.4.0

Published

Simple HTML&SVG element builder

Readme

Component.js

Библиотека для создания и настройки DOM/SVG элементов как JS объектов

npm i @alexgyver/component

Дока

Component

/**
 * Создать компонент и поместить его в переменную $root
 * @param {string} tag html tag элемента
 * @param {object} data параметры
 */
EL(tag, data = {}, svg = false);

/**
 * Создать компонент
 * @param {string} tag html tag элемента
 * @param {object} data параметры
 * @returns {Node}
 * tag {string} - тег html элемента. Если 'svg' - включится режим SVG на детей
 * context {object} - контекст для параметра 'var' и вызовов, прокидывается в детей. Если указан явно как null - прерывает проброс
 * parent - {Element} добавляет компонент к указанному элементу
 * text {string} - добавить в textContent
 * html {string} - добавить в innerHTML
 * class {string | Array} - добавить в className
 * style {string | object} - объект в виде { padding: '0px', ... } или строка css стилей
 * push {array} - добавить к указанному массиву
 * var | $ {string} - создаёт переменную $имя в указанном контексте
 * events {object} - добавляет addEventListener'ы {event: e => {}}
 * children/children_r - массив {DOM, EL, object, html string}. _r - заменить имеющиеся. Без тега tag будет div
 * child/child_r - {DOM, EL, object, html string}. _r - заменить имеющиеся. Без тега tag будет div
 * attrs {object} - добавить аттрибуты (через setAttribute)
 * props {object} - добавить свойства (как el[prop])
 * also {function} - вызвать с текущим компонентом: also(el) { console.log(el); }
 * всё остальное будет добавлено как property
 */
EL.make(tag, data = {});

/**
 * Создать теневой компонент от указанного tag, дети подключатся к нему в shadowRoot
 * @param {string|Node} host html tag теневого элемента или Node
 * @param {object} data параметры внешнего элемента
 * @param {string} sheet css стили
 * @returns {Node} host
 */
EL.makeShadow(host, data = {}, sheet = null);

/**
 * Настроить элемент
 * @param {Node | Array} el элемент или массив элементов
 * @param {object} data параметры
 * @returns {Node}
 */
EL.config(el, data);

/**
 * Создать массив компонентов из массива объектов конфигурации
 * @param {array} arr массив объектов конфигурации
 * @returns {array} of Elements
 */
EL.makeArray(arr);

SVG

SVG.make(tag, data);
SVG.config(el, data);
SVG.makeArray(arr);

SVG.svg(attrs = {}, props = {});
SVG.rect(x, y, w, h, rx, ry, attrs = {}, props = {});
SVG.circle(x, y, r, attrs = {}, props = {});
SVG.line(x1, y1, x2, y2, attrs = {}, props = {});
SVG.polyline(points, attrs = {}, props = {});
SVG.polygon(points, attrs = {}, props = {});
SVG.path(d, attrs = {}, props = {});
SVG.text(text, x, y, attrs = {}, props = {});

Sheet

/**
 * Добавить стиль с уникальным id в head. ext - стиль можно будет удалить по id
 * @param {string|array} style стили в виде css
 * @param {string|this} id уникальный id стиля. При передаче this будет именем класса
 * @param {boolean} ext внешний стиль - может быть удалён по id
 */
Sheet.addStyle(style, id, ext = false);

/**
 * Удалить ext стиль по его id
 * @param {string} id id стиля
 */
Sheet.removeStyle(id);

StyledComponent

/**
 * Создать компонент и поместить его в переменную $root
 * @param {string} tag html tag элемента
 * @param {object} data параметры
 * @param {string|array} style стили в виде css строки
 * @param {string|this} id уникальный id стиля. При передаче this будет именем класса
 * @param {boolean} ext внешний стиль - может быть удалён по id
 */
StyledComponent(tag, data = {}, style = null, id = null, ext = false);

/**
 * Создать компонент
 * @param {string} tag html tag элемента
 * @param {object} data параметры
 * @param {string|array} style стили в виде css строки
 * @param {string|this} id уникальный id стиля. При передаче this будет именем класса
 * @param {boolean} ext внешний стиль - может быть удалён по id
 */
StyledComponent.make(tag, data = {}, style = null, id = null, ext = false);

Пример

Создаст контейнер с двумя вложенными блоками текста и прикрепит к body

EL.make('div', {
    parent: document.body,
    class: 'my-div',
    style: {
        background: 'red',
    },
    events: {
        click: () => console.log('click'),
    },
    children: [
        {
            tag: 'span',
            text: 'hello',
        },
        {
            tag: 'span',
            text: 'world',
        }
    ]
});

Гораздо интереснее использовать в классе и передавать контекст. Параметр $ создаст переменную с элементом с указанным именем + префикс $:

class Button {
    constructor(text) {
        EL.make('button', {
            context: this,
            $: 'button',
            text: text,
            class: 'btn',
            events: {
                click: console.log(this.$button),
            },
        });

        // тут уже существует this.$button
    }
}

let btn = new Button('kek');
btn.$button; // элемент кнопки

Некоторые трюки

EL.make('div', {
    context: this,
    children: [
        {},   // валидно
        null, // валидно
        {
            // без тега - div
        },
        EL.make(...), // контекст будет проброшен сюда автоматически
        foo && {...}, // добавить компонент если foo - true
        {
            tag: 'svg', // автоматически запустится режим SVG
            children: [
                // и будет проброшен сюда
                SVG.circle(10, 10, 5),
                {
                    tag: 'line',
                    attrs: {}
                },
            ],
        },
    ],
    class: ['some', 'class', foo && 'plus_me'], // добавить plus_me если foo - true
});