als-layout 1.3.3 → 2.0.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.
@@ -0,0 +1,19 @@
1
+ const componentHierarchy = require('./component-hierarchy')
2
+ module.exports = function(done=[],layout) {
3
+ const strComponents = 'components:{'+componentHierarchy(done).map(componentName => {
4
+ return `"${componentName}":${layout.components[componentName].toString()}`
5
+ }).join(',')+'}'
6
+ const updateFn = `update:function ${layout.update.toString()}`
7
+ const strData = 'data:'+JSON.stringify(layout.data)
8
+ const $ = 'function $(selector,parent = document) {return parent.querySelector(selector)}'
9
+ const $$ = 'function $$(selector,parent = document) {return [...parent.querySelectorAll(selector)]}'
10
+ let actions = 'actions:{'
11
+ for(const actionName in layout.actions) {
12
+ actions += `${actionName}:${layout.actions[actionName].toString()},`
13
+ }
14
+ let utils = 'utils:{'
15
+ for(const utilsName in layout.utils) {
16
+ utils += `${utilsName}:${layout.utils[utilsName].toString()},`
17
+ }
18
+ return `window.$App = {browser:true,${strData},${strComponents},${actions}},${utils}},${updateFn},$:${$},$$:${$$}}`
19
+ }
package/lib/build-root.js CHANGED
@@ -4,7 +4,7 @@ function buildRoot(item) {
4
4
  const root =
5
5
  (item instanceof Root) ? buildFromCache(cacheDoc(item))
6
6
  : (typeof item === 'string') ? parseHTML(item)
7
- : (typeof item === 'object') ? buildFromCache(item)
7
+ : (typeof item === 'object' && item.tagName) ? buildFromCache(item)
8
8
  : new Root()
9
9
 
10
10
  const firstNode = root.childNodes[0]
@@ -0,0 +1,20 @@
1
+ function componentHierarchy(elements) {
2
+ const entries = elements
3
+ .map(el => ([el, el.getAttribute('component'), el.ancestors]))
4
+ .sort((a, b) => a[2].length - b[2].length)
5
+
6
+ const result = []
7
+ while(entries.length > 0) {
8
+ const [element, componentName, ancestors] = entries.shift()
9
+ entries.forEach(entry => {
10
+ if(entry[1] !== componentName) return
11
+ if(entry[2].includes(element)) {
12
+ throw new Error(`The component '${componentName}' acts as both a parent and a child, which may complicate rendering.`);
13
+ }
14
+ });
15
+ if(!result.includes(componentName)) result.push(componentName)
16
+ }
17
+ return result
18
+ }
19
+
20
+ module.exports = componentHierarchy
@@ -1,6 +1,6 @@
1
1
  const addMeta = require('./add-meta')
2
2
  function addImage(image,version, layout) {
3
- if (image && version) image += src.includes('?') ? '&' : '?' + `v=${version}`
3
+ if (image && version) image += (image.includes('?') ? '&' : '?') + `v=${version}`
4
4
 
5
5
  addMeta({property:'og:image',content:image},layout)
6
6
  addMeta({name:'twitter:image',content:image},layout)
@@ -3,17 +3,17 @@ const { SingleNode } = require('als-document')
3
3
  function keywords(keywords = [], layout) {
4
4
  const { root } = layout
5
5
  let keywordsElement = root.$('meta[name=keywords]')
6
- if (!keywordsElement) {
7
- keywordsElement = new SingleNode('meta', { name: 'keywords' })
8
- layout.head.insert(2, keywordsElement)
9
- }
6
+ if (!keywordsElement) keywordsElement = new SingleNode('meta', { name: 'keywords' })
10
7
  const content = keywordsElement.getAttribute('content')
11
8
  const existingKeywords = content ? content.split(',') : []
12
9
  keywords.forEach(keyword => {
13
10
  keyword = keyword.trim()
14
11
  if (!existingKeywords.includes(keyword)) existingKeywords.push(keyword)
15
12
  });
16
- keywordsElement.setAttribute('content', existingKeywords.join())
13
+ if(existingKeywords.length) {
14
+ keywordsElement.setAttribute('content', existingKeywords.join())
15
+ layout.head.insert(2, keywordsElement)
16
+ }
17
17
  return layout
18
18
  }
19
19
 
@@ -1,10 +1,10 @@
1
1
  const { SingleNode } = require('als-document')
2
2
  function addLink(href, version, layout) {
3
3
  if(!href || typeof href !== 'string') return layout
4
+ if (href && version) href += (href.includes('?') ? '&' : '?') + `v=${version}`
4
5
  const selector = `link[rel=stylesheet][href^="${href}"]`
5
6
  let linkElement = layout.root.$(selector)
6
7
  if (linkElement) return
7
- if (href && version) href += href.includes('?') ? '&' : '?' + `v=${version}`
8
8
  linkElement = new SingleNode('link', { rel: 'stylesheet', href })
9
9
  layout.head.insert(2, linkElement)
10
10
  return layout
@@ -4,7 +4,7 @@ function addScript(attrs = {}, innerHTML = '', head = true, version, layout) {
4
4
  if(attrs.src) {
5
5
  const selector = `script[src="${attrs.src}"]`
6
6
  if (attrs.src && layout.root.$(selector)) return layout
7
- if (attrs.src && version) attrs.src += attrs.src.includes('?') ? '&' : '?' + `v=${version}`
7
+ if (attrs.src && version) attrs.src += (attrs.src.includes('?') ? '&' : '?') + `v=${version}`
8
8
  }
9
9
  if(Object.keys(attrs).length || innerHTML) {
10
10
  const script = new Node('script', attrs)
package/lib/layout.js CHANGED
@@ -3,6 +3,7 @@ const {
3
3
  addKeywords, addStyle, addDescription, addTitle, addImage,
4
4
  addUrl, addFavicon, addScript, addLink, charset, viewport
5
5
  } = require('./elements/index')
6
+ const build$App = require('./build-app')
6
7
  const buildRoot = require('./build-root')
7
8
 
8
9
  class Layout {
@@ -10,40 +11,67 @@ class Layout {
10
11
  this.options = options
11
12
  this.root = buildRoot(layout)
12
13
  this.body; this.head;
14
+ this.components = {}
15
+ this.data = {}
16
+ this.actions = {}
17
+ this.utils = {}
13
18
  }
14
19
 
15
20
  get html() {
16
21
  const lang = this.options.lang || 'en'
17
- if (!this.root.$('html')) this.root.insert(2,`<html></html>`)
22
+ if (!this.root.$('html')) this.root.insert(2, `<html></html>`)
18
23
  const htmlElement = this.root.$('html')
19
- if(lang && htmlElement.getAttribute('lang') !== lang) {
20
- htmlElement.setAttribute('lang',lang)
24
+ if (lang && htmlElement.getAttribute('lang') !== lang) {
25
+ htmlElement.setAttribute('lang', lang)
21
26
  }
22
27
  return htmlElement
23
28
  }
24
29
  get body() {
25
- if (!this.root.body) this.html.insert(2,`<body></body>`)
30
+ if (!this.root.body) this.html.insert(2, `<body></body>`)
26
31
  return this.root.body
27
32
  }
28
33
  get head() {
29
- if (!this.root.head) this.html.insert(1,`<head></head>`)
34
+ if (!this.root.head) this.html.insert(1, `<head></head>`)
30
35
  return this.root.head
31
36
  }
32
37
 
38
+ update(element, done = []) {
39
+ for (const componentName in this.components) {
40
+ const fn = this.components[componentName]
41
+ let components = element.getAttribute('component') === componentName
42
+ ? [element]
43
+ : [...element.querySelectorAll(`[component=${componentName}]`)]
44
+ components = components.filter(el => !done.includes(el))
45
+ components.forEach((element, i) => {
46
+ element.componentIndex = i
47
+ fn(element, this)
48
+ done.push(element)
49
+ this.update(element, done)
50
+ });
51
+ }
52
+ }
53
+
54
+ render() {
55
+ const done = []
56
+ this.update(this.root, done)
57
+ this.script({}, build$App(done,this),false)
58
+ return this.rawHtml
59
+ }
60
+
33
61
  get rawHtml() { return this.root.innerHTML }
34
62
  get cached() { return cacheDoc(this.root) }
35
63
  get clone() { return new Layout(this.root, this.options) }
36
64
 
37
- version(v) {this.v = v; return this;}
65
+ version(v) { this.v = v; return this; }
38
66
  keywords(keywords = []) { return addKeywords(keywords, this) }
39
67
  description(description) { return addDescription(description, this) }
40
68
  title(title) { return addTitle(title, this) }
41
69
  style(styles, minified) { return addStyle(styles, minified, this) }
42
- image(image,v=this.v) { return addImage(image, v, this) }
70
+ image(image, v = this.v) { return addImage(image, v, this) }
43
71
  url(url, host = this.options.host) { return addUrl(url, host, this) }
44
72
  favicon(href) { return addFavicon(href, this) }
45
- script(attributes, innerHTML, head = true, v=this.v) { return addScript(attributes, innerHTML, head, v, this) }
46
- link(href, v=this.v) { return addLink(href, v, this) }
73
+ script(attributes, innerHTML, head = true, v = this.v) { return addScript(attributes, innerHTML, head, v, this) }
74
+ link(href, v = this.v) { return addLink(href, v, this) }
47
75
  charset(newCharset = 'UTF-8') { return charset(newCharset, this) }
48
76
  viewport(newViewport = 'width=device-width, initial-scale=1.0') { return viewport(newViewport, this) }
49
77
  }
package/package.json CHANGED
@@ -1,13 +1,14 @@
1
1
  {
2
2
  "name": "als-layout",
3
- "version": "1.3.3",
3
+ "version": "2.0.0",
4
4
  "description": "Html layout constructor",
5
5
  "main": "index.js",
6
6
  "directories": {
7
7
  "lib": "lib"
8
8
  },
9
9
  "scripts": {
10
- "test": "node --test --experimental-test-coverage"
10
+ "test": "node --test --experimental-test-coverage",
11
+ "report": "node --test --experimental-test-coverage --test-reporter=lcov --test-reporter-destination=lcov.info"
11
12
  },
12
13
  "keywords": [],
13
14
  "author": "Alex Sorkin",
package/readme.md CHANGED
@@ -1,20 +1,19 @@
1
1
  # Als-layout
2
2
 
3
- Html layout constructor.
3
+ `Als-layout` is an HTML layout constructor for Node.js that allows you to manage HTML elements, styles, and scripts through JavaScript. It's perfect for server-side HTML generation or dynamic page modifications before delivery to the client.
4
4
 
5
- ## Change log
6
- * styles as separated tags
7
- * version method
8
- * script,link,image - version parameter
9
- * updated als-document version
5
+ ## What's New
10
6
 
11
- ## install
7
+ - **Rendering Capability**: Added the ability to render HTML dynamically, updating elements based on component attributes.
8
+ - **Bug Fixes**: Various bug fixes improving stability and performance.
9
+
10
+ ## Install
12
11
 
13
12
  ```bash
14
13
  npm i als-layout
15
14
  ```
16
15
 
17
- ## Basic usage
16
+ ## Basic Usage
18
17
 
19
18
  ```js
20
19
  const Layout = require('als-layout')
@@ -23,30 +22,29 @@ const layout = new Layout()
23
22
  .viewport() // default width=device-width, initial-scale=1.0
24
23
  .title('Test title') // adding/updating title and meta[og:title]
25
24
  .favicon('/favicon.png') // adding/updating link[rel=icon][type=image/x-icon] with new href
26
- .keywords(['some','keyword']) // adding/updating meta[name=keywords]. not adding existing keywords
27
- .image('/main-image.png','1.5') // adding/updating meta - og:image,twitter:image,twitter:card
28
- .description('Cool site') // adding/updating meta og:description,twitter:description and description tag
29
- .version('1.0.0') // adds version parameter to link, script.src and image
25
+ .keywords(['some', 'keyword']) // adding/updating meta[name=keywords]. not adding existing keywords
26
+ .image('/main-image.png', '1.5') // adding/updating meta - og:image, twitter:image, twitter:card
27
+ .description('Cool site') // adding/updating meta og:description, twitter:description, and description tag
28
+ .version('1.0.0') // adds version parameter to link, script.src, and image
30
29
  .url('/some', 'http://site.com') // adding/updating meta[og:url] and link[rel="canonical"]
31
- .style([{body:{m:0,bgc:'whitesmoke'}}]) // adding as simple-css styles to existing/new style tag
32
- .style('body {margin:0; backgroung-color:whitesmoke;}',true) // adding css styles to existing/new style tag. Second parameter is minified (default=false).
33
- .link('/styles.css','2.0') // adding link[rel=stylesheet] if such href not exists
34
- .script({src:'/app.js'},'', true,'3.0') // set script with src to head if such src not exists
30
+ .style([{body:{m:0, bgc:'whitesmoke'}}]) // adding as simple-css styles to existing/new style tag
31
+ .style('body {margin:0; background-color:whitesmoke;}', true) // adding css styles to existing/new style tag. Second parameter is minified (default=false).
32
+ .link('/styles.css', '2.0') // adding link[rel=stylesheet] if such href not exists
33
+ .script({src:'/app.js'}, '', true, '3.0') // set script with src to head if such src not exists
35
34
  .script({}, 'console.log("hello world")', false) // set script with script code to footer
36
35
 
37
-
36
+ // Accessors for document parts
38
37
  layout.body // getter for body element (if not exists, created)
39
38
  layout.head // getter for head element (if not exists, created)
40
39
  layout.html // getter for html element (if not exists, created)
41
40
 
41
+ // Outputs
42
42
  layout.rawHtml // raw html
43
43
  layout.cached // cached DOM
44
- layout.clone // new layout object clone for curent object
44
+ layout.clone // new layout object clone for current object
45
45
  ```
46
46
 
47
- In image, script.src and link, last parameter is version which using 'layout.v' (defined by layout.version(v)) if not defined.
48
-
49
- ## Advanced usage
47
+ ## Advanced Usage
50
48
 
51
49
  ```js
52
50
  const Layout = require('./lib/layout')
@@ -56,14 +54,73 @@ const options = {
56
54
  host:'http://example.com', // host for url method
57
55
  lang:'fr' // for <html lang="fr"></html>
58
56
  }
59
- const layout = new Layout(raw,options)
57
+ const layout = new Layout(raw, options)
60
58
  console.log(layout.rawHtml)
61
59
  // <!DOCTYPE html><html lang="fr"><head></head><body></body></html>
62
60
 
63
61
  const homePage = layout.clone
64
62
  homePage.title('Home page')
65
63
  homePage.body.innerHTML = /*html*/`<h1>Home page</h1>`
66
- console.log(homePage.rawHtml)
64
+ console.log(homePage.rawHtml)
67
65
  // <!DOCTYPE html><html lang="fr"><head><title>Home page</title><meta property="og:title" content="Home page"></head><body><h1>Home page</h1></body></html>
68
66
  ```
69
67
 
68
+ ## Rendering
69
+
70
+ Each layout instance has a render method and the following objects:
71
+ ```js
72
+ layout.data
73
+ layout.components
74
+ layout.utils
75
+ layout.actions
76
+ ```
77
+
78
+ The render method returns raw HTML after building elements with the attribute component. It will create HTML raw which will include a `window.$App` object with the following:
79
+
80
+ ```js
81
+ window.$App = {
82
+ data,
83
+ components,
84
+ utils,
85
+ actions,
86
+ $(selector, parent=document), // querySelector
87
+ $$(selector, parent=document), // querySelectorAll
88
+ update(element), // update element if it has component attribute
89
+ }
90
+ ```
91
+
92
+
93
+ ## Counter Example
94
+
95
+ ```js
96
+ const fs = require('fs')
97
+ const Layout = require('als-layout')
98
+
99
+ const layout = new Layout().charset().viewport().title('Counter')
100
+ layout.data.counter = 0
101
+ layout.components.counter = function(element, $App) {
102
+ element.innerHTML = `${$App.data.counter}`
103
+ }
104
+
105
+ layout.actions = {
106
+ increase: () => { $App.data.counter++; $App.update($App.$('[component=counter]')) },
107
+ decrease: () => { $App.data.counter--; $App.update($App.$('[component=counter]')) }
108
+ }
109
+
110
+ layout.body.innerHTML = /*html*/`
111
+ <button onclick="$App.actions.increase()">Increase</button>
112
+ <span component="counter"></span>
113
+ <button onclick="$App.actions.decrease()">Decrease</button>
114
+ `
115
+ const time1 = performance.now()
116
+ const rawHtml = layout.render()
117
+ const time2 = performance.now()
118
+ console.log(`${time2 - time1}ms`) // e.g., 1.0649ms
119
+
120
+ fs.writeFileSync('counter.html', rawHtml, 'utf-8')
121
+ ```
122
+
123
+ Each component gets a `componentIndex` which is available inside the component function.
124
+ ```js
125
+ element.componentIndex
126
+ ```
@@ -0,0 +1,69 @@
1
+ const assert = require('assert');
2
+ const { describe, it } = require('node:test');
3
+ const build$App = require('../lib/build-app');
4
+
5
+ describe('build-$App Functionality', () => {
6
+ it('should handle empty input arrays correctly', () => {
7
+ const done = [];
8
+ const layout = {
9
+ components: {},
10
+ update: () => { }
11
+ };
12
+ const result = build$App(done, layout);
13
+ assert.strictEqual(result, 'window.$App = {browser:true,data:undefined,components:{},actions:{},utils:{},update:function () => { },$:function $(selector,parent = document) {return parent.querySelector(selector)},$$:function $$(selector,parent = document) {return [...parent.querySelectorAll(selector)]}}');
14
+ });
15
+
16
+ it('should process multiple components correctly', () => {
17
+ const done = [
18
+ { getAttribute: () => 'comp1',ancestors:2 },
19
+ { getAttribute: () => 'comp2',ancestors:2 }
20
+ ];
21
+ const layout = {
22
+ components: {
23
+ comp1: () => 'Component1',
24
+ comp2: () => 'Component2'
25
+ },
26
+ actions: {},
27
+ utils: {},
28
+ data: {},
29
+ update: function update() { }
30
+ };
31
+ const result = build$App(done, layout);
32
+ assert(result.includes(`"comp1":${layout.components.comp1.toString()}`))
33
+ assert(result.includes(`"comp2":${layout.components.comp2.toString()}`))
34
+ });
35
+
36
+ it('should add action functions correctly', () => {
37
+ const done = [];
38
+ const layout = {
39
+ components: {},
40
+ actions: {
41
+ action1: () => console.log('Action 1'),
42
+ action2: () => console.log('Action 2')
43
+ },
44
+ utils: {},
45
+ data: {},
46
+ update: function update() { }
47
+ };
48
+ const result = build$App(done, layout);
49
+ assert(result.includes(`action1:${layout.actions.action1.toString()}`))
50
+ assert(result.includes(`action2:${layout.actions.action2.toString()}`))
51
+ });
52
+
53
+ it('should integrate utilities correctly', () => {
54
+ const done = [];
55
+ const layout = {
56
+ components: {},
57
+ actions: {},
58
+ utils: {
59
+ util1: () => console.log('Utility 1'),
60
+ util2: () => console.log('Utility 2')
61
+ },
62
+ data: {},
63
+ update: function update() { }
64
+ };
65
+ const result = build$App(done, layout);
66
+ assert(result.includes(`util1:${layout.utils.util1.toString()}`))
67
+ assert(result.includes(`util2:${layout.utils.util2.toString()}`))
68
+ });
69
+ });
@@ -22,4 +22,24 @@ describe('Basic tests', function () {
22
22
  const root = buildRoot()
23
23
  assert(root.childNodes[0].tagName === '!DOCTYPE')
24
24
  });
25
- })
25
+
26
+ it('should create an instance of Root from HTML string', () => {
27
+ const htmlString = '<html><head><title>Test</title></head><body></body></html>';
28
+ const root = buildRoot(htmlString);
29
+ assert(root instanceof Root);
30
+ assert.strictEqual(root.childNodes.length > 0, true);
31
+ assert.strictEqual(root.childNodes[0].tagName, '!DOCTYPE');
32
+ });
33
+
34
+ it('should create an instance of Root from object', () => {
35
+ const docObject = cacheDoc('<html></html>')
36
+ const root = buildRoot(docObject);
37
+ assert(root instanceof Root);
38
+ });
39
+
40
+ it('should create an empty Root if object does not have tagName', () => {
41
+ const root = buildRoot({});
42
+ assert(root instanceof Root);
43
+ });
44
+ })
45
+
@@ -0,0 +1,51 @@
1
+ const { parseHTML } = require('als-document')
2
+ const assert = require('assert');
3
+ const { describe, it } = require('node:test')
4
+ const componentHierarchy = require('../lib/component-hierarchy')
5
+
6
+ function shuffleArray(array) {
7
+ for (let i = array.length - 1; i > 0; i--) {
8
+ const j = Math.floor(Math.random() * (i + 1)); // Получаем случайный индекс от 0 до i
9
+ [array[i], array[j]] = [array[j], array[i]]; // Обмен элементов местами
10
+ }
11
+ return array;
12
+ }
13
+
14
+ describe('Basic tests', () => {
15
+ it('should build correct hierarchy', () => {
16
+ const root = parseHTML(/*html*/`<div component="some">
17
+ <div>
18
+ <div component="some1"></div>
19
+ <div>
20
+ <div component="some2">
21
+ <div component="some3"></div>
22
+ </div>
23
+ <div component="some2"></div>
24
+ </div>
25
+
26
+ </div>
27
+ </div>`)
28
+
29
+ const result = componentHierarchy(shuffleArray(root.$$('[component]')))
30
+ assert.deepStrictEqual(result,[ 'some', 'some1', 'some2', 'some3' ])
31
+ })
32
+
33
+ it('should build correct hierarchy', () => {
34
+ const root = parseHTML(/*html*/`<div component="some">
35
+ <div>
36
+ <div component="some1"></div>
37
+ <div>
38
+ <div component="some2">
39
+ <div component="some3"></div>
40
+ </div>
41
+ <div component="some2">
42
+ <div component="some"></div>
43
+ </div>
44
+ </div>
45
+
46
+ </div>
47
+ </div>`)
48
+
49
+ assert.throws(() => componentHierarchy(shuffleArray(root.$$('[component]'))))
50
+ })
51
+ })
@@ -2,31 +2,80 @@ const assert = require('assert');
2
2
  const Layout = require('../lib/layout');
3
3
  const { describe, it, beforeEach } = require('node:test')
4
4
  const Simple = require('als-simple-css')
5
- describe('Elements Integration', () => {
5
+ const { SingleNode } = require('als-document')
6
+ const keywords = require('../lib/elements/keywords')
7
+
8
+ describe('Charset tests', () => {
6
9
  let layout;
7
10
 
8
11
  beforeEach(() => layout = new Layout());
9
12
 
13
+ it('should update charset if meta[charset] already exists', () => {
14
+ layout.head.insert(1, new SingleNode('meta', { charset: 'old-charset' }));
15
+ const newCharset = 'new-charset';
16
+ layout.charset(newCharset);
17
+ assert.strictEqual(layout.root.$('meta[charset]').getAttribute('charset'), newCharset, 'Charset should be updated');
18
+ });
19
+
20
+ it('should insert charset at second position if not present', () => {
21
+ layout.head.insert(1, new SingleNode('title', {}));
22
+ const charset = 'UTF-8';
23
+ layout.charset(charset);
24
+ assert.strictEqual(layout.head.childNodes[1].tagName, 'meta', 'Meta should be at second position');
25
+ assert.strictEqual(layout.head.childNodes[1].getAttribute('charset'), charset, 'Charset not set correctly');
26
+ });
27
+
10
28
  it('should add charset correctly', () => {
11
29
  const charset = 'test';
12
30
  layout.charset(charset);
13
31
  assert.strictEqual(layout.root.$('meta[charset]').getAttribute('charset'), charset, 'Charset not set correctly');
14
32
  });
33
+ });
15
34
 
16
- it('should add description correctly', () => {
17
- const description = 'Test Description';
18
- layout.description(description);
19
- assert.strictEqual(layout.root.$('meta[name="description"]').getAttribute('content'), description, 'Description not set correctly');
20
- assert.strictEqual(layout.root.$('meta[property="og:description"]').getAttribute('content'), description, 'Description not set correctly');
21
- assert.strictEqual(layout.root.$('meta[property="twitter:description"]').getAttribute('content'), description, 'Description not set correctly');
35
+ describe('Favicon tests', () => {
36
+ let layout;
37
+
38
+ beforeEach(() => {
39
+ layout = new Layout();
40
+ layout.head.insert(1, new SingleNode('title', {})); // Добавляем элемент title для проверки позиции
22
41
  });
23
42
 
24
- it('should add favicon correctly', function () {
43
+ it('should update favicon href if link[rel="icon"] already exists', () => {
44
+ const oldHref = 'old-favicon.ico';
45
+ layout.head.insert(2, new SingleNode('link', { rel: 'icon', href: oldHref, type: 'image/x-icon' }));
46
+ const newHref = 'new-favicon.ico';
47
+ layout.favicon(newHref);
48
+ assert.strictEqual(layout.root.$('link[rel="icon"]').getAttribute('href'), newHref, 'Favicon href should be updated');
49
+ });
50
+
51
+ it('should insert favicon at second position if not present', () => {
52
+ const faviconHref = 'favicon.ico';
53
+ layout.favicon(faviconHref);
54
+ assert.strictEqual(layout.head.childNodes[1].tagName, 'link', 'Favicon link should be at second position');
55
+ assert.strictEqual(layout.head.childNodes[1].getAttribute('href'), faviconHref, 'Favicon href not set correctly');
56
+ });
57
+
58
+ it('should add favicon correctly', () => {
25
59
  const faviconHref = 'favicon.ico';
26
60
  layout.favicon(faviconHref);
27
61
  assert.strictEqual(layout.root.$('link[rel="icon"]').getAttribute('href'), faviconHref, 'Favicon not set correctly');
28
62
  });
29
63
 
64
+ });
65
+
66
+ describe('Image tests', () => {
67
+ let layout;
68
+
69
+ beforeEach(() => {
70
+ layout = new Layout();
71
+ });
72
+
73
+ it('should add twitter:card meta tag', () => {
74
+ const imageUrl = 'test-image.jpg';
75
+ layout.image(imageUrl);
76
+ assert.strictEqual(layout.root.$('meta[name="twitter:card"]').getAttribute('content'), 'summary_large_image', 'twitter:card not set correctly');
77
+ });
78
+
30
79
  it('should add image correctly', () => {
31
80
  const imageUrl = 'test-image.jpg';
32
81
  layout.image(imageUrl);
@@ -34,30 +83,53 @@ describe('Elements Integration', () => {
34
83
  assert.strictEqual(layout.root.$('meta[name="twitter:image"]').getAttribute('content'), imageUrl, 'Image not set correctly');
35
84
  });
36
85
 
37
- it('should add link correctly', () => {
38
- const href = 'style.css';
39
- layout.link(href);
40
- assert.strictEqual(layout.root.$('link[rel="stylesheet"]').getAttribute('href'), href, 'Link not set correctly');
86
+ it('should handle cases where image URL already has query parameters', () => {
87
+ const imageUrl = 'test-image.jpg?existing=param';
88
+ const version = '456';
89
+ layout.image(imageUrl, version);
90
+ const expectedUrl = imageUrl + '&v=' + version;
91
+ const img = layout.root.$('meta[property="og:image"]').getAttribute('content')
92
+ assert(img === expectedUrl, 'Versioned image URL with existing parameters not set correctly');
41
93
  });
42
94
 
43
- it('should add script correctly', () => {
44
- const scriptContent = 'console.log("Hello, world!");';
45
- layout.script({}, scriptContent);
46
- assert.strictEqual(layout.root.$('script').innerHTML, scriptContent, 'Script content not set correctly');
95
+ it('should add version parameter to image URL if version is provided', () => {
96
+ const imageUrl = 'test-image.jpg';
97
+ const version = '123';
98
+ layout.image(imageUrl, version);
99
+ const expectedUrl = imageUrl + '?v=' + version;
100
+ assert.strictEqual(layout.root.$('meta[property="og:image"]').getAttribute('content'), expectedUrl, 'Versioned image URL not set correctly in og:image');
101
+ assert.strictEqual(layout.root.$('meta[name="twitter:image"]').getAttribute('content'), expectedUrl, 'Versioned image URL not set correctly in twitter:image');
47
102
  });
103
+ });
48
104
 
49
- it('should add title correctly', () => {
50
- const title = 'Test Title';
51
- layout.title(title);
52
- assert(layout.root.$('title').innerHTML === title, 'Title not set correctly');
53
- assert(layout.root.$('[property="og:title"]').getAttribute('content') === title, 'Title not set correctly');
105
+ describe('Keywords tests', () => {
106
+ let layout;
107
+
108
+ beforeEach(() => {
109
+ layout = new Layout();
54
110
  });
55
111
 
112
+ it('should add new keywords to an existing meta tag', () => {
113
+ layout.head.insert(2, new SingleNode('meta', { name: 'keywords', content: 'initial' }));
114
+ const additionalKeywords = ['keyword1', 'keyword2'];
115
+ keywords(additionalKeywords, layout);
116
+ const expectedContent = 'initial,keyword1,keyword2';
117
+ assert.strictEqual(layout.root.$('meta[name="keywords"]').getAttribute('content'), expectedContent, 'Existing keywords not updated correctly');
118
+ });
56
119
 
57
- it('should add url correctly', () => {
58
- const url = 'http://localhost';
59
- layout.url(url);
60
- assert(layout.root.$('link[rel="canonical"]').getAttribute('href') === url, 'Canonical URL not set correctly');
120
+ it('should not add duplicate keywords', () => {
121
+ layout.head.insert(2, new SingleNode('meta', { name: 'keywords', content: 'keyword1,keyword2' }));
122
+ const additionalKeywords = ['keyword2', 'keyword3'];
123
+ keywords(additionalKeywords, layout);
124
+ const expectedContent = 'keyword1,keyword2,keyword3';
125
+ assert.strictEqual(layout.root.$('meta[name="keywords"]').getAttribute('content'), expectedContent, 'Duplicate keywords were added');
126
+ });
127
+
128
+ it('should handle keywords with leading or trailing spaces', () => {
129
+ const messyKeywords = [' keyword1', 'keyword2 '];
130
+ keywords(messyKeywords, layout);
131
+ const expectedContent = 'keyword1,keyword2';
132
+ assert.strictEqual(layout.root.$('meta[name="keywords"]').getAttribute('content'), expectedContent, 'Keywords with spaces not trimmed correctly');
61
133
  });
62
134
 
63
135
  it('should add keywords correctly', () => {
@@ -66,39 +138,91 @@ describe('Elements Integration', () => {
66
138
  assert(layout.root.$('meta[name="keywords"]').getAttribute('content') === keywords.join(), 'Keywords not set correctly');
67
139
  });
68
140
 
69
- it('should add viewport correctly', () => {
70
- const viewportContent = 'width=device-width, initial-scale=1.0';
71
- layout.viewport(viewportContent);
72
- assert.strictEqual(layout.root.$('meta[name="viewport"]').getAttribute('content'), viewportContent, 'Viewport not set correctly');
141
+ it('should handle empty keywords array', () => {
142
+ keywords([], layout);
143
+ assert(!layout.root.$('meta[name="keywords"]'), 'Meta tag for empty keywords should not be created');
73
144
  });
74
145
 
75
- it('should add style correctly', () => {
76
- const styles = 'body { background-color: black; }';
77
- layout.style(styles);
78
- assert(layout.root.$('style').innerHTML.includes(styles), 'Styles not set correctly');
146
+ });
147
+
148
+ describe('Link', () => {
149
+ let layout;
150
+ beforeEach(() => layout = new Layout());
151
+
152
+ it('should add a new link element without version', () => {
153
+ const href = 'style.css';
154
+ layout.link(href);
155
+ assert.strictEqual(layout.root.$('link[rel="stylesheet"]').getAttribute('href'), href, 'Link href should match the provided href');
79
156
  });
80
157
 
81
- it('Should add simple styles', () => {
82
- const styles = [{ body: { bgc: 'black' } }]
83
- const css = new Simple(styles).stylesheet()
84
- layout.style(styles);
85
- assert(layout.root.$('style').innerHTML.includes(css), 'Styles not set correctly');
86
- })
158
+ it('should add a new link element with version', () => {
159
+ const href = 'style.css';
160
+ const version = '1.0';
161
+ layout.link(href, version);
162
+ assert.strictEqual(layout.root.$('link[rel="stylesheet"]').getAttribute('href'), `${href}?v=${version}`, 'Link href should include version query parameter');
163
+ });
87
164
 
88
- it('should add styles to existing style tag', () => {
89
- assert(layout.root.$$('style').length === 0)
90
- const styles1 = 'body { background-color: black; }';
91
- const styles2 = 'body { margin: 0; }';
92
- layout.style(styles1);
93
- assert(layout.root.$$('style').length === 1)
94
- layout.style(styles2);
95
- assert(layout.root.$$('style').length === 1)
96
- const inner = layout.root.$('style').innerHTML
97
- assert(inner.includes(styles1));
98
- assert(inner.includes(styles2));
165
+ it('should not add a link if one with the same href and version already exists', () => {
166
+ const href = 'style.css';
167
+ const version = '1.0';
168
+ layout.link(href, version);
169
+ layout.link(href, version);
170
+ assert.strictEqual(layout.root.$$(`link[rel="stylesheet"][href="${href}?v=${version}"]`).length, 1, 'Should not add duplicate link with the same version');
99
171
  });
100
172
 
101
- });
173
+ it('should handle invalid href or version correctly', () => {
174
+ layout.link('', '1.0');
175
+ layout.link(null, '1.0');
176
+ // layout.link('style.css', '');
177
+ // layout.link('style.css', null);
178
+ assert.strictEqual(layout.root.$('link[rel="stylesheet"]'), null, 'Should not add a link when href or version are invalid');
179
+ });
180
+
181
+ it('should add link correctly', () => {
182
+ const href = 'style.css';
183
+ layout.link(href);
184
+ assert.strictEqual(layout.root.$('link[rel="stylesheet"]').getAttribute('href'), href, 'Link not set correctly');
185
+ });
186
+
187
+ it('should not add a new link element if one already exists with the same href and no version', () => {
188
+ const href = 'style.css';
189
+ layout.link(href); // Добавление ссылки без версии
190
+ layout.link(href); // Повторное добавление той же ссылки без версии
191
+ assert.strictEqual(layout.root.$$(`link[rel="stylesheet"][href="${href}"]`).length, 1, 'Should not add duplicate link without version');
192
+ });
193
+
194
+ it('should not add a link if href is undefined or null', () => {
195
+ layout.link(undefined, '1.0');
196
+ layout.link(null);
197
+ assert.strictEqual(layout.root.$('link[rel="stylesheet"]'), null, 'Should not add a link when href is undefined or null');
198
+ });
199
+
200
+ it('should handle different versions for the same href', () => {
201
+ const href = 'style.css';
202
+ const version1 = '1.0';
203
+ const version2 = '1.1';
204
+ layout.link(href, version1);
205
+ layout.link(href, version2);
206
+ assert.strictEqual(layout.root.$$(`link[rel="stylesheet"]`).length, 2, 'Should add different links for different versions');
207
+ assert.strictEqual(layout.root.$$(`link[rel="stylesheet"][href="${href}?v=${version1}"]`).length, 1, 'First version link should exist');
208
+ assert.strictEqual(layout.root.$$(`link[rel="stylesheet"][href="${href}?v=${version2}"]`).length, 1, 'Second version link should exist');
209
+ });
210
+
211
+ it('should correctly add version when href already has parameters', () => {
212
+ const href = 'style.css?param=value';
213
+ const version = '1.0';
214
+ layout.link(href, version);
215
+ assert.strictEqual(layout.root.$('link[rel="stylesheet"]').getAttribute('href'), `${href}&v=${version}`, 'Href should include version appended with &');
216
+ });
217
+
218
+ it('should not add a link when one with a similar href prefix exists', () => {
219
+ const href = 'style.css';
220
+ layout.link(href);
221
+ layout.link(href + '?param=value', '1.0');
222
+ assert.strictEqual(layout.root.$$(`link[rel="stylesheet"]`).length, 2, 'Should recognize different full hrefs as different links');
223
+ });
224
+
225
+ })
102
226
 
103
227
  describe('Scripts', () => {
104
228
  let layout;
@@ -121,6 +245,37 @@ describe('Scripts', () => {
121
245
  assert.strictEqual(layout.root.$('script').innerHTML, '', 'Script innerHTML should be empty');
122
246
  });
123
247
 
248
+ it('should add script correctly', () => {
249
+ const scriptContent = 'console.log("Hello, world!");';
250
+ layout.script({}, scriptContent);
251
+ assert.strictEqual(layout.root.$('script').innerHTML, scriptContent, 'Script content not set correctly');
252
+ });
253
+
254
+ it('should add version to script src', () => {
255
+ const src = 'script.js';
256
+ const version = '1.0';
257
+ layout.script({ src }, '', true, version);
258
+ assert.strictEqual(layout.root.$('script').getAttribute('src'), `${src}?v=${version}`, 'Script src should include version');
259
+ });
260
+
261
+ it('should not add script if no attributes and no innerHTML', () => {
262
+ layout.script({}, '');
263
+ assert.strictEqual(layout.root.$('script'), null, 'Script should not be added if there are no attributes and no innerHTML');
264
+ });
265
+
266
+ it('should add script after body when head is false', () => {
267
+ const scriptContent = 'console.log("Script in body");';
268
+ layout.script({ src: 'scriptbody.js' }, scriptContent, false);
269
+ assert.strictEqual(layout.body.next.$('script').innerHTML, scriptContent, 'Script should be added to body');
270
+ });
271
+
272
+ it('should append version parameter correctly when src already has parameters', () => {
273
+ const srcWithParams = 'script.js?existing=param';
274
+ const version = '1.0';
275
+ layout.script({ src: srcWithParams }, '', true, version);
276
+ assert.strictEqual(layout.root.$('script').getAttribute('src'), `${srcWithParams}&v=${version}`, 'Version parameter should be appended with &');
277
+ });
278
+
124
279
  })
125
280
 
126
281
  describe('Styles', () => {
@@ -138,6 +293,32 @@ describe('Styles', () => {
138
293
  console.log(layout.root.$('style').innerHTML)
139
294
  assert.strictEqual(layout.root.$('style').innerHTML, 'body{color:blue}div{font-size:12px}', 'Styles should be minified');
140
295
  });
296
+
297
+ it('should add style correctly', () => {
298
+ const styles = 'body { background-color: black; }';
299
+ layout.style(styles);
300
+ assert(layout.root.$('style').innerHTML.includes(styles), 'Styles not set correctly');
301
+ });
302
+
303
+ it('Should add simple styles', () => {
304
+ const styles = [{ body: { bgc: 'black' } }]
305
+ const css = new Simple(styles).stylesheet()
306
+ layout.style(styles);
307
+ assert(layout.root.$('style').innerHTML.includes(css), 'Styles not set correctly');
308
+ })
309
+
310
+ it('should add styles to existing style tag', () => {
311
+ assert(layout.root.$$('style').length === 0)
312
+ const styles1 = 'body { background-color: black; }';
313
+ const styles2 = 'body { margin: 0; }';
314
+ layout.style(styles1);
315
+ assert(layout.root.$$('style').length === 1)
316
+ layout.style(styles2);
317
+ assert(layout.root.$$('style').length === 1)
318
+ const inner = layout.root.$('style').innerHTML
319
+ assert(inner.includes(styles1));
320
+ assert(inner.includes(styles2));
321
+ });
141
322
  })
142
323
 
143
324
  describe('Url', () => {
@@ -149,39 +330,101 @@ describe('Url', () => {
149
330
  assert.strictEqual(layout.root.$('link[rel="canonical"]'), null, 'Canonical URL should not be added for invalid URLs');
150
331
  });
151
332
 
333
+
334
+ it('should add url correctly', () => {
335
+ const url = 'http://localhost';
336
+ layout.url(url);
337
+ assert(layout.root.$('link[rel="canonical"]').getAttribute('href') === url, 'Canonical URL not set correctly');
338
+ });
339
+
340
+ it('should add og:url meta correctly', () => {
341
+ const url = 'http://example.com';
342
+ const host = 'http://example.com';
343
+ layout.url(url, host);
344
+ assert.strictEqual(layout.root.$('meta[property="og:url"]').getAttribute('content'), url, 'og:url meta not set correctly');
345
+ });
346
+
347
+ it('should add canonical link if not already present', () => {
348
+ const url = 'http://example.com';
349
+ const host = 'http://example.com';
350
+ layout.url(url, host);
351
+ assert.strictEqual(layout.root.$('link[rel="canonical"]').getAttribute('href'), url, 'Canonical link should be added if not present');
352
+ });
353
+
354
+ it('should update existing canonical link', () => {
355
+ const initialUrl = 'http://example.com/initial';
356
+ const newUrl = 'http://example.com/new';
357
+ const host = 'http://example.com';
358
+ layout.url(initialUrl, host);
359
+ layout.url(newUrl, host);
360
+ assert.strictEqual(layout.root.$('link[rel="canonical"]').getAttribute('href'), newUrl, 'Canonical link should be updated with new URL');
361
+ });
362
+
363
+ it('should handle invalid URL with valid host', () => {
364
+ layout.url('http://', 'http://example.com');
365
+ assert.strictEqual(layout.root.$('meta[property="og:url"]'), null, 'Meta og:url should not be added for invalid URL');
366
+ assert.strictEqual(layout.root.$('link[rel="canonical"]'), null, 'Canonical link should not be added for invalid URL');
367
+ });
368
+
369
+
152
370
  })
153
371
 
154
- describe('Link', () => {
372
+ describe('layout.viewport',() => {
155
373
  let layout;
374
+
156
375
  beforeEach(() => layout = new Layout());
157
376
 
158
- it('should add a new link element without version', () => {
159
- const href = 'style.css';
160
- layout.link(href);
161
- assert.strictEqual(layout.root.$('link[rel="stylesheet"]').getAttribute('href'), href, 'Link href should match the provided href');
377
+ it('should update existing viewport meta correctly', () => {
378
+ // Добавляем изначальный viewport
379
+ const initialContent = 'width=device-width, initial-scale=1.0';
380
+ layout.viewport(initialContent);
381
+
382
+ // Обновляем viewport
383
+ const updatedContent = 'width=device-width, initial-scale=2.0';
384
+ layout.viewport(updatedContent);
385
+
386
+ // Проверяем, что содержимое meta обновлено
387
+ assert.strictEqual(layout.root.$('meta[name="viewport"]').getAttribute('content'), updatedContent, 'Existing viewport meta content should be updated');
162
388
  });
163
-
164
- it('should add a new link element with version', () => {
165
- const href = 'style.css';
166
- const version = '1.0';
167
- layout.link(href, version);
168
- assert.strictEqual(layout.root.$('link[rel="stylesheet"]').getAttribute('href'), `${href}?v=${version}`, 'Link href should include version query parameter');
389
+
390
+ it('should not add a second viewport meta if one already exists', () => {
391
+ // Добавляем изначальный viewport
392
+ const initialContent = 'width=device-width, initial-scale=1.0';
393
+ layout.viewport(initialContent);
394
+
395
+ // Пытаемся добавить ещё один
396
+ const secondContent = 'width=device-width, initial-scale=2.0';
397
+ layout.viewport(secondContent);
398
+
399
+ // Проверяем, что в документе только один элемент meta viewport
400
+ assert.strictEqual(layout.root.$$(`meta[name="viewport"]`).length, 1, 'Only one viewport meta should exist');
401
+ });
402
+
403
+ it('should add viewport correctly', () => {
404
+ const viewportContent = 'width=device-width, initial-scale=1.0';
405
+ layout.viewport(viewportContent);
406
+ assert.strictEqual(layout.root.$('meta[name="viewport"]').getAttribute('content'), viewportContent, 'Viewport not set correctly');
169
407
  });
408
+ })
170
409
 
171
- it('should not add a link if one with the same href and version already exists', () => {
172
- const href = 'style.css';
173
- const version = '1.0';
174
- layout.link(href, version);
175
- layout.link(href, version);
176
- assert.strictEqual(layout.root.$$(`link[rel="stylesheet"][href="${href}?v=${version}"]`).length, 1, 'Should not add duplicate link with the same version');
410
+ describe('description and title', () => {
411
+ let layout;
412
+
413
+ beforeEach(() => layout = new Layout());
414
+
415
+ it('should add description correctly', () => {
416
+ const description = 'Test Description';
417
+ layout.description(description);
418
+ assert.strictEqual(layout.root.$('meta[name="description"]').getAttribute('content'), description, 'Description not set correctly');
419
+ assert.strictEqual(layout.root.$('meta[property="og:description"]').getAttribute('content'), description, 'Description not set correctly');
420
+ assert.strictEqual(layout.root.$('meta[property="twitter:description"]').getAttribute('content'), description, 'Description not set correctly');
177
421
  });
178
422
 
179
- it('should handle invalid href or version correctly', () => {
180
- layout.link('', '1.0');
181
- layout.link(null, '1.0');
182
- // layout.link('style.css', '');
183
- // layout.link('style.css', null);
184
- assert.strictEqual(layout.root.$('link[rel="stylesheet"]'), null, 'Should not add a link when href or version are invalid');
423
+ it('should add title correctly', () => {
424
+ const title = 'Test Title';
425
+ layout.title(title);
426
+ assert(layout.root.$('title').innerHTML === title, 'Title not set correctly');
427
+ assert(layout.root.$('[property="og:title"]').getAttribute('content') === title, 'Title not set correctly');
185
428
  });
186
429
 
187
- })
430
+ });
@@ -0,0 +1,160 @@
1
+ const assert = require('assert');
2
+ const { describe, it, beforeEach } = require('node:test')
3
+ const Layout = require('../lib/layout');
4
+ const { buildFromCache } = require('als-document')
5
+
6
+ describe('Layout Integrative tests', () => {
7
+ let layout;
8
+
9
+ beforeEach(() => layout = new Layout());
10
+
11
+ it('should integrate multiple elements correctly', () => {
12
+ layout.title('Test Title');
13
+ layout.description('Test Description');
14
+ layout.keywords(['keyword1', 'keyword2']);
15
+
16
+ assert(layout.root.$('title').innerHTML === 'Test Title', 'Title not integrated correctly');
17
+ assert(layout.root.$('meta[name="description"]').getAttribute('content') === 'Test Description', 'Description not integrated correctly');
18
+ assert(layout.root.$('meta[name="keywords"]').getAttribute('content') === 'keyword1,keyword2', 'Keywords not integrated correctly');
19
+ });
20
+
21
+ it('should update elements correctly when added multiple times', () => {
22
+ layout.title('First Title');
23
+ assert(layout.root.$('title').innerHTML === 'First Title', 'Title did not update correctly when added multiple times');
24
+ layout.title('Second Title');
25
+ assert(layout.root.$('title').innerHTML === 'Second Title', 'Title did not update correctly when added multiple times');
26
+ });
27
+
28
+ it('should remove elements correctly', () => {
29
+ layout.title('Test Title');
30
+ layout.root.$('title').remove();
31
+ assert(layout.root.$('title') === null, 'Title element was not removed correctly');
32
+ });
33
+
34
+ });
35
+
36
+ describe('HTML Structure Initialization', () => {
37
+ let layout;
38
+
39
+ beforeEach(() => {
40
+ layout = new Layout();
41
+ });
42
+
43
+ it('should initialize html element correctly', () => {
44
+ assert.strictEqual(layout.html.tagName, 'html', 'HTML element should be initialized');
45
+ });
46
+
47
+ it('should not recreate html element if it already exists', () => {
48
+ const existingHtml = layout.html; // вызовем один раз
49
+ assert.strictEqual(layout.html, existingHtml, 'HTML element should not be recreated');
50
+ });
51
+
52
+ it('should initialize body element correctly', () => {
53
+ assert.strictEqual(layout.body.tagName, 'body', 'Body element should be initialized');
54
+ });
55
+
56
+ it('should not recreate body element if it already exists', () => {
57
+ const existingBody = layout.body; // вызовем один раз
58
+ assert.strictEqual(layout.body, existingBody, 'Body element should not be recreated');
59
+ });
60
+
61
+ it('should initialize head element correctly', () => {
62
+ assert.strictEqual(layout.head.tagName, 'head', 'Head element should be initialized');
63
+ });
64
+
65
+ it('should not recreate head element if it already exists', () => {
66
+ const existingHead = layout.head; // вызовем один раз
67
+ assert.strictEqual(layout.head, existingHead, 'Head element should not be recreated');
68
+ });
69
+ });
70
+
71
+ describe('Component Updating', () => {
72
+ let layout;
73
+
74
+ beforeEach(() => {
75
+ layout = new Layout();
76
+ });
77
+
78
+ it('should correctly update components', () => {
79
+ layout.components.test2 = (element, $App) => {
80
+ assert(element.componentIndex === 0)
81
+ element.innerHTML = 'test2 success'
82
+ }
83
+ layout.components.test1 = (element, $App) => {
84
+ assert(element.componentIndex === 0)
85
+ element.insert(2, 'test1 success')
86
+ }
87
+ layout.body.innerHTML = /*html*/`<div component="test1">
88
+ <div component="test2">failed</div>
89
+ </div>`
90
+
91
+ const done = []
92
+ layout.update(layout.root, done)
93
+ assert(done.length === 2)
94
+ assert(layout.rawHtml.includes('test1 success'))
95
+ assert(layout.rawHtml.includes('test2 success'))
96
+ })
97
+
98
+ it('should correctly render components', () => {
99
+ layout.components.test2 = (element, $App) => {
100
+ assert(element.componentIndex === 0)
101
+ element.innerHTML = 'test2 success'
102
+ }
103
+ layout.components.test1 = (element, $App) => {
104
+ assert(element.componentIndex === 0)
105
+ element.insert(2, 'test1 success')
106
+ }
107
+ layout.data.test = 'hello'
108
+ layout.body.innerHTML = /*html*/`<div component="test1">
109
+ <div component="test2">failed</div>
110
+ </div>`
111
+
112
+ const rawHtml = layout.render()
113
+ assert(rawHtml.includes('test1 success'))
114
+ assert(rawHtml.includes('test2 success'))
115
+
116
+ const script = rawHtml.match(/<[^>]*?script.*?>[^<]*<\/[^>]*?script.*?>/g)[0]
117
+ .replace('<script>window.$App = ', '')
118
+ .replace('</script>', '')
119
+ const fn = new Function(`return ${script}`)
120
+ const { browser, data, components, actions, utils, updata, $, $$ } = fn()
121
+ assert(browser === true)
122
+ assert.deepStrictEqual(Object.keys(components), ['test1', 'test2'])
123
+ assert(components.test1.toString() === layout.components.test1.toString())
124
+ assert(data.test === 'hello')
125
+ })
126
+
127
+ });
128
+
129
+ describe('Cache and Clone Testing', () => {
130
+ let layout;
131
+ beforeEach(() => {
132
+ layout = new Layout();
133
+ });
134
+
135
+ it('should retrieve cached version of the layout', () => {
136
+ const cachedVersion = layout.cached;
137
+ assert.doesNotThrow(() => JSON.stringify(cachedVersion)) // should be object without recursions
138
+ assert(buildFromCache(cachedVersion).innerHTML === layout.rawHtml)
139
+ });
140
+
141
+ it('should clone the layout correctly', () => {
142
+ const clone = layout.clone;
143
+ assert(clone instanceof Layout, 'Clone should be an instance of Layout');
144
+ assert.notStrictEqual(clone, layout, 'Clone should not be the same instance as the original');
145
+ });
146
+ });
147
+
148
+ describe('Version method tests', () => {
149
+ let layout;
150
+
151
+ beforeEach(() => {
152
+ layout = new Layout();
153
+ });
154
+
155
+ it('should set the version correctly', () => {
156
+ const version = '1.0.0';
157
+ layout.version(version);
158
+ assert.strictEqual(layout.v, version, 'Version should be set correctly');
159
+ });
160
+ });
@@ -1,33 +0,0 @@
1
- const assert = require('assert');
2
- const { describe, it, beforeEach } = require('node:test')
3
- const Layout = require('../lib/layout');
4
-
5
- describe('Layout Integrative tests', () => {
6
- let layout;
7
-
8
- beforeEach(() => layout = new Layout());
9
-
10
- it('should integrate multiple elements correctly', () => {
11
- layout.title('Test Title');
12
- layout.description('Test Description');
13
- layout.keywords(['keyword1', 'keyword2']);
14
-
15
- assert(layout.root.$('title').innerHTML === 'Test Title', 'Title not integrated correctly');
16
- assert(layout.root.$('meta[name="description"]').getAttribute('content') === 'Test Description', 'Description not integrated correctly');
17
- assert(layout.root.$('meta[name="keywords"]').getAttribute('content') === 'keyword1,keyword2', 'Keywords not integrated correctly');
18
- });
19
-
20
- it('should update elements correctly when added multiple times', () => {
21
- layout.title('First Title');
22
- assert(layout.root.$('title').innerHTML === 'First Title', 'Title did not update correctly when added multiple times');
23
- layout.title('Second Title');
24
- assert(layout.root.$('title').innerHTML === 'Second Title', 'Title did not update correctly when added multiple times');
25
- });
26
-
27
- it('should remove elements correctly', () => {
28
- layout.title('Test Title');
29
- layout.root.$('title').remove();
30
- assert(layout.root.$('title') === null, 'Title element was not removed correctly');
31
- });
32
-
33
- });