@alexgyver/component 1.3.4 → 1.3.6
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.
- package/Component.js +33 -22
- package/Component.min.js +1 -0
- package/README.md +196 -166
- package/package.json +9 -2
- package/{example → test}/script.js +5 -5
- package/webpack.config.js +14 -0
- /package/{example → test}/example.html +0 -0
package/Component.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
//#region
|
|
2
|
-
export class
|
|
1
|
+
//#region EL
|
|
2
|
+
export class EL {
|
|
3
3
|
static ctx;
|
|
4
4
|
|
|
5
5
|
/**
|
|
@@ -9,8 +9,8 @@ export class Component {
|
|
|
9
9
|
* @param {Boolean} svg SVG
|
|
10
10
|
*/
|
|
11
11
|
constructor(tag, data = {}, svg = false) {
|
|
12
|
-
|
|
13
|
-
this.$root =
|
|
12
|
+
EL.ctx = this;
|
|
13
|
+
this.$root = EL.make(tag, data, svg);
|
|
14
14
|
}
|
|
15
15
|
|
|
16
16
|
/**
|
|
@@ -30,8 +30,8 @@ export class Component {
|
|
|
30
30
|
* push {array} - добавить к указанному массиву
|
|
31
31
|
* var {string} - создаёт переменную $имя в указанном контексте
|
|
32
32
|
* events {object} - добавляет addEventListener'ы {event: e => {}}
|
|
33
|
-
* children/children_r - массив {DOM,
|
|
34
|
-
* child/child_r - {DOM,
|
|
33
|
+
* children/children_r - массив {DOM, EL, object, html string}. _r - заменить имеющиеся. Без тега tag будет div
|
|
34
|
+
* child/child_r - {DOM, EL, object, html string}. _r - заменить имеющиеся. Без тега tag будет div
|
|
35
35
|
* attrs {object} - добавить аттрибуты (через setAttribute)
|
|
36
36
|
* props {object} - добавить свойства (как el[prop])
|
|
37
37
|
* also {function} - вызвать с текущим компонентом: also(el) { console.log(el); }
|
|
@@ -41,7 +41,7 @@ export class Component {
|
|
|
41
41
|
if (!tag || typeof data !== 'object') return null;
|
|
42
42
|
if (data instanceof Node) return data;
|
|
43
43
|
if (tag == 'svg') svg = true;
|
|
44
|
-
return
|
|
44
|
+
return EL.config(svg ? document.createElementNS("http://www.w3.org/2000/svg", tag) : document.createElement(tag), data, svg);
|
|
45
45
|
}
|
|
46
46
|
|
|
47
47
|
/**
|
|
@@ -53,22 +53,22 @@ export class Component {
|
|
|
53
53
|
*/
|
|
54
54
|
static config(el, data, svg = false) {
|
|
55
55
|
if (Array.isArray(el)) {
|
|
56
|
-
el.forEach(e =>
|
|
56
|
+
el.forEach(e => EL.config(e, data, svg));
|
|
57
57
|
return null;
|
|
58
58
|
}
|
|
59
59
|
if (!(el instanceof Node) || (typeof data !== 'object')) return el;
|
|
60
60
|
|
|
61
61
|
let ctx = data.context;
|
|
62
|
-
|
|
63
|
-
ctx =
|
|
62
|
+
EL.ctx = (ctx === null) ? null : (ctx ? ctx : EL.ctx);
|
|
63
|
+
ctx = EL.ctx;
|
|
64
64
|
|
|
65
65
|
let addChild = (obj) => {
|
|
66
66
|
if (!obj) return;
|
|
67
67
|
if (obj instanceof Node) el.appendChild(obj);
|
|
68
|
-
else if (obj instanceof
|
|
68
|
+
else if (obj instanceof EL) el.appendChild(obj.$root);
|
|
69
69
|
else if (typeof obj === 'string') el.innerHTML += obj;
|
|
70
70
|
else if (typeof obj === 'object') {
|
|
71
|
-
let cmp =
|
|
71
|
+
let cmp = EL.make(obj.tag ?? 'div', obj, svg || obj.tag == 'svg');
|
|
72
72
|
if (cmp) el.appendChild(cmp);
|
|
73
73
|
}
|
|
74
74
|
}
|
|
@@ -90,9 +90,9 @@ export class Component {
|
|
|
90
90
|
case 'parent': if (val) val.appendChild(el); break;
|
|
91
91
|
case 'attrs': for (let attr in val) el.setAttribute(attr, val[attr]); break;
|
|
92
92
|
case 'props': for (let prop in val) el[prop] = val[prop]; break;
|
|
93
|
-
case 'child_r':
|
|
93
|
+
case 'child_r': EL.clear(el); // fall
|
|
94
94
|
case 'child': addChild(val); break;
|
|
95
|
-
case 'children_r':
|
|
95
|
+
case 'children_r': EL.clear(el); // fall
|
|
96
96
|
case 'children': for (const obj of val) addChild(obj); break;
|
|
97
97
|
case 'style':
|
|
98
98
|
if (typeof val === 'string') el.style.cssText += (val + ';');
|
|
@@ -105,6 +105,14 @@ export class Component {
|
|
|
105
105
|
return el;
|
|
106
106
|
}
|
|
107
107
|
|
|
108
|
+
/**
|
|
109
|
+
* Удалить все child ноды
|
|
110
|
+
* @param {HTMLElement} el
|
|
111
|
+
*/
|
|
112
|
+
static clear(el) {
|
|
113
|
+
while (el.firstChild) el.removeChild(el.lastChild);
|
|
114
|
+
}
|
|
115
|
+
|
|
108
116
|
/**
|
|
109
117
|
* Создать массив компонентов из массива объектов конфигурации
|
|
110
118
|
* @param {array} arr массив объектов конфигурации
|
|
@@ -113,7 +121,7 @@ export class Component {
|
|
|
113
121
|
*/
|
|
114
122
|
static makeArray(arr, svg = false) {
|
|
115
123
|
if (!arr || !Array.isArray(arr)) return [];
|
|
116
|
-
return arr.map(x =>
|
|
124
|
+
return arr.map(x => EL.make(x.tag, x, svg));
|
|
117
125
|
}
|
|
118
126
|
|
|
119
127
|
/**
|
|
@@ -129,7 +137,7 @@ export class Component {
|
|
|
129
137
|
let $host = (host instanceof Node) ? host : document.createElement(host);
|
|
130
138
|
$host.attachShadow({ mode: 'open' });
|
|
131
139
|
|
|
132
|
-
|
|
140
|
+
EL.config($host.shadowRoot, {
|
|
133
141
|
context: data.context,
|
|
134
142
|
children: [
|
|
135
143
|
{
|
|
@@ -142,16 +150,19 @@ export class Component {
|
|
|
142
150
|
});
|
|
143
151
|
delete data.children;
|
|
144
152
|
delete data.child;
|
|
145
|
-
|
|
153
|
+
EL.config($host, data);
|
|
146
154
|
return $host;
|
|
147
155
|
}
|
|
148
156
|
}
|
|
149
157
|
|
|
158
|
+
// legacy
|
|
159
|
+
export const Component = EL;
|
|
160
|
+
|
|
150
161
|
//#region SVG
|
|
151
162
|
export class SVG {
|
|
152
|
-
static make = (tag, data) =>
|
|
153
|
-
static config = (el, data) =>
|
|
154
|
-
static makeArray = (arr) =>
|
|
163
|
+
static make = (tag, data) => EL.make(tag, data, true);
|
|
164
|
+
static config = (el, data) => EL.config(el, data, true);
|
|
165
|
+
static makeArray = (arr) => EL.makeArray(arr, true);
|
|
155
166
|
|
|
156
167
|
static svg = (attrs = {}, props = {}) => SVG._make('svg', attrs, props);
|
|
157
168
|
static rect = (x, y, w, h, rx, ry, attrs = {}, props = {}) => SVG._make('rect', { ...attrs, x: x, y: y, width: w, height: h, rx: rx, ry: ry }, props);
|
|
@@ -209,7 +220,7 @@ export class Sheet {
|
|
|
209
220
|
}
|
|
210
221
|
|
|
211
222
|
//#region StyledComponent
|
|
212
|
-
export class StyledComponent extends
|
|
223
|
+
export class StyledComponent extends EL {
|
|
213
224
|
/**
|
|
214
225
|
* Создать компонент и поместить его в переменную $root
|
|
215
226
|
* @param {string} tag html tag элемента
|
|
@@ -233,6 +244,6 @@ export class StyledComponent extends Component {
|
|
|
233
244
|
*/
|
|
234
245
|
static make(tag, data = {}, style = null, id = null, ext = false) {
|
|
235
246
|
Sheet.addStyle(style, id, ext);
|
|
236
|
-
return
|
|
247
|
+
return EL.make(tag, data);
|
|
237
248
|
}
|
|
238
249
|
}
|
package/Component.min.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e={d:(t,a)=>{for(var c in a)e.o(a,c)&&!e.o(t,c)&&Object.defineProperty(t,c,{enumerable:!0,get:a[c]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},t={};e.d(t,{EL:()=>a,LV:()=>r,cj:()=>s,t4:()=>n,uA:()=>c});class a{static ctx;constructor(e,t={},c=!1){a.ctx=this,this.$root=a.make(e,t,c)}static make(e,t={},c=!1){return e&&"object"==typeof t?t instanceof Node?t:("svg"==e&&(c=!0),a.config(c?document.createElementNS("http://www.w3.org/2000/svg",e):document.createElement(e),t,c)):null}static config(e,t,c=!1){if(Array.isArray(e))return e.forEach((e=>a.config(e,t,c))),null;if(!(e instanceof Node)||"object"!=typeof t)return e;let n=t.context;a.ctx=null===n?null:n||a.ctx,n=a.ctx;let s=t=>{if(t)if(t instanceof Node)e.appendChild(t);else if(t instanceof a)e.appendChild(t.$root);else if("string"==typeof t)e.innerHTML+=t;else if("object"==typeof t){let n=a.make(t.tag??"div",t,c||"svg"==t.tag);n&&e.appendChild(n)}};for(const[a,c]of Object.entries(t))if(c)switch(a){case"tag":case"context":case"get":case"also":continue;case"text":e.textContent=c+"";break;case"html":e.innerHTML=c;break;case"class":(Array.isArray(c)?c:c.split(" ")).map((t=>t&&e.classList.add(t)));break;case"push":c.push(e);break;case"var":n&&(n["$"+c]=e);break;case"events":for(let t in c)e.addEventListener(t,c[t].bind(n));break;case"parent":c&&c.appendChild(e);break;case"attrs":for(let t in c)e.setAttribute(t,c[t]);break;case"props":for(let t in c)e[t]=c[t];break;case"child_r":e.replaceChildren();case"child":s(c);break;case"children_r":e.replaceChildren();case"children":for(const e of c)s(e);break;case"style":if("string"==typeof c)e.style.cssText+=c+";";else for(let t in c)e.style[t]=c[t];break;default:e[a]=c}return t.also&&n&&t.also.call(n,e),e}static makeArray(e,t=!1){return e&&Array.isArray(e)?e.map((e=>a.make(e.tag,e,t))):[]}static makeShadow(e,t={},c=null){if(!e||"object"!=typeof t)return null;let n=e instanceof Node?e:document.createElement(e);return n.attachShadow({mode:"open"}),a.config(n.shadowRoot,{context:t.context,children:[{tag:"style",textContent:c??""},t.child??{},...t.children??[]]}),delete t.children,delete t.child,a.config(n,t),n}}const c=a;class n{static make=(e,t)=>a.make(e,t,!0);static config=(e,t)=>a.config(e,t,!0);static makeArray=e=>a.makeArray(e,!0);static svg=(e={},t={})=>n._make("svg",e,t);static rect=(e,t,a,c,s,r,o={},i={})=>n._make("rect",{...o,x:e,y:t,width:a,height:c,rx:s,ry:r},i);static circle=(e,t,a,c={},s={})=>n._make("circle",{...c,cx:e,cy:t,r:a},s);static line=(e,t,a,c,s={},r={})=>n._make("line",{...s,x1:e,y1:t,x2:a,y2:c},r);static polyline=(e,t={},a={})=>n._make("polyline",{...t,points:e},a);static polygon=(e,t={},a={})=>n._make("polygon",{...t,points:e},a);static path=(e,t={},a={})=>n._make("path",{...t,d:e},a);static text=(e,t,a,c={},s={})=>n._make("text",{...c,x:t,y:a},{...s,text:e});static _make=(e,t={},a={})=>n.make(e,{attrs:{...t},...a})}class s{static addStyle(e,t,a=!1){if(e&&t&&("object"==typeof t&&(t=t.constructor.name),!s.#e.has(t)&&!s.#t.has(t)))if(a){let a=document.createElement("style");document.head.appendChild(a),a.textContent=e,s.#t.set(t,a)}else s.#a||(s.#a=document.head.appendChild(document.createElement("style"))),s.#a.textContent+=e+"\r\n",s.#e.add(t)}static removeStyle(e){"object"==typeof e&&(e=e.constructor.name),s.#t.has(e)&&(s.#t.get(e).remove(),s.#t.delete(e))}static#a=null;static#e=new Set;static#t=new Map}class r extends a{constructor(e,t={},a=null,c=null,n=!1){super(e,t),s.addStyle(a,c,n)}static make(e,t={},c=null,n=null,r=!1){return s.addStyle(c,n,r),a.make(e,t)}}var o=t.uA,i=t.EL,l=t.t4,d=t.cj,p=t.LV;export{o as Component,i as EL,l as SVG,d as Sheet,p as StyledComponent};
|
package/README.md
CHANGED
|
@@ -1,166 +1,196 @@
|
|
|
1
|
-
# Component.js
|
|
2
|
-
Библиотека для создания и настройки DOM/SVG элементов как 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
|
-
|
|
15
|
-
|
|
16
|
-
/**
|
|
17
|
-
* Создать компонент
|
|
18
|
-
* @param {string} tag html tag элемента
|
|
19
|
-
* @param {object} data параметры
|
|
20
|
-
* @returns {Node}
|
|
21
|
-
* tag {string} - тег html элемента. Если 'svg' - включится режим SVG на детей
|
|
22
|
-
* context {object} - контекст для параметра 'var' и вызовов, прокидывается в детей. Если указан явно как null - прерывает проброс
|
|
23
|
-
* parent - {Element} добавляет компонент к указанному элементу
|
|
24
|
-
* text {string} - добавить в textContent
|
|
25
|
-
* html {string} - добавить в innerHTML
|
|
26
|
-
* class {string | Array} - добавить в className
|
|
27
|
-
* style {string | object} - объект в виде { padding: '0px', ... } или строка css стилей
|
|
28
|
-
* push {array} - добавить к указанному массиву
|
|
29
|
-
* var {string} - создаёт переменную $имя в указанном контексте
|
|
30
|
-
* events {object} - добавляет addEventListener'ы {event: e => {}}
|
|
31
|
-
* children/children_r - массив {DOM,
|
|
32
|
-
* child/child_r - {DOM,
|
|
33
|
-
* attrs {object} - добавить аттрибуты (через setAttribute)
|
|
34
|
-
* props {object} - добавить свойства (как el[prop])
|
|
35
|
-
* also {function} - вызвать с текущим компонентом: also(el) { console.log(el); }
|
|
36
|
-
* всё остальное будет добавлено как property
|
|
37
|
-
*/
|
|
38
|
-
|
|
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
|
-
|
|
48
|
-
|
|
49
|
-
/**
|
|
50
|
-
* Настроить элемент
|
|
51
|
-
* @param {Node | Array} el элемент или массив элементов
|
|
52
|
-
* @param {object} data параметры
|
|
53
|
-
* @returns {Node}
|
|
54
|
-
*/
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
/**
|
|
58
|
-
* Создать массив компонентов из массива объектов конфигурации
|
|
59
|
-
* @param {array} arr массив объектов конфигурации
|
|
60
|
-
* @returns {array} of Elements
|
|
61
|
-
*/
|
|
62
|
-
|
|
63
|
-
```
|
|
64
|
-
|
|
65
|
-
### SVG
|
|
66
|
-
```js
|
|
67
|
-
SVG.make(tag, data);
|
|
68
|
-
SVG.config(el, data);
|
|
69
|
-
SVG.makeArray(arr);
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
SVG.rect(x, y, w, h, rx, ry, attrs = {}, props = {});
|
|
73
|
-
SVG.circle(x, y, r, attrs = {}, props = {});
|
|
74
|
-
SVG.line(x1, y1, x2, y2, attrs = {}, props = {});
|
|
75
|
-
SVG.polyline(points, attrs = {}, props = {});
|
|
76
|
-
SVG.polygon(points, attrs = {}, props = {});
|
|
77
|
-
SVG.path(d, attrs = {}, props = {});
|
|
78
|
-
SVG.text(text, x, y, attrs = {}, props = {});
|
|
79
|
-
```
|
|
80
|
-
|
|
81
|
-
### Sheet
|
|
82
|
-
```js
|
|
83
|
-
/**
|
|
84
|
-
* Добавить стиль с уникальным id в head. ext - стиль можно будет удалить по id
|
|
85
|
-
* @param {string|array} style стили в виде css
|
|
86
|
-
* @param {string|this} id уникальный id стиля. При передаче this будет именем класса
|
|
87
|
-
* @param {boolean} ext внешний стиль - может быть удалён по id
|
|
88
|
-
*/
|
|
89
|
-
Sheet.addStyle(style, id, ext = false);
|
|
90
|
-
|
|
91
|
-
/**
|
|
92
|
-
* Удалить ext стиль по его id
|
|
93
|
-
* @param {string} id id стиля
|
|
94
|
-
*/
|
|
95
|
-
Sheet.removeStyle(id);
|
|
96
|
-
```
|
|
97
|
-
|
|
98
|
-
### StyledComponent
|
|
99
|
-
```js
|
|
100
|
-
/**
|
|
101
|
-
* Создать компонент и поместить его в переменную $root
|
|
102
|
-
* @param {string} tag html tag элемента
|
|
103
|
-
* @param {object} data параметры
|
|
104
|
-
* @param {string|array} style стили в виде css строки
|
|
105
|
-
* @param {string|this} id уникальный id стиля. При передаче this будет именем класса
|
|
106
|
-
* @param {boolean} ext внешний стиль - может быть удалён по id
|
|
107
|
-
*/
|
|
108
|
-
StyledComponent(tag, data = {}, style = null, id = null, ext = false);
|
|
109
|
-
|
|
110
|
-
/**
|
|
111
|
-
* Создать компонент
|
|
112
|
-
* @param {string} tag html tag элемента
|
|
113
|
-
* @param {object} data параметры
|
|
114
|
-
* @param {string|array} style стили в виде css строки
|
|
115
|
-
* @param {string|this} id уникальный id стиля. При передаче this будет именем класса
|
|
116
|
-
* @param {boolean} ext внешний стиль - может быть удалён по id
|
|
117
|
-
*/
|
|
118
|
-
StyledComponent.make(tag, data = {}, style = null, id = null, ext = false);
|
|
119
|
-
```
|
|
120
|
-
|
|
121
|
-
## Пример
|
|
122
|
-
Создаст контейнер с двумя вложенными блоками текста и прикрепит к body
|
|
123
|
-
```js
|
|
124
|
-
|
|
125
|
-
parent: document.body,
|
|
126
|
-
class: 'my-div',
|
|
127
|
-
style: {
|
|
128
|
-
background: 'red',
|
|
129
|
-
},
|
|
130
|
-
events: {
|
|
131
|
-
click: () => console.log('click'),
|
|
132
|
-
},
|
|
133
|
-
children: [
|
|
134
|
-
{
|
|
135
|
-
tag: 'span',
|
|
136
|
-
text: 'hello',
|
|
137
|
-
},
|
|
138
|
-
{
|
|
139
|
-
tag: 'span',
|
|
140
|
-
text: 'world',
|
|
141
|
-
}
|
|
142
|
-
]
|
|
143
|
-
});
|
|
144
|
-
```
|
|
145
|
-
|
|
146
|
-
Гораздо интереснее использовать в классе и передавать контекст. Параметр `var` создаст переменную с элементом с указанным именем + префикс `$`:
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
btn
|
|
166
|
-
|
|
1
|
+
# Component.js
|
|
2
|
+
Библиотека для создания и настройки DOM/SVG элементов как 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
|
+
EL(tag, data = {}, svg = false);
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Создать компонент
|
|
18
|
+
* @param {string} tag html tag элемента
|
|
19
|
+
* @param {object} data параметры
|
|
20
|
+
* @returns {Node}
|
|
21
|
+
* tag {string} - тег html элемента. Если 'svg' - включится режим SVG на детей
|
|
22
|
+
* context {object} - контекст для параметра 'var' и вызовов, прокидывается в детей. Если указан явно как null - прерывает проброс
|
|
23
|
+
* parent - {Element} добавляет компонент к указанному элементу
|
|
24
|
+
* text {string} - добавить в textContent
|
|
25
|
+
* html {string} - добавить в innerHTML
|
|
26
|
+
* class {string | Array} - добавить в className
|
|
27
|
+
* style {string | object} - объект в виде { padding: '0px', ... } или строка css стилей
|
|
28
|
+
* push {array} - добавить к указанному массиву
|
|
29
|
+
* var {string} - создаёт переменную $имя в указанном контексте
|
|
30
|
+
* events {object} - добавляет addEventListener'ы {event: e => {}}
|
|
31
|
+
* children/children_r - массив {DOM, EL, object, html string}. _r - заменить имеющиеся. Без тега tag будет div
|
|
32
|
+
* child/child_r - {DOM, EL, object, html string}. _r - заменить имеющиеся. Без тега tag будет div
|
|
33
|
+
* attrs {object} - добавить аттрибуты (через setAttribute)
|
|
34
|
+
* props {object} - добавить свойства (как el[prop])
|
|
35
|
+
* also {function} - вызвать с текущим компонентом: also(el) { console.log(el); }
|
|
36
|
+
* всё остальное будет добавлено как property
|
|
37
|
+
*/
|
|
38
|
+
EL.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
|
+
EL.makeShadow(host, data = {}, sheet = null);
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Настроить элемент
|
|
51
|
+
* @param {Node | Array} el элемент или массив элементов
|
|
52
|
+
* @param {object} data параметры
|
|
53
|
+
* @returns {Node}
|
|
54
|
+
*/
|
|
55
|
+
EL.config(el, data);
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Создать массив компонентов из массива объектов конфигурации
|
|
59
|
+
* @param {array} arr массив объектов конфигурации
|
|
60
|
+
* @returns {array} of Elements
|
|
61
|
+
*/
|
|
62
|
+
EL.makeArray(arr);
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
### SVG
|
|
66
|
+
```js
|
|
67
|
+
SVG.make(tag, data);
|
|
68
|
+
SVG.config(el, data);
|
|
69
|
+
SVG.makeArray(arr);
|
|
70
|
+
|
|
71
|
+
SVG.svg(attrs = {}, props = {});
|
|
72
|
+
SVG.rect(x, y, w, h, rx, ry, attrs = {}, props = {});
|
|
73
|
+
SVG.circle(x, y, r, attrs = {}, props = {});
|
|
74
|
+
SVG.line(x1, y1, x2, y2, attrs = {}, props = {});
|
|
75
|
+
SVG.polyline(points, attrs = {}, props = {});
|
|
76
|
+
SVG.polygon(points, attrs = {}, props = {});
|
|
77
|
+
SVG.path(d, attrs = {}, props = {});
|
|
78
|
+
SVG.text(text, x, y, attrs = {}, props = {});
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
### Sheet
|
|
82
|
+
```js
|
|
83
|
+
/**
|
|
84
|
+
* Добавить стиль с уникальным id в head. ext - стиль можно будет удалить по id
|
|
85
|
+
* @param {string|array} style стили в виде css
|
|
86
|
+
* @param {string|this} id уникальный id стиля. При передаче this будет именем класса
|
|
87
|
+
* @param {boolean} ext внешний стиль - может быть удалён по id
|
|
88
|
+
*/
|
|
89
|
+
Sheet.addStyle(style, id, ext = false);
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Удалить ext стиль по его id
|
|
93
|
+
* @param {string} id id стиля
|
|
94
|
+
*/
|
|
95
|
+
Sheet.removeStyle(id);
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
### StyledComponent
|
|
99
|
+
```js
|
|
100
|
+
/**
|
|
101
|
+
* Создать компонент и поместить его в переменную $root
|
|
102
|
+
* @param {string} tag html tag элемента
|
|
103
|
+
* @param {object} data параметры
|
|
104
|
+
* @param {string|array} style стили в виде css строки
|
|
105
|
+
* @param {string|this} id уникальный id стиля. При передаче this будет именем класса
|
|
106
|
+
* @param {boolean} ext внешний стиль - может быть удалён по id
|
|
107
|
+
*/
|
|
108
|
+
StyledComponent(tag, data = {}, style = null, id = null, ext = false);
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Создать компонент
|
|
112
|
+
* @param {string} tag html tag элемента
|
|
113
|
+
* @param {object} data параметры
|
|
114
|
+
* @param {string|array} style стили в виде css строки
|
|
115
|
+
* @param {string|this} id уникальный id стиля. При передаче this будет именем класса
|
|
116
|
+
* @param {boolean} ext внешний стиль - может быть удалён по id
|
|
117
|
+
*/
|
|
118
|
+
StyledComponent.make(tag, data = {}, style = null, id = null, ext = false);
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
## Пример
|
|
122
|
+
Создаст контейнер с двумя вложенными блоками текста и прикрепит к body
|
|
123
|
+
```js
|
|
124
|
+
EL.make('div', {
|
|
125
|
+
parent: document.body,
|
|
126
|
+
class: 'my-div',
|
|
127
|
+
style: {
|
|
128
|
+
background: 'red',
|
|
129
|
+
},
|
|
130
|
+
events: {
|
|
131
|
+
click: () => console.log('click'),
|
|
132
|
+
},
|
|
133
|
+
children: [
|
|
134
|
+
{
|
|
135
|
+
tag: 'span',
|
|
136
|
+
text: 'hello',
|
|
137
|
+
},
|
|
138
|
+
{
|
|
139
|
+
tag: 'span',
|
|
140
|
+
text: 'world',
|
|
141
|
+
}
|
|
142
|
+
]
|
|
143
|
+
});
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
Гораздо интереснее использовать в классе и передавать контекст. Параметр `var` создаст переменную с элементом с указанным именем + префикс `$`:
|
|
147
|
+
|
|
148
|
+
```js
|
|
149
|
+
class Button {
|
|
150
|
+
constructor(text) {
|
|
151
|
+
EL.make('button', {
|
|
152
|
+
context: this,
|
|
153
|
+
var: 'button',
|
|
154
|
+
text: text,
|
|
155
|
+
class: 'btn',
|
|
156
|
+
events: {
|
|
157
|
+
click: console.log(this.$button),
|
|
158
|
+
},
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
// тут уже существует this.$button
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
let btn = new Button('kek');
|
|
166
|
+
btn.$button; // элемент кнопки
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
Некоторые трюки
|
|
170
|
+
|
|
171
|
+
```js
|
|
172
|
+
EL.make('div', {
|
|
173
|
+
context: this,
|
|
174
|
+
children: [
|
|
175
|
+
{}, // валидно
|
|
176
|
+
null, // валидно
|
|
177
|
+
{
|
|
178
|
+
// без тега - div
|
|
179
|
+
},
|
|
180
|
+
EL.make(...), // контекст будет проброшен сюда автоматически
|
|
181
|
+
foo && {...}, // добавить компонент если foo - true
|
|
182
|
+
{
|
|
183
|
+
tag: 'svg', // автоматически запустится режим SVG
|
|
184
|
+
children: [
|
|
185
|
+
// и будет проброшен сюда
|
|
186
|
+
SVG.circle(10, 10, 5),
|
|
187
|
+
{
|
|
188
|
+
tag: 'line',
|
|
189
|
+
attrs: {}
|
|
190
|
+
},
|
|
191
|
+
],
|
|
192
|
+
},
|
|
193
|
+
],
|
|
194
|
+
class: ['some', 'class', foo && 'plus_me'], // добавить plus_me если foo - true
|
|
195
|
+
});
|
|
196
|
+
```
|
package/package.json
CHANGED
|
@@ -1,14 +1,21 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alexgyver/component",
|
|
3
|
-
"version": "1.3.
|
|
3
|
+
"version": "1.3.6",
|
|
4
4
|
"description": "Simple HTML&SVG element builder",
|
|
5
5
|
"main": "./Component.js",
|
|
6
6
|
"module": "./Component.js",
|
|
7
7
|
"types": "./Component.js",
|
|
8
|
+
"scripts": {
|
|
9
|
+
"build": "webpack --config ./webpack.config.js"
|
|
10
|
+
},
|
|
8
11
|
"repository": {
|
|
9
12
|
"type": "git",
|
|
10
13
|
"url": "git+https://github.com/GyverLibs/Component.js.git"
|
|
11
14
|
},
|
|
12
15
|
"author": "AlexGyver <alex@alexgyver.ru>",
|
|
13
|
-
"license": "MIT"
|
|
16
|
+
"license": "MIT",
|
|
17
|
+
"devDependencies": {
|
|
18
|
+
"webpack": "^5.98.0",
|
|
19
|
+
"webpack-cli": "^6.0.1"
|
|
20
|
+
}
|
|
14
21
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { EL, Sheet, StyledComponent } from "https://gyverlibs.github.io/EL.js/EL.min.js";
|
|
2
2
|
|
|
3
3
|
// кнопка наследует, стили добавляются отдельно
|
|
4
|
-
class Button extends
|
|
4
|
+
class Button extends EL {
|
|
5
5
|
constructor(text, handler) {
|
|
6
6
|
|
|
7
7
|
super('button', {
|
|
@@ -75,7 +75,7 @@ function Checkbox(name) {
|
|
|
75
75
|
}
|
|
76
76
|
|
|
77
77
|
function Container(children) {
|
|
78
|
-
return
|
|
78
|
+
return EL.make('div',
|
|
79
79
|
{
|
|
80
80
|
children: children,
|
|
81
81
|
});
|
|
@@ -83,7 +83,7 @@ function Container(children) {
|
|
|
83
83
|
|
|
84
84
|
class ShadowComponent {
|
|
85
85
|
constructor() {
|
|
86
|
-
|
|
86
|
+
EL.makeShadow('div', {
|
|
87
87
|
context: this,
|
|
88
88
|
parent: document.body,
|
|
89
89
|
events: {
|
|
@@ -106,7 +106,7 @@ class ShadowComponent {
|
|
|
106
106
|
document.addEventListener('kek', () => console.log('kek!'));
|
|
107
107
|
|
|
108
108
|
document.addEventListener("DOMContentLoaded", () => {
|
|
109
|
-
|
|
109
|
+
EL.make('h1', {
|
|
110
110
|
text: 'Hello!',
|
|
111
111
|
parent: document.body,
|
|
112
112
|
});
|
|
File without changes
|