Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SPIKE] Add JS property observer function; allow for programatic updating of character count #5067

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

querkmachine
Copy link
Member

Some experimental code dabbling into one way we could resolve the old, old problem of form controls with associated JS not responding to programatic value changes.

This is only one possible approach. In the past we've discussed creating an explicit JavaScript API for changing those values, but this hasn't yet come to fruition.

Changes

  • Introduces a new helper function, observeElementProperty, which overrides an HTML element's native property setter function to inject a customisable callback function, allowing us to invoke custom code when the property's value is changed.
  • Add some (currently very minimal) tests for this function.
  • Updates the Character Count component to use this function, updating the counters in response to programatic changes to the textarea's value property.

I've devtested this in all contemporary major browser engines and back to Safari 11 without issue.

Limitations

As this works by overriding the property's native setter function, this solution only works for direct manipulation of a property value. It does not work if the property value is passively updated by some other code.

observeElementProperty($input, 'disabled', () => {})
observeElementProperty($input, 'value', () => {})

// These will invoke the callback function
$input.disabled = true
$input.value = 'hello world'

// These will not invoke the callback function, even though changing these attributes also updates the underlying properties
$input.removeAttribute('disabled') 
$input.setAttribute('value', 'hello world')

Property setters and getters come as a pair. Because we're overriding the setter, we must also redefine the getter. In this case, I've just manually re-invoked the native getter.

I've not done extensive testing on this whatsoever. There is a possibility that by overriding the native property handling that something somewhere else may become broken as a result.

Add an observer to the character count component's `value` property and call the usual counter update functions if it gets changed programatically.
Copy link

📋 Stats

File sizes

File Size
dist/govuk-frontend-development.min.css 113.43 KiB
dist/govuk-frontend-development.min.js 42.23 KiB
packages/govuk-frontend/dist/govuk/all.bundle.js 88.27 KiB
packages/govuk-frontend/dist/govuk/all.bundle.mjs 82.93 KiB
packages/govuk-frontend/dist/govuk/all.mjs 981 B
packages/govuk-frontend/dist/govuk/govuk-frontend-component.mjs 359 B
packages/govuk-frontend/dist/govuk/govuk-frontend.min.css 113.42 KiB
packages/govuk-frontend/dist/govuk/govuk-frontend.min.js 42.22 KiB
packages/govuk-frontend/dist/govuk/i18n.mjs 5.55 KiB
packages/govuk-frontend/dist/govuk/init.mjs 4.86 KiB

Modules

File Size (bundled) Size (minified)
all.mjs 80.06 KiB 40.2 KiB
accordion.mjs 23.5 KiB 12.39 KiB
button.mjs 5.98 KiB 2.69 KiB
character-count.mjs 23.22 KiB 10.27 KiB
checkboxes.mjs 5.83 KiB 2.83 KiB
error-summary.mjs 7.89 KiB 3.46 KiB
exit-this-page.mjs 17.1 KiB 9.26 KiB
header.mjs 4.46 KiB 2.6 KiB
notification-banner.mjs 6.26 KiB 2.62 KiB
password-input.mjs 15.15 KiB 7.25 KiB
radios.mjs 4.83 KiB 2.38 KiB
skip-link.mjs 4.39 KiB 2.18 KiB
tabs.mjs 10.13 KiB 6.11 KiB

View stats and visualisations on the review app


Action run for 918908b

Copy link

JavaScript changes to npm package

