From 9b90449afa07537be611379384abab307b136756 Mon Sep 17 00:00:00 2001 From: Romaric Date: Mon, 17 Oct 2022 15:30:12 +0100 Subject: [PATCH] Make CharacterCount's JS inject fallback hint if missing --- .../character-count/character-count.mjs | 7 ++++++ .../character-count/character-count.test.js | 22 +++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/src/govuk/components/character-count/character-count.mjs b/src/govuk/components/character-count/character-count.mjs index 95239faccf..2286b05267 100644 --- a/src/govuk/components/character-count/character-count.mjs +++ b/src/govuk/components/character-count/character-count.mjs @@ -120,6 +120,13 @@ CharacterCount.prototype.init = function () { var $textarea = this.$textarea var $fallbackLimitMessage = document.getElementById($textarea.id + '-info') + // Inject a decription for the textarea if none is present already + // for when the component was rendered with no maxlength, maxwords + // nor custom fallbackHintText + if ($fallbackLimitMessage.textContent.match(/^\s*$/)) { + $fallbackLimitMessage.textContent = this.i18n.t('fallbackHint', { count: this.maxLength }) + } + // Move the fallback count message to be immediately after the textarea // Kept for backwards compatibility $textarea.insertAdjacentElement('afterend', $fallbackLimitMessage) diff --git a/src/govuk/components/character-count/character-count.test.js b/src/govuk/components/character-count/character-count.test.js index 0c95ea8992..40c077ded8 100644 --- a/src/govuk/components/character-count/character-count.test.js +++ b/src/govuk/components/character-count/character-count.test.js @@ -433,6 +433,28 @@ describe('Character count', () => { const visibility = await page.$eval('.govuk-character-count__status', el => window.getComputedStyle(el).visibility) expect(visibility).toEqual('visible') }) + + it.only('injects the description of the textarea', async () => { + page.on('console', async (e) => { + const args = await Promise.all( + e.args().map((a) => a.jsonValue()) + ) + console[e.type() === 'warning' ? 'warn' : e.type()](...args) + }) + + await renderAndInitialise(page, 'character-count', { + nunjucksParams: examples['no maximum'], + javascriptConfig: { + maxlength: 10 + } + }) + + const message = await page.$eval( + '.govuk-character-count__message', + (el) => el.innerHTML.trim() + ) + expect(message).toEqual('No more than 10 characters') + }) }) describe('via `initAll`', () => {