Skip to main content

Custom widget development

info

This content is intended for advanced Studio users.

Widgets are embeddable UI components that run inside Better Studio forms. Better Studio provides a library of pre-built widgets in the Marketplace, covering clinical tools such as body charts, timeline views, and specialist scoring tools. When no Marketplace widget meets your requirement, you can build your own.

Prerequisites: Custom widget development requires JavaScript, HTML, and CSS skills, and a basic understanding of web components. Familiarity with the Studio Script API is recommended for widgets that exchange actions with the form.

When to build a custom widget​

SituationRecommendation
A Marketplace widget already meets your requirementUse the Marketplace widget
A Marketplace widget partially meets your requirementContact the widget author or raise a feature request before building from scratch
No Marketplace widget exists for your clinical or UI needBuild a custom widget
You need to integrate with a proprietary external systemBuild a custom widget
Your organisation has strict UI/UX constraints that Marketplace widgets cannot meetBuild a custom widget

How a widget runs in Studio​

A widget is a standard custom element. Studio does not care how it was written: plain JavaScript, Lit, React, Svelte, Angular, or anything else works, as long as the result is one JavaScript file that registers a custom element and follows the contract on this page.

At runtime, Studio does the following:

  1. Adds your file to the page as a classic script (<script type="text/javascript">). Running the script registers your custom element.
  2. Waits until the element is defined, creates an instance of it, and places it in the form.
  3. Sets properties on the element to pass data in.
  4. Listens for events dispatched by the element to get data out.

The same element is used in three places: on the Form builder canvas, in Form playground, and in the deployed form.

The widget contract​

Studio communicates with the widget only through the properties and events below. All of them are optional: implement the ones your widget needs.

Properties set by Studio​

PropertyTypeDescription
configobjectThe configuration the Studio user set in Form builder, shaped by configuration in your descriptor. {} when nothing is configured. Can be replaced while the form is open.
inputDataanyThe data bound to the widget, shaped by valueModel in your descriptor. Reassigned every time the bound source changes.
inputActionobjectAn action sent to the widget from a script, as { [action]: value }. See Actions.
languagestringThe current form language code. Reassigned when the form language changes.
readonlybooleantrue when the field or the whole form is read-only. Render a non-editable state.
useDefaultDatabooleantrue on the Form builder canvas, false in Form playground and in deployed forms. See Default data.

Studio assigns these as JavaScript properties, not HTML attributes, and replaces the whole value on every change. Your element must react to a property being reassigned at any time, including after the first render.

Property read by Studio​

PropertyTypeDescription
descriptorobjectDescribes the widget's data and configuration. Studio reads it from the element shortly after creating it. See The descriptor.

Events dispatched by the widget​

EventPayloadDescription
outputDataThe new value, in the same shape as inputDataWrites a value back to the form. Studio stores it in the same way as the value of a generic field.
outputAction{ [action]: payload }, as declared in outputActionModelNotifies the form that something happened in the widget, so that form logic can react to it.

Dispatch both as a CustomEvent on the widget element, with the payload in detail:

this.dispatchEvent(new CustomEvent('outputData', { detail: newValue }));
good to know

Frameworks that compile components to custom elements usually do this for you. For example, an Angular @Output() named outputData becomes an outputData event on the element.

Minimal example​

A complete widget with no framework and no build step:

class RatingWidget extends HTMLElement {
descriptor = {
valueModel: { type: 'number' },
configuration: {
max: { type: 'number', defaultValue: 5, metadata: { title: 'Maximum rating' } },
},
};

#config = {};
#value = null;
#readonly = false;
#useDefaultData = true;

set config(value) {
this.#config = value ?? {};
this.#render();
}
set inputData(value) {
this.#value = value;
this.#render();
}
set readonly(value) {
this.#readonly = !!value;
this.#render();
}
set useDefaultData(value) {
this.#useDefaultData = value !== false;
this.#render();
}

connectedCallback() {
this.attachShadow({ mode: 'open' });
this.#render();
}

#render() {
if (!this.shadowRoot) {
return;
}
const max = this.#config.max ?? 5;
const value = this.#useDefaultData ? 3 : this.#value ?? 0;
this.shadowRoot.replaceChildren(
...Array.from({ length: max }, (_, index) => {
const button = document.createElement('button');
button.textContent = index < value ? '★' : '☆';
button.disabled = this.#readonly;
button.addEventListener('click', () =>
this.dispatchEvent(new CustomEvent('outputData', { detail: index + 1 })),
);
return button;
}),
);
}
}

