@alexgyver/component 1.0.25 → 1.0.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,29 +9,28 @@ export class Component {
9
9
  this.$root = Component.make(tag, data);
10
10
  }
11
11
 
12
- /*
13
- tag {string} тег html элемента (для указания в children например)
14
- context {object} контекст для параметра 'var' и вызовов 'also'
15
- text {string} добавить в textContent
16
- html {string} добавить в innerHTML
17
- attrs {object} добавить аттрибуты
18
- props {object} добавить свойства
19
- class {string} добавить в className
20
- also {function} - вызвать с текущим компонентом: { ... , also(el) { console.log(el); }, }
21
- export {array} - положить в 0 ячейку указанного массива
22
- var {string} создаёт переменную $имя в указанном контексте
23
- events {object} добавляет addEventListener'ы {event: handler}
24
- parent - {Element} добавляет компонент к указанному элементу (имеет смысл только для корневого компонента)
25
- style {string | object} объект в виде { padding: '0px', ... } или строка css стилей
26
- children - массив DOM, Component, object, html string
27
- child - DOM, Component, object, html string
28
- всё остальное будет добавлено как property
29
- */
30
12
  /**
31
13
  * Создать компонент
32
14
  * @param {string} tag html tag элемента
33
15
  * @param {object} data параметры
34
16
  * @returns {Node}
17
+ * @params
18
+ * tag {string} тег html элемента (для указания в children например)
19
+ * context {object} контекст для параметра 'var' и вызовов 'also'
20
+ * text {string} добавить в textContent
21
+ * html {string} добавить в innerHTML
22
+ * attrs {object} добавить аттрибуты
23
+ * props {object} добавить свойства
24
+ * class {string} добавить в className
25
+ * also {function} - вызвать с текущим компонентом: { ... , also(el) { console.log(el); }, }
26
+ * export {array} - положить в 0 ячейку указанного массива
27
+ * var {string} создаёт переменную $имя в указанном контексте
28
+ * events {object} добавляет addEventListener'ы {event: handler}
29
+ * parent - {Element} добавляет компонент к указанному элементу (имеет смысл только для корневого компонента)
30
+ * style {string | object} объект в виде { padding: '0px', ... } или строка css стилей
31
+ * children - массив DOM, Component, object, html string
32
+ * child - DOM, Component, object, html string
33
+ * всё остальное будет добавлено как property
35
34
  */
