Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

JS: DOM and i18n helpers

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

KeyTypeDescription
descriptionarrayThe element, as [tag, attrs, content, events].
translate_fnfunctionThe translation function. The attribute i18n uses it.

Returns

The element that the function built.

The four slots

SlotTypeDescription
tagstringThe name of the element.
attrsobjectThe attributes. style accepts a string or an object. i18n gives the content through translate_fn.
contentstring or arrayThe text, one child, or a list of children.
eventsobjectThe 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

KeyTypeDescription
elementElementThe root of the tree. With an empty value the function takes the whole document.
tfunctionThe 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.

AttributeWhat it translates
data-i18nThe first text node of the element.
data-i18n-titleThe title attribute, which is the tooltip.
data-i18n-aria-labelThe aria-label attribute, which a screen reader reads.
data-i18n-placeholderThe placeholder attribute of an input or a text area.