@alexgyver/component 1.0.26 → 1.1.0

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.
@@ -4,39 +4,42 @@ export class Component {
4
4
  * @param {string} tag html tag элемента
5
5
  * @param {object} data параметры
6
6
  */
7
- constructor(tag, data = {}) {
7
+ constructor(tag, data = {}, ns = false) {
8
8
  data.context = this;
9
- this.$root = Component.make(tag, data);
9
+ this.$root = Component.make(tag, data, ns);
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
- static make(tag, data = {}) {
35
+ static make(tag, data = {}, ns = false) {
37
36
  if (!tag || typeof data !== 'object') return null;
38
37
  if (data instanceof Node) return data;
39
- return Component.config(document.createElement(tag), data);
38
+ return Component.config(ns ? document.createElementNS("http://www.w3.org/2000/svg", tag) : document.createElement(tag), data, ns);
39
+ }
40
+
41
+ static makeNS(tag, data = {}) {
42
+ return Component.make(tag, data, true);
40
43
  }
41
44
 
42
45
  /**
@@ -73,9 +76,10 @@ export class Component {
73
76
  * Настроить элемент
74
77
  * @param {Node} el элемент
75
78
  * @param {object} data параметры
79
+ * @param {object} ns NS
76
80
  * @returns {Node}
77
81
  */
78
- static config(el, data) {
82
+ static config(el, data, ns = false) {
79
83
  if (!(el instanceof Node) || (typeof data !== 'object')) return el;
80
84
  const context = data.context;
81
85
 
@@ -85,7 +89,7 @@ export class Component {
85
89
  else if (obj instanceof Component) el.appendChild(obj.$root);
86
90
  else if (typeof obj === 'object') {
87
91
  if (!obj.context) obj.context = context;
88
- let cmp = Component.make(obj.tag, obj);
92
+ let cmp = Component.make(obj.tag, obj, ns);
89
93
  if (cmp) el.appendChild(cmp);
90
94
  } else if (typeof obj === 'string') {
91
95
  el.innerHTML += obj;
@@ -120,14 +124,22 @@ export class Component {
120
124
  return el;
121
125
  }
122
126
 
127
+ static configNS(el, data) {
128
+ return Component.config(el, data, true);
129
+ }
130
+
123
131
  /**
124
132
  * Создать массив компонентов из массива объектов конфигурации
125
133
  * @param {array} arr массив объектов конфигурации
126
134
  * @returns {array} of Elements
127
135
  */
128
- static makeArray(arr) {
136
+ static makeArray(arr, ns = false) {
129
137
  if (!arr || !Array.isArray(arr)) return [];
130
- return arr.map(x => Component.make(x.tag, x));
138
+ return arr.map(x => Component.make(x.tag, x, ns));
139
+ }
140
+
141
+ static makeArrayNS(arr) {
142
+ return Component.makeArray(arr, true);
131
143
  }
132
144
  }
133
145
 
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/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "@alexgyver/component",
3
- "version": "1.0.26",
3
+ "version": "1.1.0",
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"