customElements.define('acme-rating-widget', RatingWidget);

The descriptor​

The descriptor tells Studio what your widget accepts and emits. Studio uses it to render the configuration panel and the data mapping panel in Form builder. Expose it as a descriptor property on the element.

Root propertyDescribes
valueModelThe shape of inputData, and therefore of outputData
configurationThe shape of config. Each entry becomes a control in the configuration panel
outputActionModelThe actions the widget can emit through outputAction, keyed by action name
$conditionsRules that show, hide, or clear configuration options based on the value of another option

Configuration is not mandatory. If your widget has no configurable settings, leave configuration empty.

Option properties​

Every entry in the descriptor is an option with the following properties:

PropertyDescription
typeOne of boolean, string, number, enum, object, or list
valuesThe allowed values. For enum only
objectModelThe nested options. For object only
listModelThe option describing each list item. For list only
defaultValueThe value used until the Studio user sets one
inputFor valueModel entries: whether the Studio user can enter a fixed value (static), bind the entry to data (dynamic), or both
metadatatitle and description shown in Studio, plus optional translations under localization, keyed by language code

Example: A pie chart descriptor​

descriptor = {
valueModel: {
type: 'list',
listModel: {
type: 'object',
objectModel: {
value: { type: 'string' },
label: { type: 'string' },
},
},
},
configuration: {
chartType: {
type: 'enum',
values: ['pie', 'doughnut'],
defaultValue: 'pie',
metadata: {
title: 'Chart type',
description: 'Defines whether the chart is displayed as a pie or doughnut.',
localization: {
de: { title: 'Diagrammtyp' },
},
},
},
hideLegend: { type: 'boolean' },
legendPosition: { type: 'enum', values: ['top', 'bottom'], defaultValue: 'bottom' },
},
outputActionModel: {
sliceSelected: {
type: 'object',
objectModel: {
label: { type: 'string' },
},
},
},
$conditions: [
{
field: 'hideLegend',
targets: ['legendPosition'],
actions: [{ eq: true, state: ['hide', 'clear'] }],
},
],
};

Studio renders chartType as a dropdown with the two enum options and hideLegend as a toggle. When hideLegend is switched on, legendPosition is hidden and its value cleared.

Working with form data​

Reading data​

Bind inputData to a form field, variable, or data connector in the Form builder data mapping panel. Studio assigns the bound value to inputData each time it changes.

If the widget is placed inside a parent component such as a column list or stacked list, it inherits the data binding of that parent. You do not configure the binding separately for each row.

Writing data back​

For input widgets, dispatch the updated value as an outputData event. The value must match valueModel. Studio stores it in the composition in the same location as a generic field bound to the same data path.

Default data​

A widget placed on the Form builder canvas has no real data yet. Studio sets useDefaultData to true there, and to false in Form playground and in deployed forms.

When useDefaultData is not false, render built-in placeholder data so that the widget looks meaningful on the canvas.

Actions​

Actions let the form and the widget notify each other without going through the stored value.

  • Form to widget: A script calls api.sendActionToWidget(tagOrPath, action, value). Studio assigns { [action]: value } to the widget's inputAction property.
  • Widget to form: The widget dispatches an outputAction event with { [action]: payload } as its detail, for example { sliceSelected: { label: 'A' } }. Declare each action in outputActionModel so that Studio can offer it when building form logic.

A script can also replace the widget's configuration with api.setWidgetConfig(tagOrPath, config).

Bundle requirements​

Studio expects one self-contained JavaScript file per widget. Because the file is loaded as a classic script and not as a module, it must meet the following requirements:

  • No ES module syntax at the top level. No import and no export.
  • All dependencies inlined. Framework runtime, helpers, and styles are part of the file. Nothing is loaded from other files at runtime.
  • Exactly one customElements.define(...) call for the widget itself.
  • A valid custom element name as the tag name: it starts with a lowercase letter, contains at least one hyphen, and uses only lowercase letters, numbers, and hyphens.