diff --git a/packages/govuk-frontend/dist/govuk/govuk-frontend.min.js b/packages/govuk-frontend/dist/govuk/govuk-frontend.min.js
index 754775151..189ae02b3 100644
--- a/packages/govuk-frontend/dist/govuk/govuk-frontend.min.js
+++ b/packages/govuk-frontend/dist/govuk/govuk-frontend.min.js
@@ -445,7 +445,21 @@ class CharacterCount extends GOVUKFrontendComponent {
         const h = document.createElement("div");
         h.className = "govuk-character-count__sr-status govuk-visually-hidden", h.setAttribute("aria-live", "polite"), this.$screenReaderCountMessage = h, c.insertAdjacentElement("afterend", h);
         const u = document.createElement("div");
-        u.className = c.className, u.classList.add("govuk-character-count__status"), u.setAttribute("aria-hidden", "true"), this.$visibleCountMessage = u, c.insertAdjacentElement("afterend", u), c.classList.add("govuk-visually-hidden"), this.$textarea.removeAttribute("maxlength"), this.bindChangeEvents(), window.addEventListener("pageshow", (() => this.updateCountMessage())), this.updateCountMessage()
+        u.className = c.className, u.classList.add("govuk-character-count__status"), u.setAttribute("aria-hidden", "true"), this.$visibleCountMessage = u, c.insertAdjacentElement("afterend", u), c.classList.add("govuk-visually-hidden"), this.$textarea.removeAttribute("maxlength"), this.bindChangeEvents(), window.addEventListener("pageshow", (() => this.updateCountMessage())), this.updateCountMessage(),
+            function(e, t, n) {
+                var i;
+                const s = null != (i = Object.getOwnPropertyDescriptor(e, t)) ? i : Object.getOwnPropertyDescriptor(e.constructor.prototype, t);
+                Object.defineProperty(e, t, {
+                    set(e) {
+                        var t;
+                        null == s || null == (t = s.set) || t.call(this, e), n.call(this, e)
+                    },
+                    get() {
+                        var e;
+                        return null == s || null == (e = s.get) ? void 0 : e.call(this)
+                    }
+                })
+            }(this.$textarea, "value", this.updateCountMessage.bind(this))
     }
     bindChangeEvents() {
         this.$textarea.addEventListener("keyup", (() => this.handleKeyUp())), this.$textarea.addEventListener("focus", (() => this.handleFocus())), this.$textarea.addEventListener("blur", (() => this.handleBlur()))

Action run for 918908b

Copy link

Other changes to npm package

diff --git a/packages/govuk-frontend/dist/govuk/all.bundle.js b/packages/govuk-frontend/dist/govuk/all.bundle.js
index fbc644fbf..962f93ebc 100644
--- a/packages/govuk-frontend/dist/govuk/all.bundle.js
+++ b/packages/govuk-frontend/dist/govuk/all.bundle.js
@@ -860,6 +860,22 @@
     return $closestElementWithAttribute ? $closestElementWithAttribute.getAttribute(attributeName) : null;
   }
 
