@alexgyver/component 1.0.5 → 1.0.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/.gitattributes ADDED
@@ -0,0 +1,2 @@
1
+ # Auto detect text files and perform LF normalization
2
+ * text=auto
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 AlexGyver
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,3 @@
1
+ # Component.js
2
+
3
+ > npm i @alexgyver/component
package/component.js CHANGED
@@ -1,136 +1,136 @@
1
- export class Sheet {
2
- /**
3
- * @abstract Добавить стиль с уникальным id в head. ext - стиль можно будет удалить по id
4
- * @param {string|array} style стили в виде css строки или [ 'class', ['color: red', 'padding: 0'], ... ]
5
- * @param {string} id уникальный id стиля
6
- * @param {boolean} ext внешний стиль - может быть удалён по id
7
- */
8
- static addStyle(style, id, ext = false) {
9
- if (!style || !id) return;
10
- if (typeof id === 'object') id = id.constructor.name;
11
-
12
- if (!Sheet.#internal.has(id) && !Sheet.#external.has(id)) {
13
- if (typeof style === 'object') {
14
- let str = '';
15
- let f = 0;
16
- for (const v of style) {
17
- if (f = !f) {
18
- str += v;
19
- } else {
20
- str += '{';
21
- for (const rule of v) str += rule + ';';
22
- str += '}';
23
- }
24
- }
25
- style = str;
26
- }
27
-
28
- if (ext) {
29
- let sheet = document.createElement('style');
30
- document.head.appendChild(sheet);
31
- sheet.sheet.insertRule(style);
32
- Sheet.#external.set(id, sheet);
33
- } else {
34
- if (!Sheet.#sheet) {
35
- Sheet.#sheet = document.head.appendChild(document.createElement('style')).sheet;
36
- }
37
- Sheet.#sheet.insertRule(style);
38
- Sheet.#internal.add(id);
39
- }
40
- }
41
- }
42
-
43
- /**
44
- * @abstract Удалить ext стиль по его id
45
- * @param {string} id id стиля
46
- */
47
- static removeStyle(id) {
48
- if (Sheet.#external.has(id)) {
49
- Sheet.#external.get(id).remove();
50
- Sheet.#external.delete(id);
51
- }
52
- }
53
-
54
- static #sheet;
55
- static #internal = new Set();
56
- static #external = new Map();
57
- }
58
-
59
- export class Component {
60
- /**
61
- * @abstract Создать компонент и поместить его в переменную $root
62
- * @param {string} tag html tag элемента
63
- * @param {object} data параметры
64
- * @param {string|array} style стили в виде css строки или [ 'class', ['color: red', 'padding: 0'], ... ]
65
- * @param {string|this} id уникальный id стиля
66
- * @param {boolean} ext внешний стиль - может быть удалён по id
67
- */
68
- constructor(tag, data = {}, style = null, id = null, ext = false) {
69
- data.context = this;
70
- this.$root = Component.make(tag, data, style, id, ext);
71
- }
72
-
73
- /*
74
- tag {string} тег html элемента (для указания в children например)
75
- context {object} контекст для параметра 'var' и вызовов 'also'
76
- text {string} добавить в textContent
77
- html {string} добавить в innerHTML
78
- class {string} добавить в className
79
- also {function} - вызвать с текущим компонентом: { ... , also(el) { console.log(el); }, }
80
- var {string} создаёт переменную $имя в указанном контексте
81
- events {object} добавляет addEventListener'ы {event: handler}
82
- append - {Element} добавляет компонент к указанному элементу (имеет смысл только для корневого компонента)
83
- style {string | object} объект в виде { padding: '0px', ... } или строка css стилей
84
- children - массив DOM, Component, object, html string
85
- */
86
- /**
87
- * @abstract Создать компонент
88
- * @param {string} tag html tag элемента
89
- * @param {object} data параметры
90
- * @param {string|array} style стили в виде css строки или [ 'class', ['color: red', 'padding: 0'], ... ]
91
- * @param {string|this} id уникальный id стиля
92
- * @param {boolean} ext внешний стиль - может быть удалён по id
93
- */
94
- static make(tag, data = {}, style = null, id = null, ext = false) {
95
- Sheet.addStyle(style, id, ext);
96
- if (!tag || typeof data !== 'object') return null;
97
- if (data instanceof Node) return data;
98
-
99
- const context = data.context;
100
- const $el = document.createElement(tag);
101
-
102
- for (const [key, val] of Object.entries(data)) {
103
- switch (key) {
104
- case 'tag':
105
- case 'context':
106
- continue;
107
- case 'text': $el.textContent = val; break;
108
- case 'html': $el.innerHTML = val; break;
109
- case 'class': $el.className = val; break;
110
- case 'also': if (context) val.call(context, $el); break;
111
- case 'var': if (context) context['$' + val] = $el; break;
112
- case 'events': for (const [ev, handler] of Object.entries(val)) $el.addEventListener(ev, handler.bind(context)); break;
113
- case 'append': if (val instanceof Element) val.append($el); break;
114
- case 'style':
115
- if (typeof val === 'string') $el.style = val + ';';
116
- else for (const [skey, sval] of Object.entries(val)) $el.style[skey] = sval;
117
- break;
118
- case 'children':
119
- for (const obj of val) {
120
- if (obj instanceof Node) $el.appendChild(obj);
121
- else if (obj instanceof Component) $el.appendChild(obj.$root);
122
- else if (typeof obj === 'object') {
123
- if (!obj.context) obj.context = context;
124
- let cmp = Component.make(obj.tag, obj);
125
- if (cmp) $el.appendChild(cmp);
126
- } else if (typeof obj === 'string') {
127
- $el.innerHTML += obj;
128
- }
129
- }
130
- break;
131
- default: $el[key] = val; break;
132
- }
133
- }
134
- return $el;
135
- }
1
+ export class Sheet {
2
+ /**
3
+ * Добавить стиль с уникальным id в head. ext - стиль можно будет удалить по id
4
+ * @param {string|array} style стили в виде css строки или [ 'class', ['color: red', 'padding: 0'], ... ]
5
+ * @param {string} id уникальный id стиля
6
+ * @param {boolean} ext внешний стиль - может быть удалён по id
7
+ */
8
+ static addStyle(style, id, ext = false) {
9
+ if (!style || !id) return;
10
+ if (typeof id === 'object') id = id.constructor.name;
11
+
12
+ if (!Sheet.#internal.has(id) && !Sheet.#external.has(id)) {
13
+ if (typeof style === 'object') {
14
+ let str = '';
15
+ let f = 0;
16
+ for (const v of style) {
17
+ if (f = !f) {
18
+ str += v;
19
+ } else {
20
+ str += '{';
21
+ for (const rule of v) str += rule + ';';
22
+ str += '}';
23
+ }
24
+ }
25
+ style = str;
26
+ }
27
+
28
+ if (ext) {
29
+ let sheet = document.createElement('style');
30
+ document.head.appendChild(sheet);
31
+ sheet.sheet.insertRule(style);
32
+ Sheet.#external.set(id, sheet);
33
+ } else {
34
+ if (!Sheet.#sheet) {
35
+ Sheet.#sheet = document.head.appendChild(document.createElement('style')).sheet;
36
+ }
37
+ Sheet.#sheet.insertRule(style);
38
+ Sheet.#internal.add(id);
39
+ }
40
+ }
41
+ }
42
+
43
+ /**
44
+ * Удалить ext стиль по его id
45
+ * @param {string} id id стиля
46
+ */
47
+ static removeStyle(id) {
48
+ if (Sheet.#external.has(id)) {
49
+ Sheet.#external.get(id).remove();
50
+ Sheet.#external.delete(id);
51
+ }
52
+ }
53
+
54
+ static #sheet;
55
+ static #internal = new Set();
56
+ static #external = new Map();
57
+ }
58
+
59
+ export class Component {
60
+ /**
61
+ * Создать компонент и поместить его в переменную $root
62
+ * @param {string} tag html tag элемента
63
+ * @param {object} data параметры
64
+ * @param {string|array} style стили в виде css строки или [ 'class', ['color: red', 'padding: 0'], ... ]
65
+ * @param {string|this} id уникальный id стиля
66
+ * @param {boolean} ext внешний стиль - может быть удалён по id
67
+ */
68
+ constructor(tag, data = {}, style = null, id = null, ext = false) {
69
+ data.context = this;
70
+ this.$root = Component.make(tag, data, style, id, ext);
71
+ }
72
+
73
+ /*
74
+ tag {string} тег html элемента (для указания в children например)
75
+ context {object} контекст для параметра 'var' и вызовов 'also'
76
+ text {string} добавить в textContent
77
+ html {string} добавить в innerHTML
78
+ class {string} добавить в className
79
+ also {function} - вызвать с текущим компонентом: { ... , also(el) { console.log(el); }, }
80
+ var {string} создаёт переменную $имя в указанном контексте
81
+ events {object} добавляет addEventListener'ы {event: handler}
82
+ append - {Element} добавляет компонент к указанному элементу (имеет смысл только для корневого компонента)
83
+ style {string | object} объект в виде { padding: '0px', ... } или строка css стилей
84
+ children - массив DOM, Component, object, html string
85
+ */
86
+ /**
87
+ * Создать компонент
88
+ * @param {string} tag html tag элемента
89
+ * @param {object} data параметры
90
+ * @param {string|array} style стили в виде css строки или [ 'class', ['color: red', 'padding: 0'], ... ]
91
+ * @param {string|this} id уникальный id стиля
92
+ * @param {boolean} ext внешний стиль - может быть удалён по id
93
+ */
94
+ static make(tag, data = {}, style = null, id = null, ext = false) {
95
+ Sheet.addStyle(style, id, ext);
96
+ if (!tag || typeof data !== 'object') return null;
97
+ if (data instanceof Node) return data;
98
+
99
+ const context = data.context;
100
+ const $el = document.createElement(tag);
101
+
102
+ for (const [key, val] of Object.entries(data)) {
103
+ switch (key) {
104
+ case 'tag':
105
+ case 'context':
106
+ continue;
107
+ case 'text': $el.textContent = val; break;
108
+ case 'html': $el.innerHTML = val; break;
109
+ case 'class': $el.className = val; break;
110
+ case 'also': if (context) val.call(context, $el); break;
111
+ case 'var': if (context) context['$' + val] = $el; break;
112
+ case 'events': for (const [ev, handler] of Object.entries(val)) $el.addEventListener(ev, handler.bind(context)); break;
113
+ case 'append': if (val instanceof Element) val.append($el); break;
114
+ case 'style':
115
+ if (typeof val === 'string') $el.style = val + ';';
116
+ else for (const [skey, sval] of Object.entries(val)) $el.style[skey] = sval;
117
+ break;
118
+ case 'children':
119
+ for (const obj of val) {
120
+ if (obj instanceof Node) $el.appendChild(obj);
121
+ else if (obj instanceof Component) $el.appendChild(obj.$root);
122
+ else if (typeof obj === 'object') {
123
+ if (!obj.context) obj.context = context;
124
+ let cmp = Component.make(obj.tag, obj);
125
+ if (cmp) $el.appendChild(cmp);
126
+ } else if (typeof obj === 'string') {
127
+ $el.innerHTML += obj;
128
+ }
129
+ }
130
+ break;
131
+ default: $el[key] = val; break;
132
+ }
133
+ }
134
+ return $el;
135
+ }
136
136
  }
package/example.html ADDED
@@ -0,0 +1,15 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+
4
+ <head>
5
+ <meta charset="UTF-8">
6
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
7
+ <title>Document</title>
8
+ <script type="module" src="script.js"></script>
9
+ </head>
10
+
11
+ <body>
12
+
13
+ </body>
14
+
15
+ </html>
package/package.json CHANGED
@@ -1,20 +1,14 @@
1
- {
2
- "name": "@alexgyver/component",
3
- "version": "1.0.5",
4
- "description": "Simple HTML element builder",
5
- "main": "./component.js",
6
- "module": "./component.js",
7
- "scripts": {
8
- "test": "echo \"Error: no test specified\" && exit 1"
9
- },
10
- "repository": {
11
- "type": "git",
12
- "url": "git+https://github.com/GyverLibs/Component.js.git"
13
- },
14
- "author": "AlexGyver <alex@alexgyver.ru>",
15
- "license": "MIT",
16
- "bugs": {
17
- "url": "https://github.com/GyverLibs/Component.js/issues"
18
- },
19
- "homepage": "https://github.com/GyverLibs/Component.js#readme"
1
+ {
2
+ "name": "@alexgyver/component",
3
+ "version": "1.0.6",
4
+ "description": "Simple HTML element builder",
5
+ "main": "./component.js",
6
+ "module": "./component.js",
7
+ "types": "./component.js",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/GyverLibs/Component.js.git"
11
+ },
12
+ "author": "AlexGyver <alex@alexgyver.ru>",
13
+ "license": "MIT"
20
14
  }
package/script.js ADDED
@@ -0,0 +1,106 @@
1
+ import { Component, Sheet } from "./component.js";
2
+
3
+ // кнопка наследует, стили добавляются отдельно
4
+ class Button extends Component {
5
+ constructor(text, handler) {
6
+
7
+ super('button', {
8
+ text: text,
9
+ class: 'btn',
10
+ style: 'border-radius: 5px',
11
+ events: {
12
+ click: handler,
13
+ },
14
+ also(el) {
15
+ // console.log('123');
16
+ }
17
+ });
18
+
19
+ Sheet.addStyle([
20
+ '.btn', [
21
+ 'background: red',
22
+ 'color: white'
23
+ ]
24
+ ], this, true); // this превратится в Button
25
+ }
26
+ }
27
+
28
+ // инпут сразу добавляет стили
29
+ class Input extends Component {
30
+ constructor(text) {
31
+ super('input',
32
+ {
33
+ type: 'text',
34
+ value: text,
35
+ class: 'inp',
36
+ },
37
+ [
38
+ '.inp', [
39
+ 'background: blue'
40
+ ]
41
+ ],
42
+ 'Input'
43
+ );
44
+ }
45
+ }
46
+
47
+ class Num {
48
+ constructor(text) {
49
+ return new Component('input',
50
+ {
51
+ type: 'number',
52
+ value: text,
53
+ class: 'num',
54
+ },
55
+ [
56
+ '.num', [
57
+ 'background: green',
58
+ 'margin-left: 10px',
59
+ ]
60
+ ],
61
+ 'Num'
62
+ );
63
+ }
64
+ }
65
+
66
+ // функция вернёт элемент
67
+ function Checkbox(name) {
68
+ return Component.make('div',
69
+ {
70
+ children: [
71
+ {
72
+ tag: 'input',
73
+ type: 'checkbox'
74
+ },
75
+ `<label class=check>${name}</label>`,
76
+ ]
77
+ },
78
+ '.check {font-size: 20px;}',
79
+ 'Checkbox'
80
+ );
81
+ }
82
+
83
+ function Container(children) {
84
+ return Component.make('div',
85
+ {
86
+ children: children,
87
+ });
88
+ }
89
+
90
+ document.addEventListener("DOMContentLoaded", () => {
91
+ Component.make('h1', {
92
+ text: 'Hello!',
93
+ append: document.body,
94
+ });
95
+
96
+ let b = new Button('b1', () => console.log(123));
97
+
98
+ let cont = Container([b, new Button('b2', () => console.log('hello')), new Input('hello'), new Num('123')]);
99
+ document.body.appendChild(cont);
100
+
101
+ document.body.appendChild(Checkbox('kek'));
102
+ document.body.appendChild(Checkbox('pek'));
103
+
104
+ // Sheet.removeStyle('Button');
105
+ // Sheet.removeStyle('Checkbox');
106
+ });