IIFE is the bundler output format that produces exactly this. ES module output does not work.

Example: Lit and Rollup​

src/acme-rating-widget.js:

import { LitElement, html } from 'lit';

class AcmeRatingWidget extends LitElement {
static properties = {
config: { attribute: false },
inputData: { attribute: false },
readonly: { attribute: false },
useDefaultData: { attribute: false },
};

descriptor = {
valueModel: { type: 'number' },
configuration: {
max: { type: 'number', defaultValue: 5, metadata: { title: 'Maximum rating' } },
},
};

render() {
const max = this.config?.max ?? 5;
const value = this.useDefaultData !== false ? 3 : this.inputData ?? 0;
return html`${Array.from(
{ length: max },
(_, index) =>
html`<button ?disabled=${this.readonly} @click=${() => this.#select(index + 1)}>
${index < value ? '★' : '☆'}
</button>`,
)}`;
}

#select(value) {
this.dispatchEvent(new CustomEvent('outputData', { detail: value }));
}
}

customElements.define('acme-rating-widget', AcmeRatingWidget);

rollup.config.js:

import resolve from '@rollup/plugin-node-resolve';
import terser from '@rollup/plugin-terser';

export default {
input: 'src/acme-rating-widget.js',
output: {
file: 'dist/acme-rating-widget.js',
format: 'iife',
inlineDynamicImports: true,
},
plugins: [resolve(), terser()],
};

The same settings apply to other bundlers: one entry file, IIFE output, no external dependencies, and no code splitting. In Vite, for example, use library mode with formats: ['iife'].

good to know

The entry file must not export anything, and tree shaking must not treat the customElements.define call as removable. Registering the element is a side effect, and it is the whole purpose of the file.

To check that the result is self-contained, confirm that the built file contains no top-level import or export statements and no require( calls.

Selector detection and versioning​

How Studio finds the selector​

When you upload the file, Studio looks for the tag name in the customElements.define(...) call. Detection works when the first argument is a string literal:

customElements.define('acme-rating-widget', AcmeRatingWidget);

It cannot work when the tag name is held in a variable. This is what some decorators, such as Lit's @customElement, and some minifiers produce after bundling:

const t = 'acme-rating-widget';
customElements.define(t, AcmeRatingWidget);

In that case the upload dialog asks you to enter the selector by hand. Enter the same tag name you use in your source. Studio checks that the name is a valid custom element name and that it appears in the file as a whole word.

Why the tag name changes after upload​

Studio allows several versions of the same widget on one page, while the browser allows only one definition per tag name. On upload, Studio therefore rewrites the tag name to a version-scoped one, such as acme-rating-widget-<suffix>, and maps your original selector to it at runtime.

The rewrite replaces every occurrence of the selector text in the file, not only the one in customElements.define. This keeps internal references such as CSS selectors and querySelector calls consistent. It also has two consequences:

  • Choose a distinctive selector. A selector that also appears as part of unrelated strings, class names, or identifiers in your bundle is replaced there too. Prefix it with your organisation or product name.
  • Do not depend on the exact tag name at runtime. Read this.localName instead of hard-coding the selector where you need it.

Custom elements shared between widgets​

If your widget registers additional custom elements for its internal parts, and two of your widgets ship the same part, the second customElements.define call for the same tag name throws and that widget fails to load. Guard such registrations:

if (!customElements.get('acme-tooltip')) {
customElements.define('acme-tooltip', AcmeTooltip);
}

Local development and testing​

There is no dedicated development server for widgets. The recommended workflow is:

  1. Test in a plain HTML page. Load the built file with a <script> tag, create the element, and set the contract properties by hand. This verifies the bundle exactly as Studio loads it.

    <script src="dist/acme-rating-widget.js"></script>
    <acme-rating-widget></acme-rating-widget>
    <script>
    const widget = document.querySelector('acme-rating-widget');
    widget.useDefaultData = false;
    widget.config = { max: 10 };
    widget.inputData = 7;
    widget.addEventListener('outputData', (event) => console.log(event.detail));
    </script>
  2. Upload to a private library. The upload flow shows a preview of the widget and its configuration panel, which confirms that the selector and the descriptor were picked up.

  3. Try it in Form builder and Form playground. Check the canvas placeholder, the data binding, read-only mode, and a language change.

Uploading to the Marketplace​

Once your widget is built, upload it to your library on Marketplace from within Studio.

good to know

You always have access to the public library in Marketplace. However, submitting or uploading content to it is restricted. For more information on how to share your widgets in the public library, check the Marketplace section.

To upload a widget onto your private library:

  1. Open Marketplace from the Studio main screen or from the Widgets tab in the Generics fields panel.
  2. Click Sign in (top right). Studio creates a Marketplace account using your Studio credentials if one does not already exist.
  3. Once signed in, click Upload.
  4. Select your widget file. If Studio cannot detect the selector, enter it by hand.
  5. In the upload modal, choose which library to publish to. Libraries are organisation-controlled repositories. Members of a library can see and install content published there.
  6. Complete the metadata: Name, description, version, keywords, and any supporting content (AQL views, API calls).
  7. Optionally add documentation, screenshots, a "What's new" note, and attachments.
  8. Submit the upload.

For details on metadata, versioning, and sharing, see Uploading content.

warning

Upload permissions are required. To request your own library, or for any admin actions beyond adding library members and managing content, contact tools@better.care.

warning

Uploading through the Studio user interface is the only supported way to publish a widget. The underlying APIs are not a supported integration point and can change without notice.

Widget presets​

A preset is a saved configuration object for a widget. Presets let Studio users apply a known configuration in one click rather than filling in every option manually.

To create a preset:

  1. Open the widget in the Marketplace.
  2. Navigate to the presets section.
  3. Save the current configuration as a named preset.

Presets can be set as the default configuration for the widget. When a widget with presets is installed, the user can select a preset during installation.

Preset supporting content: If a preset's configuration references an AQL view or an API call, both can be bundled with the preset as supporting content when it is uploaded. This ensures that users who install the preset have all the dependencies they need.

Frequently asked questions (FAQs)​

Which framework should I use?

Any, or none. Studio only requires a standard custom element that follows the widget contract, delivered as one self-contained file. Smaller runtimes give smaller files, which matters when a form contains several widgets.

Can I upload an ES module bundle?

No. The file is loaded as a classic script, so top-level import and export statements fail. Build to the IIFE format with all dependencies inlined.

Why was my selector not detected during upload?

Detection needs a string literal as the first argument of customElements.define. If your tooling moves the tag name into a variable, enter the selector by hand in the upload dialog, or call customElements.define directly with a string literal in your source.

Why does my widget have a different tag name in the form?

Studio rewrites the tag name to a version-scoped name on upload, so that several versions of one widget can be loaded on the same page. Every occurrence of the selector in the file is replaced.

What is the difference between a read-only widget, an input widget, and an action widget?

Read-only widgets display data without accepting user input — for example, a patient banner or a chart. Input widgets accept user input and store the entered data in the composition in the same way as generic fields. Action widgets trigger actions — for example, buttons that initiate a workflow step.

Does outputData need to match the schema of inputData?

Yes. outputData must conform to the same schema as inputData, as defined in the valueModel of your descriptor.

What is useDefaultData and why does my widget need to handle it?

useDefaultData signals whether your widget is rendered on the Form builder canvas (design time) or in Form playground or a deployed form (runtime). When it is not false, display built-in placeholder data so that the widget looks meaningful on the canvas before any real data is bound.

Can I update my widget's configuration at runtime from a script?

Yes. Use api.setWidgetConfig(tagOrPath, config) from the Script API to replace a widget's configuration object. You can also send named actions to a widget with api.sendActionToWidget(tagOrPath, action, value).

Can I bind my widget to a data connector or AQL view rather than a form field?

Yes. The inputData binding supports form fields, variables, and data connector or API results. Configure the binding in the data mapping panel in Form builder when placing the widget on the canvas.

How do I make my widget available to other users in my organisation?

Upload your widget to your organisation's Marketplace library. Members of that library can then find, install, and use it in their forms. To make your widget available to users outside your library, contact tools@better.care.

I have a suggestion for a new widget capability, or I found an issue with the documentation on this page. Where should I report it?

Use the feedback link on the side of this page.