als-layout 2.0.0 → 2.2.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,8 @@
1
+ const { readFileSync, writeFileSync, readdirSync } = require('fs')
2
+ const { join } = require('path')
3
+
4
+ const docsDir = join(__dirname, 'docs')
5
+ const files = readdirSync(docsDir)
6
+ const content = files.map(file => readFileSync(join(docsDir, file), 'utf-8')).join('\n');
7
+ writeFileSync(join(__dirname, 'readme.md'), content, 'utf-8')
8
+
package/docs/#.md ADDED
@@ -0,0 +1,27 @@
1
+ # als-layout Documentation
2
+
3
+ ## Library Description
4
+
5
+ ### What is it?
6
+ `als-layout` is a JavaScript library designed to simplify and enhance the process of constructing and managing web page layouts. It provides a comprehensive API for modifying HTML documents dynamically, allowing developers to add, update, and manipulate various elements such as meta tags, styles, scripts, and more.
7
+
8
+ ### Why is it needed?
9
+ Managing HTML document structures and their contents can often become repetitive and error-prone when done manually. `als-modular` offers a structured and reusable approach, reducing development time and improving code maintainability.
10
+
11
+ ### What can you do with it and where can it be used?
12
+ The `als-layout` library is versatile, suitable for:
13
+ - Building dynamic web pages that require frequent updates to their metadata, styles, or scripts.
14
+ - Creating templating systems where multiple page layouts share similar structures but differ in content or styling.
15
+ - Developing web applications that need to dynamically adjust their UI based on user interactions or data changes.
16
+ This library is particularly useful in environments where rapid development and modular design are prioritized.
17
+
18
+ ## Installation and Adding
19
+ To use the `als-layout` library in your project, you can install it via npm and then include it in your JavaScript files:
20
+
21
+ ```bash
22
+ npm i als-layout
23
+ ```
24
+
25
+ ```js
26
+ const Layout = require('als-layout')
27
+ ```
@@ -0,0 +1,16 @@
1
+ ## Change Log
2
+ * V2.2.0
3
+ * fixed empty update function if no components for $App
4
+ * if component function return string, it will element.innerHTML = string
5
+ * Now each Layout extends Document (als-document)
6
+ * layout.$ and layout.$$
7
+ * Also $App.$ and $App.$$ on backend too
8
+ * no langs validation any more
9
+ * lang method instead
10
+ * no layout.cached
11
+ * charset meta tag allready exists by default
12
+ * V2.1.0
13
+ * updated als-document version
14
+ * [part] attribute for static components
15
+ * onload() method
16
+ * bugs fixed
@@ -0,0 +1,49 @@
1
+ ## Basic Usage
2
+
3
+ ### Initialization
4
+ To start using `als-layout`, you first need to create a new instance of `Layout`. This instance will serve as the foundation for building and modifying your web page.
5
+
6
+ ```js
7
+ const Layout = require('als-layout');
8
+ const layout = new Layout();
9
+ ```
10
+
11
+ ### Adding Different Elements
12
+ Once you have your `Layout` instance, you can easily add or modify various elements of your web page. Here are some examples of how you can use the library to customize your layout:
13
+
14
+ ```js
15
+ const layout = new Layout()
16
+ .charset() // default UTF-8
17
+ .viewport() // default width=device-width, initial-scale=1.0
18
+ .title('Test title') // adding/updating title and meta[og:title]
19
+ .favicon('/favicon.png') // adding/updating link[rel=icon][type=image/x-icon] with new href
20
+ .keywords(['some', 'keyword']) // adding/updating meta[name=keywords]. not adding existing keywords
21
+ .image('/main-image.png', '1.5') // adding/updating meta - og:image, twitter:image, twitter:card
22
+ .description('Cool site') // adding/updating meta og:description, twitter:description, and description tag
23
+ .version('1.0.0') // adds version parameter to link, script.src, and image
24
+ .url('/some', 'http://site.com') // adding/updating meta[og:url] and link[rel="canonical"]
25
+ .style([{body:{m:0, bgc:'whitesmoke'}}]) // adding as simple-css styles to existing/new style tag
26
+ .style('body {margin:0; background-color:whitesmoke;}', true) // adding css styles to existing/new style tag. Second parameter is minified (default=false).
27
+ .link('/styles.css', '2.0') // adding link[rel=stylesheet] if such href not exists
28
+ .script({src:'/app.js'}, '', true, '3.0') // set script with src to head if such src not exists
29
+ .script({}, 'console.log("hello world")', false) // set script with script code to footer
30
+
31
+ // Accessors for document parts
32
+ layout.body // getter for body element (if not exists, created)
33
+ layout.head // getter for head element (if not exists, created)
34
+ layout.html // getter for html Element (if not exists, created)
35
+
36
+ // Outputs
37
+ layout.rawHtml // raw HTML of the document
38
+ layout.clone // creates a new layout object clone for current object
39
+ ```
40
+
41
+ ### onload
42
+
43
+ By adding onload attribute, you can run scripts for each element after dom content has loaded.
44
+
45
+ Example how it works:
46
+ ```js
47
+ const layout = new Layout().charset().viewport().title('On load').onload()
48
+ layout.body.innerHTML = /*html*/`<div onload="this.innerHTML = 'new content'">original content</div>`
49
+ ```
@@ -0,0 +1,19 @@
1
+ ## Cloning Functionality
2
+
3
+ ### What is Cloning and Why is it Necessary?
4
+ Cloning in the `als-layout` library refers to creating a complete, independent copy of the existing `Layout` instance. This functionality is crucial when you need to generate multiple pages or versions of a page from a single base layout without affecting the original setup.
5
+
6
+ ### How to Use Cloning
7
+ To clone a `Layout` instance, simply use the `clone` method. This method creates a new `Layout` instance with the same properties and settings as the original, allowing for independent modifications without interference.
8
+
9
+ ```js
10
+ const newLayout = layout.clone;
11
+ ```
12
+
13
+ ### Benefits of Cloning
14
+ - **Efficiency:** Cloning is highly efficient, especially for creating pages with similar structures but different content or styles. It avoids the overhead of reinitializing and reconfiguring a new `Layout` instance from scratch.
15
+ - **Speed:** Cloning is fast, typically taking less than 20ms even for large pages. This makes it ideal for high-performance web applications that need to dynamically generate content.
16
+ - **Isolation:** Changes made to a cloned `Layout` do not affect the original, ensuring that each instance can be modified independently based on specific requirements.
17
+
18
+ Cloning is particularly useful in scenarios where templates or base layouts are used repeatedly with slight variations, providing a robust and scalable solution for web page generation.
19
+
@@ -0,0 +1,43 @@
1
+ ## Advanced Usage
2
+
3
+ The `als-layout` library allows for sophisticated manipulation of web page layouts, providing robust tools for creating dynamic and complex web pages. Below is an advanced example demonstrating various capabilities of the library:
4
+
5
+ ```js
6
+ const Layout = require('als-layout')
7
+
8
+ // Starting with a basic HTML template and specifying the host for URL methods
9
+ const raw = /*html*/`<html></html>`
10
+ const host = 'http://example.com';
11
+ const layout = new Layout(raw, host).lang('fr')
12
+ console.log(layout.rawHtml)
13
+ // <!DOCTYPE html><html lang="fr"><head></p></head><body></body></html>
14
+
15
+ // Cloning the initial layout to create a specialized page
16
+ const homePage = layout.clone
17
+ homeAutoReload = layout.clone
18
+ homePage.title('Home page')
19
+ homePage.body.innerHTML = /*html*/`<h1>Home page</h1>`
20
+ console.log(homePage.rawHtml)
21
+ // <!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>
22
+
23
+ // Adding script that reloads the page every minute
24
+ homeAutoReload.script({}, 'setTimeout(function() { window.location.reload(); }, 60000);', false)
25
+ console.log(homeAutoReload.rawHtml)
26
+ // <!DOCTYPE html><html lang="fr"><head><title>Automatic Reload Page</title><meta property="og:title" content="Automatic Reload Page"></head><body><script>setTimeout(function() { window.location.reload(); }, 60000);</script></body></html>
27
+
28
+ // Demonstrating dynamic stylesheet linkage with versioning
29
+ const styleVersion = '1.1';
30
+ homePage.link('/css/main.css', styleVersion)
31
+ console.log(homePage.rawHtml)
32
+ // Includes link to the stylesheet with version parameter to ensure fresh cache
33
+ ```
34
+
35
+ In this example:
36
+ - We start with a basic HTML template and use the `lang` method to set the language.
37
+ - We use the `clone` method to create two versions of the base layout: one for the home page and another that automatically reloads every minute.
38
+ - We manipulate the `body` of the `homePage` to include custom HTML.
39
+ - We add a script to `homeAutoReload` that sets up an automatic page reload, showcasing how to insert JavaScript dynamically.
40
+ - We dynamically add a versioned link to a stylesheet in the `homePage`, demonstrating control over caching and resource management.
41
+
42
+ This advanced example illustrates how `als-layout` can be used to handle complex scenarios and requirements in web development, enhancing the flexibility and power at your disposal.
43
+
@@ -0,0 +1,71 @@
1
+ ## Rendering
2
+
3
+ Each instance of `Layout` comes equipped with a `render` method that compiles the HTML structure and embeds a JavaScript object to manage the page dynamically. This object, known as `window.$App`, allows for real-time interaction and updates within the page.
4
+
5
+ ### Structure
6
+ The layout object houses several key properties that facilitate dynamic content management:
7
+
8
+ - `layout.data`: Stores the data that can be used across the page, such as state variables or configuration settings.
9
+ - `layout.components`: Holds functions that define the behavior and rendering logic for components identified by specific attributes in the HTML.
10
+ - `layout.utils`: Contains utility functions that can be used throughout the page for common tasks.
11
+ - `layout.actions`: Methods that can be triggered by user interaction, often modifying `layout.data` and updating the page accordingly.
12
+
13
+ ### The Render Method
14
+ The `render` method processes all elements with a `component` attribute, dynamically generating their content and behavior based on the defined components. After rendering, the page includes the `window.$App` JavaScript object, which provides methods and properties to interact with the page elements and data:
15
+
16
+ ```js
17
+ window.$App = {
18
+ data, // Access to the layout data object
19
+ components, // Access to components functions
20
+ utils, // Access to utility functions
21
+ actions, // Access to action functions
22
+ $(selector, parent = document), // Equivalent to querySelector
23
+ $$(selector, parent = document), // Equivalent to querySelectorAll
24
+ update(element) { // Updates the element if it has a component attribute
25
+ // Update logic here
26
+ }
27
+ }
28
+ ```
29
+
30
+ ### Counter Example
31
+ To demonstrate dynamic interaction, consider a counter that can be increased or decreased through user input:
32
+
33
+ ```js
34
+ const fs = require('fs')
35
+ const Layout = require('als-layout')
36
+
37
+ // Create and configure the layout
38
+ const layout = new Layout().title('Counter')
39
+ layout.data.counter = 0 // Initialize counter data
40
+
41
+ // Define a component for displaying the counter
42
+ layout.components.counter = function(element, $App) {
43
+ element.innerHTML = `${$App.data.counter}`
44
+ }
45
+
46
+ // Define actions for increasing and decreasing the counter
47
+ layout.actions = {
48
+ increase: () => { $App.data.counter++; $App.update($App.$('[component=counter]')); },
49
+ decrease: () => { $We render the html page to measure and write to a document.app.data.counter--; $Page updates are shown in real-time on the rendered HTML.$App.update($App.$('[component=counter]')); }
50
+ }
51
+
52
+ // Add buttons and the counter display to the body
53
+ layout.body.innerHTML = /*html*/`
54
+ <button onclick="$App.actions.increase()">Increase</button>
55
+ <span component="counter"></span>
56
+ <button onclick="$App.actions.decrease()">Decrease</button>
57
+ `
58
+
59
+ // Measure render time and generate HTML
60
+ const time1 = performance.now()
61
+ const rawHtml = layout.render()
62
+ const time2 = performance.now()
63
+ console.log(`${time2 - time1}ms`) // e.g., 1.0649ms
64
+
65
+ // Write the output to a file
66
+ fs.writeFileSync('counter.html', rawHtml, 'utf-8')
67
+ ```
68
+
69
+ ### Advanced Rendering Details
70
+ - **Component Indexing:** Each component is assigned a `componentIndex` during rendering, providing a unique index within its parent component.
71
+ - **Part Attribute:** Using the `part` attribute in a component prevents it from being added to `$App.components`, unless it is nested within another component.
@@ -9,7 +9,7 @@ function addScript(attrs = {}, innerHTML = '', head = true, version, layout) {
9
9
  if(Object.keys(attrs).length || innerHTML) {
10
10
  const script = new Node('script', attrs)
11
11
  if(innerHTML) script.innerHTML = innerHTML
12
- if (head) layout.root.head.insert(2, script)
12
+ if (head) layout.head.insert(2, script)
13
13
  else layout.body.insert(3, script)
14
14
  }
15
15
  return layout
package/lib/layout.js CHANGED
@@ -1,79 +1,44 @@
1
- const { cacheDoc } = require('als-document')
1
+ const { Document } = require('als-document')
2
+ const build$App = require('./render/build-app')
3
+ const onload = require('./onload')
4
+ const update = require('./render/update')
2
5
  const {
3
- addKeywords, addStyle, addDescription, addTitle, addImage,
4
- addUrl, addFavicon, addScript, addLink, charset, viewport
6
+ addKeywords, addStyle, addDescription, addTitle, addImage,
7
+ addUrl, addFavicon, addScript,addLink,charset,viewport
5
8
  } = require('./elements/index')
6
- const build$App = require('./build-app')
7
- const buildRoot = require('./build-root')
8
9
 
9
- class Layout {
10
- constructor(layout, options = {}) {
11
- this.options = options
12
- this.root = buildRoot(layout)
13
- this.body; this.head;
10
+ class Layout extends Document {
11
+ constructor(html,url) {
12
+ super(html,url)
14
13
  this.components = {}
15
14
  this.data = {}
16
15
  this.actions = {}
17
16
  this.utils = {}
17
+ this.root = this.html
18
+ this.update = update
18
19
  }
19
-
20
- get html() {
21
- const lang = this.options.lang || 'en'
22
- if (!this.root.$('html')) this.root.insert(2, `<html></html>`)
23
- const htmlElement = this.root.$('html')
24
- if (lang && htmlElement.getAttribute('lang') !== lang) {
25
- htmlElement.setAttribute('lang', lang)
26
- }
27
- return htmlElement
28
- }
29
- get body() {
30
- if (!this.root.body) this.html.insert(2, `<body></body>`)
31
- return this.root.body
32
- }
33
- get head() {
34
- if (!this.root.head) this.html.insert(1, `<head></head>`)
35
- return this.root.head
36
- }
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
-
61
- get rawHtml() { return this.root.innerHTML }
62
- get cached() { return cacheDoc(this.root) }
63
- get clone() { return new Layout(this.root, this.options) }
64
-
20
+ onload() {this.script({},onload); return this}
21
+ lang(lang) {this.html.setAttribute('lang',lang); return this}
65
22
  version(v) { this.v = v; return this; }
23
+ charset(newCharset = 'UTF-8') { return charset(newCharset, this) }
66
24
  keywords(keywords = []) { return addKeywords(keywords, this) }
67
25
  description(description) { return addDescription(description, this) }
68
26
  title(title) { return addTitle(title, this) }
69
27
  style(styles, minified) { return addStyle(styles, minified, this) }
70
28
  image(image, v = this.v) { return addImage(image, v, this) }
71
- url(url, host = this.options.host) { return addUrl(url, host, this) }
29
+ url(url, host = this.URL) { return addUrl(url, host, this) }
72
30
  favicon(href) { return addFavicon(href, this) }
73
31
  script(attributes, innerHTML, head = true, v = this.v) { return addScript(attributes, innerHTML, head, v, this) }
74
32
  link(href, v = this.v) { return addLink(href, v, this) }
75
- charset(newCharset = 'UTF-8') { return charset(newCharset, this) }
76
33
  viewport(newViewport = 'width=device-width, initial-scale=1.0') { return viewport(newViewport, this) }
34
+ get rawHtml() {return this.innerHTML}
35
+ get clone() {return new Layout(new Document(this),this.URL)}
36
+ render() {
37
+ const done = []
38
+ this.update(this.root, done)
39
+ this.script({}, build$App(done,this),false)
40
+ return this.rawHtml
41
+ }
77
42
  }
78
43
 
79
44
  module.exports = Layout
package/lib/onload.js ADDED
@@ -0,0 +1,9 @@
1
+ module.exports = `document.addEventListener('DOMContentLoaded', function() {
2
+ const elements = document.querySelectorAll('[onload]');
3
+ elements.forEach(element => {
4
+ const onloadCode = element.getAttribute('onload');
5
+ const func = Function('"use strict"; return function() { ' + onloadCode + ' }');
6
+ func().call(element);
7
+ element.removeAttribute('onload');
8
+ });
9
+ });`
@@ -1,9 +1,13 @@
1
1
  const componentHierarchy = require('./component-hierarchy')
2
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()}`
3
+ let strComponents = 'components:{}', updateFn = 'update:()=>{}'
4
+ const components = componentHierarchy(done)
5
+ if(components.length) {
6
+ strComponents = 'components:{'+components.map(componentName => {
7
+ return `"${componentName}":${layout.components[componentName].toString()}`
8
+ }).join(',')+'}'
9
+ updateFn = `update:${layout.update.toString()}`
10
+ }
7
11
  const strData = 'data:'+JSON.stringify(layout.data)
8
12
  const $ = 'function $(selector,parent = document) {return parent.querySelector(selector)}'
9
13
  const $$ = 'function $$(selector,parent = document) {return [...parent.querySelectorAll(selector)]}'
@@ -1,4 +1,5 @@
1
1
  function componentHierarchy(elements) {
2
+
2
3
  const entries = elements
3
4
  .map(el => ([el, el.getAttribute('component'), el.ancestors]))
4
5
  .sort((a, b) => a[2].length - b[2].length)
@@ -6,6 +7,13 @@ function componentHierarchy(elements) {
6
7
  const result = []
7
8
  while(entries.length > 0) {
8
9
  const [element, componentName, ancestors] = entries.shift()
10
+ if(element.getAttribute('part') !== null) {
11
+ element.removeAttribute('component')
12
+ element.removeAttribute('part')
13
+ continue
14
+ }
15
+ const partsInside = element.$$('[component][part]')
16
+ partsInside.forEach(element => { element.removeAttribute('part') });
9
17
  entries.forEach(entry => {
10
18
  if(entry[1] !== componentName) return
11
19
  if(entry[2].includes(element)) {
@@ -0,0 +1,19 @@
1
+ function update(element, done = []) {
2
+ for (const componentName in this.components) {
3
+ const fn = this.components[componentName]
4
+ let components = element.getAttribute('component') === componentName
5
+ ? [element]
6
+ : [...element.querySelectorAll(`[component=${componentName}]`)]
7
+ components = components.filter(el => !done.includes(el))
8
+ components.forEach((element, i) => {
9
+ element.componentIndex = i
10
+ const result = fn(element, this)
11
+ if(typeof result === 'string') element.innerHTML = result
12
+ done.push(element)
13
+ this.update(element, done)
14
+ });
15
+ }
16
+ }
17
+
18
+
19
+ module.exports = update
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "als-layout",
3
- "version": "2.0.0",
3
+ "version": "2.2.0",
4
4
  "description": "Html layout constructor",
5
5
  "main": "index.js",
6
6
  "directories": {
@@ -15,7 +15,7 @@
15
15
  "license": "ISC",
16
16
  "dependencies": {
17
17
  "als-css-parser": "^0.5.0",
18
- "als-document": "^1.1.2",
18
+ "als-document": "^1.3.1",
19
19
  "als-simple-css": "^9.1.0"
20
20
  }
21
21
  }