Creating a Web Component

A web component is an ECMAScript (ES) module. It contains:

  • A class extending HTMLElement. The class can use the shadowRoot to define local CSS styles. These styles are only applied to HTML elements inside that shadowRoot – they will not affect any elements in documents where the web component is displayed.

  • A statement to register the class as a custom element. The custom element name must contain a -.

Here is a skeleton web component that you can use as a basis for your own web components:

/**
 * Creating the web component
 */
class MyComponent extends HTMLElement {
  constructor() {
    super();

    this.attachShadow({ mode: 'open' });
    this.shadowRoot.innerHTML = `
      <style>
        :host { width: 100%; display: block; } /* Styles the web component tag */
      </style>

      <!-- Add your web component HTML here -->
    `;
  }

  connectedCallback() {
    console.log('The CUE interface of the web component:', this.cueInterface);
    // The web component is now attached.
    // Add your logic here.
  }

  disconnectedCallback() {
    // The web component is now detached.
    // Add your clean-up logic here.
  }
}
customElements.define('my-component', MyComponent);

/**
 * Creating the icon (if required)
 */
class MyComponentIcon extends HTMLElement {
  constructor() {
    super();

    this.attachShadow({ mode: 'open' });
    this.shadowRoot.innerHTML = `<!-- Add your web component icon HTML here -->`;
  }

  connectedCallback() {
    console.log('The CUE interface of the icon:', this.cueInterface);
    // The icon is now attached.
    // Add your logic here.
  }

  disconnectedCallback() {
    // The web component is now detached.
    // Add your clean-up logic here.
  }
}

customElements.define('my-component-icon', MyComponentIcon);

Field editor web components have no use for an icon, so in this case the icon class can be omitted.

Drag and drop from web components

You can drag objects from all web components except rich text field extensions to drop zones in CUE. Anywhere in the CUE interface that you can drop an uploaded file, you can also drop an object that has been dragged from a web component, as long the object is correctly constructed. A correctly constructed draggable object is a JSON object with a single property, files. This property is an array of objects, each object being composed of three properties:

name

The file name of this object

mimeType

The mime type of this object

dataURL OR url

For external objects, the third property is called dataURL, and holds the content of the object, encoded as a data URL. The dropped object may, however, in some cases be an existing CUE content item, in which case the third property is called url and holds the URL of the content item.

The entire JSON object must be supplied as the drag event's dragData property and be assigned the mime type application/x-web-component-data.