DOM and i18n helpers¶
The browser is an operating system, and its DOM is where a GUI gclass draws. These helpers build the elements and keep the untrusted values safe.
Source code: src/helpers.js
Build an element¶
createElement2()¶
Builds an HTML element from a description that is a plain array. It is the function that a GUI gclass uses to draw.
createElement2(description, translate_fn)Parameters
| Key | Type | Description |
|---|---|---|
description | array | The element, as [tag, attrs, content, events]. |
translate_fn | function | The translation function. The attribute i18n uses it. |
Returns
The element that the function built.
The four slots
| Slot | Type | Description |
|---|---|---|
tag | string | The name of the element. |
attrs | object | The attributes. style accepts a string or an object. i18n gives the content through translate_fn. |
content | string or array | The text, one child, or a list of children. |
events | object | The listeners, as {event: function}. |
['div', { class: 'window-top', style: 'border-bottom: 1px solid black;' },
[
['span', {}, 'title'],
['button', {}, 'Close', {
click: (e) => {
e.target.closest('.window').remove();
}
}]
]
]The style attribute accepts both forms:
['span', {style: {position: 'absolute'} }, 'title']createOneHtml(htmlString)¶
Builds one element from a string of HTML.
parseSVG(string)¶
Builds an SVG element from a string of SVG code.
getPositionRelativeToBody(element)¶
Gives the position of an element against the body of the document. A popover or a menu that must stay next to its button uses it.
Untrusted values¶
escapeHtml(str)¶
Escapes a value for an HTML context. Use it every time that a string from a
user or from a server goes into a template that becomes innerHTML.
safeSrc(url)¶
Validates a URL for the src attribute of an image or a media element. It
refuses the javascript: and data: schemes, which carry a cross-site script.
It gives an empty string back for every scheme that it refuses.
Language¶
refresh_language()¶
Translates a DOM tree again, after the application changes its language.
refresh_language(element, t)Parameters
| Key | Type | Description |
|---|---|---|
element | Element | The root of the tree. With an empty value the function takes the whole document. |
t | function | The translation function, such as the t of i18next. |
What the function translates
It reads four attributes, and each one carries the key of its own text.
| Attribute | What it translates |
|---|---|
data-i18n | The first text node of the element. |
data-i18n-title | The title attribute, which is the tooltip. |
data-i18n-aria-label | The aria-label attribute, which a screen reader reads. |
data-i18n-placeholder | The placeholder attribute of an input or a text area. |