Skip to content

Scripts, web components and theme files ​

What a kit needs besides markup and CSS: the JavaScript that makes components work, custom elements, files that live in the theme, and the limits of rich text. Everything here is how Frame works today.

Scripts that run once at page load ​

A script written for a plain page often starts when the page loads: DOMContentLoaded, or a call at the end of the file that looks for .tabs, [data-menu], .accordion and prepares them. In Frame that finds only what is on the page at that moment. A component that an editor adds or changes is rendered later, in the canvas, as HTML that is put in the page, so the script never sees it. The same is true of Drupal's AJAX and of blocks that load later.

Wrap the start in a Drupal behavior. Drupal calls attach(context) on page load and again with the new markup as context each time markup is added, and the editor does the same after it renders a component (The canvas). once() keeps an element from being prepared twice:

js
// assets/js/tabs.js, in a library that depends on core/drupal and core/once
((Drupal, once) => {
  Drupal.behaviors.kitTabs = {
    attach(context) {
      once('kit-tabs', '[data-kit-tabs]', context).forEach((element) => initTabs(element));
    },
  };
})(Drupal, once);
yaml
# my_theme.libraries.yml
tabs:
  js:
    assets/js/tabs.js: {}
  dependencies:
    - core/drupal
    - core/once
  • Select inside context (once(id, selector, context)), not in document, or you prepare things twice and slowly.
  • Listeners on elements are lost when the editor replaces the element, and that is fine: the new element goes through attach again. A listener on document or window is added once, outside attach, or with once('x', 'body').
  • A script of the theme that is not a component is built from js/*.js (Build).
  • Attach the library to the component that needs it (libraryOverrides in its *.component.yml) so the canvas loads it with the component, or to the whole theme in the .info.yml.

Web components ​

A custom element works in a component's Twig like any element. Define it in a library script, print it in the template, and the browser upgrades it when the editor puts it in the canvas, as on the page.

twig
{# components/disclosure/disclosure.twig #}
<kit-disclosure{{ attributes }}{% if open %} open{% endif %} data-items="{{ items|json_encode }}" max="{{ max }}">
  <span slot="summary">{{ summary }}</span>
  <div slot="details">{% block details %}{% endblock %}</div>
</kit-disclosure>

Props reach the element as attributes. The template makes HTML, so every value is a string by the time the element reads it. The element converts:

PropIn the templateIn the element
a booleanpresent or absent: {% if open %} open{% endif %}. Never open="{{ open }}": false prints an empty string, and an empty attribute is a present attributethis.hasAttribute('open')
a numbermax="{{ max }}"Number(this.getAttribute('max')), and check for NaN
a list or an objectdata-items="{{ items|json_encode }}". Twig escapes the quotes, the browser decodes themJSON.parse(this.getAttribute('data-items') || '[]')
a stringlabel="{{ label }}"this.getAttribute('label')

Attributes, not properties: nothing in a template can set a property. If the element is easier to use with properties, read the attributes in connectedCallback(). When an editor changes a prop, the editor renders the component again and puts new HTML in the canvas, so the element is made anew; observedAttributes matters only for code of your own that changes the attributes.

Slots. The slot of a component ({% block details %}) is a block of Twig, not a <slot> of the shadow DOM. Put the block inside a light-DOM child of the element, and give that child the slot="..." attribute of the shadow <slot>, as the <div slot="details"> above. In the canvas Frame puts a marker and a drop zone in the block (<div data-frame-editor-slot>, see The canvas); they are in the light DOM inside your slot element, so they are projected like the rest. Without the slot child the content goes to the default slot of the element, and a named slot stays empty.

Shadow DOM.

  • CSS of the page does not reach inside a shadow root. The classes and variables the kit uses there have to come in with the element: custom properties pass through (so the tokens of the theme, var(--frame-space-m), work), a stylesheet does not. Put the styles in the shadow root, or in ::part() rules of the page.
  • What the editor sets in Layout and style is printed as inline styles on the root element of the component, so it works when that root is the custom element itself ({{ attributes }} on it), as in the example. Inline styles are declarations on the host: they apply to it, and inherited properties (colour, font) continue into the shadow root.
  • Content in a slot is light DOM: styled by the page's CSS, so a component dropped into a slot looks as everywhere.

Form-associated elements (static formAssociated = true, attachInternals()) take part in a form as a native control: a Drupal form submits their value, name and required are attributes you print from props. The canvas has no form around a component, so there it shows only the look.

Files of the theme in Twig ​

A component finds its own files from the metadata Drupal passes to every component template. componentMetadata.path is the folder of the component, relative to the Drupal root and with no leading slash:

twig
<img src="{{ file_url(componentMetadata.path ~ '/logo.svg') }}" alt="">

file_url() adds the base path of the site, so this works in a site in a subfolder too. Do not write the path of the theme by hand (/themes/custom/my_theme/...): it breaks when the theme is renamed or moved. For a file that belongs to the theme and not to one component, use the folder of the theme (active_theme_path() is the active theme's), or the library of the theme with url() in CSS (url('../images/x.svg') in a stylesheet is relative to the stylesheet and needs nothing).

The prop variant ​

A prop named variant is special in Drupal's Single Directory Components. When it has a value, Drupal adds data-component-variant="<value>" next to data-component-id to the attributes of the component, so the root element gets it if the template prints {{ attributes }} there:

yaml
# components/notice/notice.component.yml
props:
  type: object
  properties:
    variant:
      type: string
      title: Look
      enum: [info, warning, error]
css
.notice[data-component-variant='warning'] { border-color: orange; }

The editor shows variant as a select like any enum. Style by the attribute, or print a class from the prop yourself ('notice--' ~ variant); do not do both for the same thing. The attribute is there only when the root prints {{ attributes }}, and not when the value is empty.

Rich text and the classes of a text format ​

A rich text prop is filtered by its text format when it is printed (Rendering), exactly as body text is. The formats Drupal ships with, such as Basic HTML, allow a short list of tags and attributes and remove the class and style attributes that are not in it. An editor can use a class in the source only if the format allows it, so a kit that styles rich text with classes (<p class="lead">, <a class="button">) finds them gone.

Choose one:

  • Allow the classes in the format: Configuration > Content authoring > Text formats, Limit allowed HTML tags, for example <p class="lead"> <a href class="button">. In CKEditor 5 the Source editing allowed tags and the style list follow it.
  • Style the elements and not the classes: .rich-text p, .rich-text a, in the component's CSS.
  • Pin another format for the prop with x-builder-format (Components for the editor) and give that format the tags the kit needs. Editors need access to the format.

The format of a prop is the one the editor stored with the text; the pinned one wins.