36
35
  static make(tag, data = {}) {
37
36
  if (!tag || typeof data !== 'object') return null;
@@ -39,6 +38,36 @@ export class Component {
39
38
  return Component.config(document.createElement(tag), data);
40
39
  }
41
40
 
41
+ /**
42
+ * Создать теневой компонент от указанного tag, дети подключатся к нему в shadowRoot
43
+ * @param {string|Node} host html tag теневого элемента или Node
44
+ * @param {object} data параметры внешнего элемента
45
+ * @param {string} sheet css стили
46
+ * @returns {Node} host
47
+ */
48
+ static makeShadow(host, data = {}, sheet = null) {
49
+ if (!host || typeof data !== 'object') return null;
50
+
51
+ let $host = (host instanceof Node) ? host : document.createElement(host);
52
+ $host.attachShadow({ mode: 'open' });
53
+
54
+ Component.config($host.shadowRoot, {
55
+ context: data.context,
56
+ children: [
57
+ {
58
+ tag: 'style',
59
+ textContent: sheet ?? '',
60
+ },
61
+ data.child ?? {},
62
+ ...(data.children ?? []),
63
+ ]
64
+ });
65
+ delete data.children;
66
+ delete data.child;
67
+ Component.config($host, data);
68
+ return $host;
69
+ }
70
+
42
71
  /**
43
72
  * Настроить элемент
44
73
  * @param {Node} el элемент
@@ -46,7 +75,7 @@ export class Component {
46
75
  * @returns {Node}
47
76
  */
48
77
  static config(el, data) {
49
- if (!(el instanceof Node)) return el;
78
+ if (!(el instanceof Node) || (typeof data !== 'object')) return el;
50
79
  const context = data.context;
51
80
 
52
81
  let addChild = (obj) => {
@@ -63,6 +92,7 @@ export class Component {
63
92
  }
64
93
 
65
94
  for (const [key, val] of Object.entries(data)) {
95
+ if (!val) continue;
66
96
  switch (key) {
67
97
  case 'tag':
68
98
  case 'context':
@@ -74,7 +104,7 @@ export class Component {
74
104
  case 'export': val[0] = el; break;
75
105
  case 'var': if (context) context['$' + val] = el; break;
76
106
  case 'events': for (let ev in val) if (val[ev]) el.addEventListener(ev, val[ev].bind(context)); break;
77
- case 'parent': if (val instanceof Element) val.append(el); break;
107
+ case 'parent': if (val instanceof Node || val instanceof DocumentFragment) val.append(el); break;
78
108
  case 'attrs': for (let attr in val) el.setAttribute(attr, val[attr]); break;
79
109
  case 'props': for (let prop in val) el[prop] = val[prop]; break;
80
110
  case 'child': addChild(val); break;
@@ -95,6 +125,7 @@ export class Component {
95
125
  * @returns {array} of Elements
96
126
  */
97
127
  static makeArray(arr) {
128
+ if (!arr || !Array.isArray(arr)) return [];
98
129
  return arr.map(x => Component.make(x.tag, x));
99
130
  }
100
131
  }
package/README.md CHANGED
@@ -1,3 +1,150 @@
1
1
  # Component.js
2
-
3
- > npm i @alexgyver/component
2
+ Библиотека для создания и настройки DOM элементов как JS объектов
3
+
4
+ > npm i @alexgyver/component
5
+
6
+ ## Дока
7
+ ### Component
8
+ ```js
9
+ /**
10
+ * Создать компонент и поместить его в переменную $root
11
+ * @param {string} tag html tag элемента
12
+ * @param {object} data параметры
13
+ */
14
+ Component(tag, data = {});
15
+
16
+ /**
17
+ * Создать компонент
18
+ * @param {string} tag html tag элемента
19
+ * @param {object} data параметры
20
+ * @returns {Node}
21
+ * tag {string} тег html элемента (для указания в children например)
22
+ * context {object} контекст для параметра 'var' и вызовов 'also'
23
+ * text {string} добавить в textContent
24
+ * html {string} добавить в innerHTML
25
+ * attrs {object} добавить аттрибуты
26
+ * props {object} добавить свойства
27
+ * class {string} добавить в className
28
+ * also {function} - вызвать с текущим компонентом: { ... , also(el) { console.log(el); }, }
29
+ * export {array} - положить в 0 ячейку указанного массива
30
+ * var {string} создаёт переменную $имя в указанном контексте
31
+ * events {object} добавляет addEventListener'ы {event: handler}
32
+ * parent - {Element} добавляет компонент к указанному элементу (имеет смысл только для корневого компонента)
33
+ * style {string | object} объект в виде { padding: '0px', ... } или строка css стилей
34
+ * children - массив DOM, Component, object, html string
35
+ * child - DOM, Component, object, html string
36
+ * всё остальное будет добавлено как property
37
+ */
38
+ Component.make(tag, data = {});
39
+
40
+ /**
41
+ * Создать теневой компонент от указанного tag, дети подключатся к нему в shadowRoot
42
+ * @param {string|Node} host html tag теневого элемента или Node
43
+ * @param {object} data параметры внешнего элемента
44
+ * @param {string} sheet css стили
45
+ * @returns {Node} host
46
+ */
47
+ Component.makeShadow(host, data = {}, sheet = null);
48
+
49
+ /**
50
+ * Настроить элемент
51
+ * @param {Node} el элемент
52
+ * @param {object} data параметры
53
+ * @returns {Node}
54
+ */
55
+ Component.config(el, data);
56
+
57
+ /**
58
+ * Создать массив компонентов из массива объектов конфигурации
59
+ * @param {array} arr массив объектов конфигурации
60
+ * @returns {array} of Elements
61
+ */
62
+ Component.makeArray(arr);
63
+ ```
64
+
65
+ ### Sheet
66
+ ```js
67
+ /**
68
+ * Добавить стиль с уникальным id в head. ext - стиль можно будет удалить по id
69
+ * @param {string|array} style стили в виде css строки или [ 'class', ['color: red', 'padding: 0'], ... ]
70
+ * @param {string|this} id уникальный id стиля. При передаче this будет именем класса
71
+ * @param {boolean} ext внешний стиль - может быть удалён по id
72
+ */
73
+ Sheet.addStyle(style, id, ext = false);
74
+
75
+ /**
76
+ * Удалить ext стиль по его id
77
+ * @param {string} id id стиля
78
+ */
79
+ Sheet.removeStyle(id);
80
+ ```
81
+
82
+ ### StyledComponent
83
+ ```js
84
+ /**
85
+ * Создать компонент и поместить его в переменную $root
86
+ * @param {string} tag html tag элемента
87
+ * @param {object} data параметры
88
+ * @param {string|array} style стили в виде css строки или [ 'class', ['color: red', 'padding: 0'], ... ]
89
+ * @param {string|this} id уникальный id стиля. При передаче this будет именем класса
90
+ * @param {boolean} ext внешний стиль - может быть удалён по id
91
+ */
92
+ StyledComponent(tag, data = {}, style = null, id = null, ext = false);
93
+
94
+ /**
95
+ * Создать компонент
96
+ * @param {string} tag html tag элемента
97
+ * @param {object} data параметры
98
+ * @param {string|array} style стили в виде css строки или [ 'class', ['color: red', 'padding: 0'], ... ]
99
+ * @param {string|this} id уникальный id стиля. При передаче this будет именем класса
100
+ * @param {boolean} ext внешний стиль - может быть удалён по id
101
+ */
102
+ StyledComponent.make(tag, data = {}, style = null, id = null, ext = false);
103
+ ```
104
+
105
+ ## Пример
106
+ Создаст контейнер с двумя вложенными блоками текста и прикрепит к body
107
+ ```js
108
+ Component.make('div', {
109
+ parent: document.body,
110
+ class: 'my-div',
111
+ style: {
112
+ background: 'red',
113
+ },
114
+ events: {
115
+ click: () => console.log('click'),
116
+ },
117
+ children: [
118
+ {
119
+ tag: 'span',
120
+ text: 'hello',
121
+ },
122
+ {
123
+ tag: 'span',
124
+ text: 'world',
125
+ }
126
+ ]
127
+ });
128
+ ```
129
+
130
+ Гораздо интереснее использовать в классе и передавать контекст. Параметр `var` создаст переменную с элементом с указанным именем + префикс `$`:
131
+ ```js
132
+ class Button {
133
+ constructor(text) {
134
+ Component.make('button', {
135
+ context: this,
136
+ var: 'button',
137
+ text: text,
138
+ class: 'btn',
139
+ events: {
140
+ click: console.log(this.$button),
141
+ },
142
+ });
143
+
144
+ // тут уже существует this.$button
145
+ }
146
+ }
147
+
148
+ let btn = new Button('kek');
149
+ btn.$button; // элемент кнопки
150
+ ```
package/example/script.js CHANGED
@@ -87,6 +87,30 @@ function Container(children) {
87
87
  });
88
88
  }
89
89
 
90
+ class ShadowComponent {
91
+ constructor() {
92
+ Component.makeShadow('div', {
93
+ context: this,
94
+ parent: document.body,
95
+ events: {
96
+ click: () => this.$div.dispatchEvent(new Event('kek', { bubbles: true, composed: true })),
97
+ },
98
+ children: [
99
+ {
100
+ tag: 'div',
101
+ text: 'Hello!',
102
+ class: 'myclass',
103
+ var: 'div',
104
+ }
105
+ ]
106
+ }, '.myclass{color:red;}'
107
+ );
108
+
109
+ }
110
+ }
111
+
112
+ document.addEventListener('kek', () => console.log('kek!'));
113
+
90
114
  document.addEventListener("DOMContentLoaded", () => {
91
115
  Component.make('h1', {
92
116
  text: 'Hello!',
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "@alexgyver/component",
3
- "version": "1.0.25",
3
+ "version": "1.0.27",
4
4
  "description": "Simple HTML element builder",
5
- "main": "./component.js",
6
- "module": "./component.js",
7
- "types": "./component.js",
5
+ "main": "./Component.js",
6
+ "module": "./Component.js",
7
+ "types": "./Component.js",
8
8
  "repository": {
9
9
  "type": "git",
10
10
  "url": "git+https://github.com/GyverLibs/Component.js.git"