+  function observeElementProperty(element, property, callback) {
+    var _Object$getOwnPropert;
+    const nativeProperty = (_Object$getOwnPropert = Object.getOwnPropertyDescriptor(element, property)) != null ? _Object$getOwnPropert : Object.getOwnPropertyDescriptor(element.constructor.prototype, property);
+    Object.defineProperty(element, property, {
+      set(value) {
+        var _nativeProperty$set;
+        nativeProperty == null || (_nativeProperty$set = nativeProperty.set) == null || _nativeProperty$set.call(this, value);
+        callback.call(this, value);
+      },
+      get() {
+        var _nativeProperty$get;
+        return nativeProperty == null || (_nativeProperty$get = nativeProperty.get) == null ? void 0 : _nativeProperty$get.call(this);
+      }
+    });
+  }
+
   /**
    * Character count component
    *
@@ -956,6 +972,7 @@
       this.bindChangeEvents();
       window.addEventListener('pageshow', () => this.updateCountMessage());
       this.updateCountMessage();
+      observeElementProperty(this.$textarea, 'value', this.updateCountMessage.bind(this));
     }
     bindChangeEvents() {
       this.$textarea.addEventListener('keyup', () => this.handleKeyUp());
diff --git a/packages/govuk-frontend/dist/govuk/all.bundle.mjs b/packages/govuk-frontend/dist/govuk/all.bundle.mjs
index 3d03f5f0f..80e2d4168 100644
--- a/packages/govuk-frontend/dist/govuk/all.bundle.mjs
+++ b/packages/govuk-frontend/dist/govuk/all.bundle.mjs
@@ -854,6 +854,22 @@ function closestAttributeValue($element, attributeName) {
   return $closestElementWithAttribute ? $closestElementWithAttribute.getAttribute(attributeName) : null;
 }
 
+function observeElementProperty(element, property, callback) {
+  var _Object$getOwnPropert;
+  const nativeProperty = (_Object$getOwnPropert = Object.getOwnPropertyDescriptor(element, property)) != null ? _Object$getOwnPropert : Object.getOwnPropertyDescriptor(element.constructor.prototype, property);
+  Object.defineProperty(element, property, {
+    set(value) {
+      var _nativeProperty$set;
+      nativeProperty == null || (_nativeProperty$set = nativeProperty.set) == null || _nativeProperty$set.call(this, value);
+      callback.call(this, value);
+    },
+    get() {
+      var _nativeProperty$get;
+      return nativeProperty == null || (_nativeProperty$get = nativeProperty.get) == null ? void 0 : _nativeProperty$get.call(this);
+    }
+  });
+}
+
 /**
  * Character count component
  *
@@ -950,6 +966,7 @@ class CharacterCount extends GOVUKFrontendComponent {
     this.bindChangeEvents();
     window.addEventListener('pageshow', () => this.updateCountMessage());
     this.updateCountMessage();
+    observeElementProperty(this.$textarea, 'value', this.updateCountMessage.bind(this));
   }
   bindChangeEvents() {
     this.$textarea.addEventListener('keyup', () => this.handleKeyUp());
diff --git a/packages/govuk-frontend/dist/govuk/common/observe-element-property.mjs b/packages/govuk-frontend/dist/govuk/common/observe-element-property.mjs
new file mode 100644
index 000000000..85d47ade9
--- /dev/null
+++ b/packages/govuk-frontend/dist/govuk/common/observe-element-property.mjs
@@ -0,0 +1,18 @@
+function observeElementProperty(element, property, callback) {
+  var _Object$getOwnPropert;
+  const nativeProperty = (_Object$getOwnPropert = Object.getOwnPropertyDescriptor(element, property)) != null ? _Object$getOwnPropert : Object.getOwnPropertyDescriptor(element.constructor.prototype, property);
+  Object.defineProperty(element, property, {
+    set(value) {
+      var _nativeProperty$set;
+      nativeProperty == null || (_nativeProperty$set = nativeProperty.set) == null || _nativeProperty$set.call(this, value);
+      callback.call(this, value);
+    },
+    get() {
+      var _nativeProperty$get;
+      return nativeProperty == null || (_nativeProperty$get = nativeProperty.get) == null ? void 0 : _nativeProperty$get.call(this);
+    }
+  });
+}
+
+export { observeElementProperty };
+//# sourceMappingURL=observe-element-property.mjs.map
diff --git a/packages/govuk-frontend/dist/govuk/components/character-count/character-count.bundle.js b/packages/govuk-frontend/dist/govuk/components/character-count/character-count.bundle.js
index baeeae62c..c35dcc5bf 100644
--- a/packages/govuk-frontend/dist/govuk/components/character-count/character-count.bundle.js
+++ b/packages/govuk-frontend/dist/govuk/components/character-count/character-count.bundle.js
@@ -148,6 +148,22 @@
     return out;
   }
 
+  function observeElementProperty(element, property, callback) {
+    var _Object$getOwnPropert;
+    const nativeProperty = (_Object$getOwnPropert = Object.getOwnPropertyDescriptor(element, property)) != null ? _Object$getOwnPropert : Object.getOwnPropertyDescriptor(element.constructor.prototype, property);
+    Object.defineProperty(element, property, {
+      set(value) {
+        var _nativeProperty$set;
+        nativeProperty == null || (_nativeProperty$set = nativeProperty.set) == null || _nativeProperty$set.call(this, value);
+        callback.call(this, value);
+      },
+      get() {
+        var _nativeProperty$get;
+        return nativeProperty == null || (_nativeProperty$get = nativeProperty.get) == null ? void 0 : _nativeProperty$get.call(this);
+      }
+    });
+  }
+
   class GOVUKFrontendError extends Error {
     constructor(...args) {
       super(...args);
@@ -490,6 +506,7 @@
       this.bindChangeEvents();
       window.addEventListener('pageshow', () => this.updateCountMessage());
       this.updateCountMessage();
+      observeElementProperty(this.$textarea, 'value', this.updateCountMessage.bind(this));
     }
     bindChangeEvents() {
       this.$textarea.addEventListener('keyup', () => this.handleKeyUp());
diff --git a/packages/govuk-frontend/dist/govuk/components/character-count/character-count.bundle.mjs b/packages/govuk-frontend/dist/govuk/components/character-count/character-count.bundle.mjs
index 473db45b5..244c03e8b 100644
--- a/packages/govuk-frontend/dist/govuk/components/character-count/character-count.bundle.mjs
+++ b/packages/govuk-frontend/dist/govuk/components/character-count/character-count.bundle.mjs
@@ -142,6 +142,22 @@ function normaliseDataset(Component, dataset) {
   return out;
 }
 
+function observeElementProperty(element, property, callback) {
+  var _Object$getOwnPropert;
+  const nativeProperty = (_Object$getOwnPropert = Object.getOwnPropertyDescriptor(element, property)) != null ? _Object$getOwnPropert : Object.getOwnPropertyDescriptor(element.constructor.prototype, property);
+  Object.defineProperty(element, property, {
+    set(value) {
+      var _nativeProperty$set;
+      nativeProperty == null || (_nativeProperty$set = nativeProperty.set) == null || _nativeProperty$set.call(this, value);
+      callback.call(this, value);
+    },
+    get() {
+      var _nativeProperty$get;
+      return nativeProperty == null || (_nativeProperty$get = nativeProperty.get) == null ? void 0 : _nativeProperty$get.call(this);
+    }
+  });
+}
+
 class GOVUKFrontendError extends Error {
   constructor(...args) {
     super(...args);
@@ -484,6 +500,7 @@ class CharacterCount extends GOVUKFrontendComponent {
     this.bindChangeEvents();
     window.addEventListener('pageshow', () => this.updateCountMessage());
     this.updateCountMessage();
+    observeElementProperty(this.$textarea, 'value', this.updateCountMessage.bind(this));
   }
   bindChangeEvents() {
     this.$textarea.addEventListener('keyup', () => this.handleKeyUp());
diff --git a/packages/govuk-frontend/dist/govuk/components/character-count/character-count.mjs b/packages/govuk-frontend/dist/govuk/components/character-count/character-count.mjs
index 955e4ef16..04dd78d5b 100644
--- a/packages/govuk-frontend/dist/govuk/components/character-count/character-count.mjs
+++ b/packages/govuk-frontend/dist/govuk/components/character-count/character-count.mjs
@@ -1,6 +1,7 @@
 import { closestAttributeValue } from '../../common/closest-attribute-value.mjs';
 import { mergeConfigs, validateConfig } from '../../common/index.mjs';
 import { normaliseDataset } from '../../common/normalise-dataset.mjs';
+import { observeElementProperty } from '../../common/observe-element-property.mjs';
 import { ElementError, ConfigError } from '../../errors/index.mjs';
 import { GOVUKFrontendComponent } from '../../govuk-frontend-component.mjs';
 import { I18n } from '../../i18n.mjs';
@@ -101,6 +102,7 @@ class CharacterCount extends GOVUKFrontendComponent {
     this.bindChangeEvents();
     window.addEventListener('pageshow', () => this.updateCountMessage());
     this.updateCountMessage();
+    observeElementProperty(this.$textarea, 'value', this.updateCountMessage.bind(this));
   }
   bindChangeEvents() {
     this.$textarea.addEventListener('keyup', () => this.handleKeyUp());

Action run for 918908b

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants