govuk-frontend
Version:
GOV.UK Frontend contains the code you need to start building a user interface for government platforms and services.
516 lines (499 loc) • 19.1 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.GOVUKFrontend = global.GOVUKFrontend || {}));
})(this, (function (exports) { 'use strict';
function closestAttributeValue($element, attributeName) {
const $closestElementWithAttribute = $element.closest(`[${attributeName}]`);
return $closestElementWithAttribute ? $closestElementWithAttribute.getAttribute(attributeName) : null;
}
function isInitialised($root, moduleName) {
return $root instanceof HTMLElement && $root.hasAttribute(`data-${moduleName}-init`);
}
/**
* Checks if GOV.UK Frontend is supported on this page
*
* Some browsers will load and run our JavaScript but GOV.UK Frontend
* won't be supported.
*
* @param {HTMLElement | null} [$scope] - (internal) `<body>` HTML element checked for browser support
* @returns {boolean} Whether GOV.UK Frontend is supported on this page
*/
function isSupported($scope = document.body) {
if (!$scope) {
return false;
}
return $scope.classList.contains('govuk-frontend-supported');
}
function isArray(option) {
return Array.isArray(option);
}
function isObject(option) {
return !!option && typeof option === 'object' && !isArray(option);
}
function formatErrorMessage(Component, message) {
return `${Component.moduleName}: ${message}`;
}
/**
* @typedef ComponentWithModuleName
* @property {string} moduleName - Name of the component
*/
class GOVUKFrontendError extends Error {
constructor(...args) {
super(...args);
this.name = 'GOVUKFrontendError';
}
}
class SupportError extends GOVUKFrontendError {
/**
* Checks if GOV.UK Frontend is supported on this page
*
* @param {HTMLElement | null} [$scope] - HTML element `<body>` checked for browser support
*/
constructor($scope = document.body) {
const supportMessage = 'noModule' in HTMLScriptElement.prototype ? 'GOV.UK Frontend initialised without `<body class="govuk-frontend-supported">` from template `<script>` snippet' : 'GOV.UK Frontend is not supported in this browser';
super($scope ? supportMessage : 'GOV.UK Frontend initialised without `<script type="module">`');
this.name = 'SupportError';
}
}
class ConfigError extends GOVUKFrontendError {
constructor(...args) {
super(...args);
this.name = 'ConfigError';
}
}
class ElementError extends GOVUKFrontendError {
constructor(messageOrOptions) {
let message = typeof messageOrOptions === 'string' ? messageOrOptions : '';
if (isObject(messageOrOptions)) {
const {
component,
identifier,
element,
expectedType
} = messageOrOptions;
message = identifier;
message += element ? ` is not of type ${expectedType != null ? expectedType : 'HTMLElement'}` : ' not found';
if (component) {
message = formatErrorMessage(component, message);
}
}
super(message);
this.name = 'ElementError';
}
}
class InitError extends GOVUKFrontendError {
constructor(componentOrMessage) {
const message = typeof componentOrMessage === 'string' ? componentOrMessage : formatErrorMessage(componentOrMessage, `Root element (\`$root\`) already initialised`);
super(message);
this.name = 'InitError';
}
}
/**
* @import { ComponentWithModuleName } from '../common/index.mjs'
*/
class Component {
/**
* Returns the root element of the component
*
* @protected
* @returns {RootElementType} - the root element of component
*/
get $root() {
return this._$root;
}
constructor($root) {
this._$root = void 0;
const childConstructor = this.constructor;
if (typeof childConstructor.moduleName !== 'string') {
throw new InitError(`\`moduleName\` not defined in component`);
}
if (!($root instanceof childConstructor.elementType)) {
throw new ElementError({
element: $root,
component: childConstructor,
identifier: 'Root element (`$root`)',
expectedType: childConstructor.elementType.name
});
} else {
this._$root = $root;
}
childConstructor.checkSupport();
this.checkInitialised();
const moduleName = childConstructor.moduleName;
this.$root.setAttribute(`data-${moduleName}-init`, '');
}
checkInitialised() {
const constructor = this.constructor;
const moduleName = constructor.moduleName;
if (moduleName && isInitialised(this.$root, moduleName)) {
throw new InitError(constructor);
}
}
static checkSupport() {
if (!isSupported()) {
throw new SupportError();
}
}
}
/**
* @typedef ChildClass
* @property {string} moduleName - The module name that'll be looked for in the DOM when initialising the component
*/
/**
* @typedef {typeof Component & ChildClass} ChildClassConstructor
*/
Component.elementType = HTMLElement;
const configOverride = Symbol.for('configOverride');
class ConfigurableComponent extends Component {
[configOverride](param) {
return {};
}
/**
* Returns the root element of the component
*
* @protected
* @returns {ConfigurationType} - the root element of component
*/
get config() {
return this._config;
}
constructor($root, config) {
super($root);
this._config = void 0;
const childConstructor = this.constructor;
if (!isObject(childConstructor.defaults)) {
throw new ConfigError(formatErrorMessage(childConstructor, 'Config passed as parameter into constructor but no defaults defined'));
}
const datasetConfig = normaliseDataset(childConstructor, this._$root.dataset);
this._config = mergeConfigs(childConstructor.defaults, config != null ? config : {}, this[configOverride](datasetConfig), datasetConfig);
}
}
function normaliseString(value, property) {
const trimmedValue = value ? value.trim() : '';
let output;
let outputType = property == null ? void 0 : property.type;
if (!outputType) {
if (['true', 'false'].includes(trimmedValue)) {
outputType = 'boolean';
}
if (trimmedValue.length > 0 && isFinite(Number(trimmedValue))) {
outputType = 'number';
}
}
switch (outputType) {
case 'boolean':
output = trimmedValue === 'true';
break;
case 'number':
output = Number(trimmedValue);
break;
default:
output = value;
}
return output;
}
function normaliseDataset(Component, dataset) {
if (!isObject(Component.schema)) {
throw new ConfigError(formatErrorMessage(Component, 'Config passed as parameter into constructor but no schema defined'));
}
const out = {};
const entries = Object.entries(Component.schema.properties);
for (const entry of entries) {
const [namespace, property] = entry;
const field = namespace.toString();
if (field in dataset) {
out[field] = normaliseString(dataset[field], property);
}
if ((property == null ? void 0 : property.type) === 'object') {
out[field] = extractConfigByNamespace(Component.schema, dataset, namespace);
}
}
return out;
}
function mergeConfigs(...configObjects) {
const formattedConfigObject = {};
for (const configObject of configObjects) {
for (const key of Object.keys(configObject)) {
const option = formattedConfigObject[key];
const override = configObject[key];
if (isObject(option) && isObject(override)) {
formattedConfigObject[key] = mergeConfigs(option, override);
} else {
formattedConfigObject[key] = override;
}
}
}
return formattedConfigObject;
}
function extractConfigByNamespace(schema, dataset, namespace) {
const property = schema.properties[namespace];
if ((property == null ? void 0 : property.type) !== 'object') {
return;
}
const newObject = {
[namespace]: {}
};
for (const [key, value] of Object.entries(dataset)) {
let current = newObject;
const keyParts = key.split('.');
for (const [index, name] of keyParts.entries()) {
if (isObject(current)) {
if (index < keyParts.length - 1) {
if (!isObject(current[name])) {
current[name] = {};
}
current = current[name];
} else if (key !== namespace) {
current[name] = normaliseString(value);
}
}
}
}
return newObject[namespace];
}
/**
* Schema for component config
*
* @template {Partial<Record<keyof ConfigurationType, unknown>>} ConfigurationType
* @typedef {object} Schema
* @property {Record<keyof ConfigurationType, SchemaProperty | undefined>} properties - Schema properties
* @property {SchemaCondition<ConfigurationType>[]} [anyOf] - List of schema conditions
*/
/**
* Schema property for component config
*
* @typedef {object} SchemaProperty
* @property {'string' | 'boolean' | 'number' | 'object'} type - Property type
*/
/**
* Schema condition for component config
*
* @template {Partial<Record<keyof ConfigurationType, unknown>>} ConfigurationType
* @typedef {object} SchemaCondition
* @property {(keyof ConfigurationType)[]} required - List of required config fields
* @property {string} errorMessage - Error message when required config fields not provided
*/
/**
* @template {Partial<Record<keyof ConfigurationType, unknown>>} [ConfigurationType=ObjectNested]
* @typedef ChildClass
* @property {string} moduleName - The module name that'll be looked for in the DOM when initialising the component
* @property {Schema<ConfigurationType>} [schema] - The schema of the component configuration
* @property {ConfigurationType} [defaults] - The default values of the configuration of the component
*/
/**
* @template {Partial<Record<keyof ConfigurationType, unknown>>} [ConfigurationType=ObjectNested]
* @typedef {typeof Component & ChildClass<ConfigurationType>} ChildClassConstructor<ConfigurationType>
*/
/**
* @import { CompatibleClass, Config, CreateAllOptions, OnErrorCallback } from '../init.mjs'
*/
class I18n {
constructor(translations = {}, config = {}) {
var _config$locale;
this.translations = void 0;
this.locale = void 0;
this.translations = translations;
this.locale = (_config$locale = config.locale) != null ? _config$locale : document.documentElement.lang || 'en';
}
t(lookupKey, options) {
if (!lookupKey) {
throw new Error('i18n: lookup key missing');
}
let translation = this.translations[lookupKey];
if (typeof (options == null ? void 0 : options.count) === 'number' && isObject(translation)) {
const translationPluralForm = translation[this.getPluralSuffix(lookupKey, options.count)];
if (translationPluralForm) {
translation = translationPluralForm;
}
}
if (typeof translation === 'string') {
if (translation.match(/%{(.\S+)}/)) {
if (!options) {
throw new Error('i18n: cannot replace placeholders in string if no option data provided');
}
return this.replacePlaceholders(translation, options);
}
return translation;
}
return lookupKey;
}
replacePlaceholders(translationString, options) {
const formatter = Intl.NumberFormat.supportedLocalesOf(this.locale).length ? new Intl.NumberFormat(this.locale) : undefined;
return translationString.replace(/%{(.\S+)}/g, function (placeholderWithBraces, placeholderKey) {
if (Object.prototype.hasOwnProperty.call(options, placeholderKey)) {
const placeholderValue = options[placeholderKey];
if (placeholderValue === false || typeof placeholderValue !== 'number' && typeof placeholderValue !== 'string') {
return '';
}
if (typeof placeholderValue === 'number') {
return formatter ? formatter.format(placeholderValue) : `${placeholderValue}`;
}
return placeholderValue;
}
throw new Error(`i18n: no data found to replace ${placeholderWithBraces} placeholder in string`);
});
}
hasIntlPluralRulesSupport() {
return Boolean('PluralRules' in window.Intl && Intl.PluralRules.supportedLocalesOf(this.locale).length);
}
getPluralSuffix(lookupKey, count) {
count = Number(count);
if (!isFinite(count)) {
return 'other';
}
const translation = this.translations[lookupKey];
const preferredForm = this.hasIntlPluralRulesSupport() ? new Intl.PluralRules(this.locale).select(count) : 'other';
if (isObject(translation)) {
if (preferredForm in translation) {
return preferredForm;
} else if ('other' in translation) {
console.warn(`i18n: Missing plural form ".${preferredForm}" for "${this.locale}" locale. Falling back to ".other".`);
return 'other';
}
}
throw new Error(`i18n: Plural form ".other" is required for "${this.locale}" locale`);
}
}
/**
* Password input component
*
* @preserve
* @augments ConfigurableComponent<PasswordInputConfig>
*/
class PasswordInput extends ConfigurableComponent {
/**
* @param {Element | null} $root - HTML element to use for password input
* @param {PasswordInputConfig} [config] - Password input config
*/
constructor($root, config = {}) {
super($root, config);
this.i18n = void 0;
this.$input = void 0;
this.$showHideButton = void 0;
this.$screenReaderStatusMessage = void 0;
const $input = this.$root.querySelector('.govuk-js-password-input-input');
if (!($input instanceof HTMLInputElement)) {
throw new ElementError({
component: PasswordInput,
element: $input,
expectedType: 'HTMLInputElement',
identifier: 'Form field (`.govuk-js-password-input-input`)'
});
}
if ($input.type !== 'password') {
throw new ElementError('Password input: Form field (`.govuk-js-password-input-input`) must be of type `password`.');
}
const $showHideButton = this.$root.querySelector('.govuk-js-password-input-toggle');
if (!($showHideButton instanceof HTMLButtonElement)) {
throw new ElementError({
component: PasswordInput,
element: $showHideButton,
expectedType: 'HTMLButtonElement',
identifier: 'Button (`.govuk-js-password-input-toggle`)'
});
}
if ($showHideButton.type !== 'button') {
throw new ElementError('Password input: Button (`.govuk-js-password-input-toggle`) must be of type `button`.');
}
this.$input = $input;
this.$showHideButton = $showHideButton;
this.i18n = new I18n(this.config.i18n, {
locale: closestAttributeValue(this.$root, 'lang')
});
this.$showHideButton.removeAttribute('hidden');
const $screenReaderStatusMessage = document.createElement('div');
$screenReaderStatusMessage.className = 'govuk-password-input__sr-status govuk-visually-hidden';
$screenReaderStatusMessage.setAttribute('aria-live', 'polite');
this.$screenReaderStatusMessage = $screenReaderStatusMessage;
this.$input.insertAdjacentElement('afterend', $screenReaderStatusMessage);
this.$showHideButton.addEventListener('click', this.toggle.bind(this));
if (this.$input.form) {
this.$input.form.addEventListener('submit', () => this.hide());
}
window.addEventListener('pageshow', event => {
if (event.persisted && this.$input.type !== 'password') {
this.hide();
}
});
this.hide();
}
toggle(event) {
event.preventDefault();
if (this.$input.type === 'password') {
this.show();
return;
}
this.hide();
}
show() {
this.setType('text');
}
hide() {
this.setType('password');
}
setType(type) {
if (type === this.$input.type) {
return;
}
this.$input.setAttribute('type', type);
const isHidden = type === 'password';
const prefixButton = isHidden ? 'show' : 'hide';
const prefixStatus = isHidden ? 'passwordHidden' : 'passwordShown';
this.$showHideButton.innerText = this.i18n.t(`${prefixButton}Password`);
this.$showHideButton.setAttribute('aria-label', this.i18n.t(`${prefixButton}PasswordAriaLabel`));
this.$screenReaderStatusMessage.innerText = this.i18n.t(`${prefixStatus}Announcement`);
}
}
/**
* Password input config
*
* @typedef {object} PasswordInputConfig
* @property {PasswordInputTranslations} [i18n=PasswordInput.defaults.i18n] - Password input translations
*/
/**
* Password input translations
*
* @see {@link PasswordInput.defaults.i18n}
* @typedef {object} PasswordInputTranslations
*
* Messages displayed to the user indicating the state of the show/hide toggle.
* @property {string} [showPassword] - Visible text of the button when the
* password is currently hidden. Plain text only.
* @property {string} [hidePassword] - Visible text of the button when the
* password is currently visible. Plain text only.
* @property {string} [showPasswordAriaLabel] - aria-label of the button when
* the password is currently hidden. Plain text only.
* @property {string} [hidePasswordAriaLabel] - aria-label of the button when
* the password is currently visible. Plain text only.
* @property {string} [passwordShownAnnouncement] - Screen reader
* announcement to make when the password has just become visible.
* Plain text only.
* @property {string} [passwordHiddenAnnouncement] - Screen reader
* announcement to make when the password has just been hidden.
* Plain text only.
*/
/**
* @import { Schema } from '../../common/configuration.mjs'
*/
PasswordInput.moduleName = 'govuk-password-input';
PasswordInput.defaults = Object.freeze({
i18n: {
showPassword: 'Show',
hidePassword: 'Hide',
showPasswordAriaLabel: 'Show password',
hidePasswordAriaLabel: 'Hide password',
passwordShownAnnouncement: 'Your password is visible',
passwordHiddenAnnouncement: 'Your password is hidden'
}
});
PasswordInput.schema = Object.freeze({
properties: {
i18n: {
type: 'object'
}
}
});
exports.PasswordInput = PasswordInput;
}));
//# sourceMappingURL=password-input.bundle.js.map