From 915fcdd8ad35128e1ccd78df1923523c2d64b3df Mon Sep 17 00:00:00 2001 From: "Storm B. Heg" Date: Thu, 20 Jul 2023 14:59:12 +0200 Subject: [PATCH] Allow Telepath's widget rendering to take options This will allow us supply attributes to be included in the widgets' rendered html. Similar how to Django widgets can take a `attrs` argument. --- .../src/entrypoints/admin/telepath/widgets.js | 24 +++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/client/src/entrypoints/admin/telepath/widgets.js b/client/src/entrypoints/admin/telepath/widgets.js index 4dfe7fa504ea..98c3b9b8b965 100644 --- a/client/src/entrypoints/admin/telepath/widgets.js +++ b/client/src/entrypoints/admin/telepath/widgets.js @@ -2,12 +2,20 @@ import { gettext } from '../../../utils/gettext'; class BoundWidget { - constructor(element, name, idForLabel, initialState, parentCapabilities) { + constructor( + element, + name, + idForLabel, + initialState, + parentCapabilities, + options, + ) { var selector = ':input[name="' + name + '"]'; this.input = element.find(selector).addBack(selector); // find, including element itself this.idForLabel = idForLabel; this.setState(initialState); this.parentCapabilities = parentCapabilities || new Map(); + this.options = options; } getValue() { @@ -49,10 +57,21 @@ class Widget { boundWidgetClass = BoundWidget; - render(placeholder, name, id, initialState, parentCapabilities) { + render(placeholder, name, id, initialState, parentCapabilities, options) { var html = this.html.replace(/__NAME__/g, name).replace(/__ID__/g, id); var idForLabel = this.idPattern.replace(/__ID__/g, id); var dom = $(html); + + // Add any extra attributes we received to the HTML of the widget + if ( + options && + 'attributes' in options && + typeof options.attributes === 'object' + ) { + Object.entries(options.attributes).forEach(([key, value]) => { + dom.attr(key, value); + }); + } $(placeholder).replaceWith(dom); // eslint-disable-next-line new-cap return new this.boundWidgetClass( @@ -61,6 +80,7 @@ class Widget { idForLabel, initialState, parentCapabilities, + options, ); } }