@defra/forms-engine-plugin 5.0.0-alpha.12 → 5.0.0-alpha.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.public/javascripts/shared.min.js +1 -1
- package/.public/javascripts/shared.min.js.map +1 -1
- package/.server/client/javascripts/geospatial-map.d.ts +153 -5
- package/.server/client/javascripts/geospatial-map.js +147 -46
- package/.server/client/javascripts/geospatial-map.js.map +1 -1
- package/.server/client/javascripts/location-map.d.ts +38 -0
- package/.server/client/javascripts/location-map.js +42 -2
- package/.server/client/javascripts/location-map.js.map +1 -1
- package/.server/client/javascripts/map-constants.d.ts +3 -0
- package/.server/client/javascripts/map-constants.js +4 -0
- package/.server/client/javascripts/map-constants.js.map +1 -0
- package/.server/client/javascripts/map.d.ts +4 -0
- package/.server/client/javascripts/map.js +5 -0
- package/.server/client/javascripts/map.js.map +1 -1
- package/.server/server/plugins/engine/__stubs__/definitions.d.ts +29 -0
- package/.server/server/plugins/engine/__stubs__/definitions.js +125 -0
- package/.server/server/plugins/engine/__stubs__/definitions.js.map +1 -0
- package/.server/server/plugins/engine/components/EastingNorthingField.d.ts +2 -0
- package/.server/server/plugins/engine/components/GeospatialField.d.ts +1 -0
- package/.server/server/plugins/engine/components/GeospatialField.js +1 -0
- package/.server/server/plugins/engine/components/GeospatialField.js.map +1 -1
- package/.server/server/plugins/engine/components/LatLongField.d.ts +2 -0
- package/.server/server/plugins/engine/components/LocationFieldBase.js +3 -0
- package/.server/server/plugins/engine/components/LocationFieldBase.js.map +1 -1
- package/.server/server/plugins/engine/components/LocationFieldHelpers.d.ts +2 -0
- package/.server/server/plugins/engine/components/LocationFieldHelpers.js +2 -1
- package/.server/server/plugins/engine/components/LocationFieldHelpers.js.map +1 -1
- package/.server/server/plugins/engine/components/helpers/components.js +2 -1
- package/.server/server/plugins/engine/components/helpers/components.js.map +1 -1
- package/.server/server/plugins/engine/errors.d.ts +49 -0
- package/.server/server/plugins/engine/errors.js +75 -0
- package/.server/server/plugins/engine/errors.js.map +1 -0
- package/.server/server/plugins/engine/i18n/translations/cy.json +51 -1
- package/.server/server/plugins/engine/i18n/translations/en-GB.json +51 -1
- package/.server/server/plugins/engine/models/FormModel.js +10 -2
- package/.server/server/plugins/engine/models/FormModel.js.map +1 -1
- package/.server/server/plugins/engine/pageControllers/helpers/pages.js +2 -1
- package/.server/server/plugins/engine/pageControllers/helpers/pages.js.map +1 -1
- package/.server/server/plugins/engine/views/components/_location-field-base.html +1 -0
- package/.server/server/plugins/engine/views/components/geospatialfield.html +1 -0
- package/.server/server/plugins/engine/views/components/osgridreffield.html +3 -1
- package/package.json +1 -1
- package/src/client/javascripts/geospatial-map.js +169 -47
- package/src/client/javascripts/location-map.js +50 -2
- package/src/client/javascripts/map-constants.js +3 -0
- package/src/client/javascripts/map.js +5 -0
- package/src/server/plugins/engine/__stubs__/definitions.ts +155 -0
- package/src/server/plugins/engine/components/GeospatialField.ts +1 -0
- package/src/server/plugins/engine/components/LocationFieldBase.ts +4 -0
- package/src/server/plugins/engine/components/LocationFieldHelpers.ts +2 -1
- package/src/server/plugins/engine/components/helpers/components.ts +2 -1
- package/src/server/plugins/engine/errors.ts +78 -0
- package/src/server/plugins/engine/i18n/translations/cy.json +51 -1
- package/src/server/plugins/engine/i18n/translations/en-GB.json +51 -1
- package/src/server/plugins/engine/models/FormModel.ts +12 -2
- package/src/server/plugins/engine/pageControllers/helpers/pages.ts +2 -1
- package/src/server/plugins/engine/views/components/_location-field-base.html +1 -0
- package/src/server/plugins/engine/views/components/geospatialfield.html +1 -0
- package/src/server/plugins/engine/views/components/osgridreffield.html +3 -1
|
@@ -449,4 +449,9 @@ export function getMapCountryLayers(apiPath, country) {
|
|
|
449
449
|
/**
|
|
450
450
|
* @import { Feature } from '../../server/plugins/engine/types.js'
|
|
451
451
|
*/
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* Supported language codes
|
|
455
|
+
* @typedef {('en-GB'|'cy')} LanguageCode
|
|
456
|
+
*/
|
|
452
457
|
//# sourceMappingURL=map.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"map.js","names":["InteractiveMap","createInteractPlugin","createMapStylesPlugin","createScaleBarPlugin","createSearchPlugin","maplibreProvider","centroid","OsGridRef","LatLon","processGeospatial","processLocation","DEFAULT_LAT","DEFAULT_LONG","COMPANY_SYMBOL_CODE","defaultData","VTS_OUTDOOR_URL","VTS_DARK_URL","VTS_BLACK_AND_WHITE_URL","VTS_AERIAL_URL","latLongToEastingNorthing","lat","long","point","toOsGrid","eastingNorthingToLatLong","easting","northing","latLong","toLatLon","latitude","longitude","latLongToOsGridRef","toString","osGridRefToLatLong","osGridRef","parse","getCoordinateGridRef","feature","geometry","type","coordinates","getCentroidGridRef","centre","defaultConfig","zoom","center","EVENTS","mapReady","interactMarkerChange","drawReady","drawCreated","drawEdited","drawCancelled","formSubmitFactory","buttons","onFormSubmit","e","submitter","HTMLButtonElement","includes","preventDefault","initMaps","config","assetPath","apiPath","data","locations","document","querySelectorAll","geospatials","length","form","closest","Array","from","addEventListener","forEach","location","index","geospatial","makeTileRequestTransformer","transformTileRequest","url","resourceType","startsWith","replace","window","origin","headers","encodeURIComponent","spritesPath","path","substring","createMap","mapId","initConfig","mapsConfig","logoAltText","interactPlugin","markerColor","outdoor","dark","interactionModes","multiSelect","map","enableFullscreen","autoColorScheme","mapProvider","behaviour","minZoom","maxZoom","containerHeight","enableZoomControls","transformRequest","plugins","mapStyles","id","label","thumbnail","logo","attribution","String","fromCodePoint","Date","getFullYear","backgroundColor","mapColorScheme","appColorScheme","osNamesURL","width","showMarker","units","centerMap","addMarker","flyTo","essential","getMapLayers","layers","trimmed","trim","split","getMapCountryLayers","country","datasets","push","geojson","showInKey","showInMenu","style","stroke","strokeWidth","fill"],"sources":["../../../src/client/javascripts/map.js"],"sourcesContent":["// @ts-expect-error - no types\nimport InteractiveMap from '@defra/interactive-map'\n// @ts-expect-error - no types\nimport createInteractPlugin from '@defra/interactive-map/plugins/interact'\n// @ts-expect-error - no types\nimport createMapStylesPlugin from '@defra/interactive-map/plugins/map-styles'\n// @ts-expect-error - no types\nimport createScaleBarPlugin from '@defra/interactive-map/plugins/scale-bar'\n// @ts-expect-error - no types\nimport createSearchPlugin from '@defra/interactive-map/plugins/search'\n// @ts-expect-error - no types\nimport maplibreProvider from '@defra/interactive-map/providers/maplibre'\nimport { centroid } from '@turf/centroid'\n// @ts-expect-error - no types\nimport OsGridRef, { LatLon } from 'geodesy/osgridref.js'\n\nimport { processGeospatial } from '~/src/client/javascripts/geospatial-map.js'\nimport { processLocation } from '~/src/client/javascripts/location-map.js'\n\n// Center of UK\nconst DEFAULT_LAT = 53.825564\nconst DEFAULT_LONG = -2.421975\nconst COMPANY_SYMBOL_CODE = 169\n\nconst defaultData = {\n VTS_OUTDOOR_URL: '/api/maps/vts/OS_VTS_3857_Outdoor.json',\n VTS_DARK_URL: '/api/maps/vts/OS_VTS_3857_Dark.json',\n VTS_BLACK_AND_WHITE_URL: '/api/maps/vts/OS_VTS_3857_Black_and_White.json',\n VTS_AERIAL_URL: '/api/maps/vts/esri-aerial.json'\n}\n\n/**\n * Converts lat long to easting and northing\n * @param {object} param\n * @param {number} param.lat\n * @param {number} param.long\n * @returns {{ easting: number, northing: number }}\n */\nexport function latLongToEastingNorthing({ lat, long }) {\n const point = new LatLon(lat, long)\n\n return point.toOsGrid()\n}\n\n/**\n * Converts easting and northing to lat long\n * @param {object} param\n * @param {number} param.easting\n * @param {number} param.northing\n * @returns {{ lat: number, long: number }}\n */\nexport function eastingNorthingToLatLong({ easting, northing }) {\n const point = new OsGridRef(easting, northing)\n const latLong = point.toLatLon()\n\n return { lat: latLong.latitude, long: latLong.longitude }\n}\n\n/**\n * Converts lat long to an ordnance survey grid reference\n * @param {object} param\n * @param {number} param.lat\n * @param {number} param.long\n * @returns {string}\n */\nexport function latLongToOsGridRef({ lat, long }) {\n const point = new LatLon(lat, long)\n\n return point.toOsGrid().toString()\n}\n\n/**\n * Converts an ordnance survey grid reference to lat long\n * @param {string} osGridRef\n * @returns {{ lat: number, long: number }}\n */\nexport function osGridRefToLatLong(osGridRef) {\n const point = OsGridRef.parse(osGridRef)\n const latLong = point.toLatLon()\n\n return { lat: latLong.latitude, long: latLong.longitude }\n}\n\n/**\n * Get the grid ref from the first coordinate of a long/lat feature\n * @param {Feature} feature\n */\nexport function getCoordinateGridRef(feature) {\n if (feature.geometry.type === 'Point') {\n const [long, lat] = feature.geometry.coordinates\n const point = new LatLon(lat, long)\n\n return point.toOsGrid().toString()\n } else if (feature.geometry.type === 'LineString') {\n const [long, lat] = feature.geometry.coordinates[0]\n const point = new LatLon(lat, long)\n\n return point.toOsGrid().toString()\n } else {\n const [long, lat] = feature.geometry.coordinates[0][0]\n const point = new LatLon(lat, long)\n\n return point.toOsGrid().toString()\n }\n}\n\n/**\n * Get the centroid grid ref from a long/lat feature\n * @param {Feature} feature\n */\nexport function getCentroidGridRef(feature) {\n if (feature.geometry.type === 'Point') {\n const [long, lat] = feature.geometry.coordinates\n const point = new LatLon(lat, long)\n\n return point.toOsGrid().toString()\n } else {\n const centre = centroid(feature)\n const [long, lat] = centre.geometry.coordinates\n const point = new LatLon(lat, long)\n\n return point.toOsGrid().toString()\n }\n}\n\n/** @type {InteractiveMapInitConfig} */\nexport const defaultConfig = {\n zoom: '6',\n center: [DEFAULT_LONG, DEFAULT_LAT]\n}\n\nexport const EVENTS = {\n mapReady: 'map:ready',\n interactMarkerChange: 'interact:markerchange',\n drawReady: 'draw:ready',\n drawCreated: 'draw:created',\n drawEdited: 'draw:edited',\n drawCancelled: 'draw:cancelled'\n}\n\n/**\n * Make a form submit handler that only allows submissions from allowed buttons\n * @param {HTMLButtonElement[]} buttons - the form buttons to allow submissions\n */\nexport function formSubmitFactory(buttons) {\n /**\n * The submit handler\n * @param {SubmitEvent} e\n */\n const onFormSubmit = function (e) {\n if (\n !(e.submitter instanceof HTMLButtonElement) ||\n !buttons.includes(e.submitter)\n ) {\n e.preventDefault()\n }\n }\n\n return onFormSubmit\n}\n\n/**\n * Initialise location maps\n * @param {Partial<MapsEnvironmentConfig>} config - the map configuration\n */\nexport function initMaps(config = {}) {\n const {\n assetPath = '/assets',\n apiPath = '/form/api',\n data = defaultData\n } = config\n const locations = document.querySelectorAll('.app-location-field')\n const geospatials = document.querySelectorAll('.app-geospatial-field')\n\n // TODO: Fix this in `interactive-map`\n // If there are location components on the page fix up the main form submit\n // handler so it doesn't fire when using the integrated map search feature\n if (locations.length) {\n const form = locations[0].closest('form')\n\n if (form === null) {\n return\n }\n\n const buttons = Array.from(form.querySelectorAll('button'))\n form.addEventListener('submit', formSubmitFactory(buttons), false)\n }\n\n if (geospatials.length) {\n const form = geospatials[0].closest('form')\n\n if (form === null) {\n return\n }\n\n const buttons = Array.from(form.querySelectorAll('button'))\n form.addEventListener('submit', formSubmitFactory(buttons), false)\n }\n\n locations.forEach((location, index) => {\n processLocation({ assetPath, apiPath, data }, location, index)\n })\n\n geospatials.forEach((geospatial, index) => {\n processGeospatial({ assetPath, apiPath, data }, geospatial, index)\n })\n}\n\n/**\n * OS API request proxy factory\n * @param {string} apiPath - the root API path\n */\nexport function makeTileRequestTransformer(apiPath) {\n /**\n * Proxy OS API requests via our server\n * @param {string} url - the request URL\n * @param {string} resourceType - the resource type\n */\n return function transformTileRequest(url, resourceType) {\n if (url.startsWith('https://api.os.uk')) {\n if (resourceType === 'Tile') {\n return {\n url: url.replace(\n 'https://api.os.uk/maps/vector/v1/vts',\n `${window.location.origin}${apiPath}`\n ),\n headers: {}\n }\n }\n\n if (resourceType !== 'Style') {\n return {\n url: `${apiPath}/map-proxy?url=${encodeURIComponent(url)}`,\n headers: {}\n }\n }\n }\n\n const spritesPath =\n 'https://raw.githubusercontent.com/OrdnanceSurvey/OS-Vector-Tile-API-Stylesheets/main'\n\n // Proxy sprite requests\n if (url.startsWith(spritesPath)) {\n const path = url.substring(spritesPath.length)\n return {\n url: `${apiPath}/maps/vts${path}`,\n headers: {}\n }\n }\n\n return { url, headers: {} }\n }\n}\n\n/**\n * Create a Defra map instance\n * @param {string} mapId - the map id\n * @param {InteractiveMapInitConfig} initConfig - the map initial configuration\n * @param {MapsEnvironmentConfig} mapsConfig - the map environment params\n */\nexport function createMap(mapId, initConfig, mapsConfig) {\n const { assetPath, apiPath, data = defaultData } = mapsConfig\n const logoAltText = 'Ordnance survey logo'\n const interactPlugin = createInteractPlugin({\n markerColor: { outdoor: '#ff0000', dark: '#00ff00' },\n interactionModes: ['placeMarker'],\n multiSelect: false\n })\n\n /** @type {InteractiveMap} */\n const map = new InteractiveMap(mapId, {\n enableFullscreen: true,\n autoColorScheme: false,\n mapProvider: maplibreProvider(),\n behaviour: 'inline',\n minZoom: 6,\n maxZoom: 18,\n containerHeight: '400px',\n enableZoomControls: true,\n transformRequest: makeTileRequestTransformer(apiPath),\n ...initConfig,\n plugins: [\n createMapStylesPlugin({\n mapStyles: [\n {\n id: 'outdoor',\n label: 'Outdoor',\n url: data.VTS_OUTDOOR_URL,\n thumbnail: `${assetPath}/interactive-map/assets/images/outdoor-map-thumb.jpg`,\n logo: `${assetPath}/interactive-map/assets/images/os-logo.svg`,\n logoAltText,\n attribution: `Contains OS data ${String.fromCodePoint(COMPANY_SYMBOL_CODE)} Crown copyright and database rights ${new Date().getFullYear()}`,\n backgroundColor: '#f5f5f0'\n },\n {\n id: 'dark',\n label: 'Dark',\n url: data.VTS_DARK_URL,\n mapColorScheme: 'dark',\n appColorScheme: 'dark',\n thumbnail: `${assetPath}/interactive-map/assets/images/dark-map-thumb.jpg`,\n logo: `${assetPath}/interactive-map/assets/images/os-logo-white.svg`,\n logoAltText,\n attribution: `Contains OS data ${String.fromCodePoint(COMPANY_SYMBOL_CODE)} Crown copyright and database rights ${new Date().getFullYear()}`\n },\n {\n id: 'black-and-white',\n label: 'Black/White',\n url: data.VTS_BLACK_AND_WHITE_URL,\n thumbnail: `${assetPath}/interactive-map/assets/images/black-and-white-map-thumb.jpg`,\n logo: `${assetPath}/interactive-map/assets/images/os-logo-black.svg`,\n logoAltText,\n attribution: `Contains OS data ${String.fromCodePoint(COMPANY_SYMBOL_CODE)} Crown copyright and database rights ${new Date().getFullYear()}`\n },\n {\n id: 'aerial',\n label: 'Aerial',\n url: data.VTS_AERIAL_URL,\n thumbnail: `${assetPath}/interactive-map/assets/images/aerial-map-thumb.jpg`,\n logo: `${assetPath}/interactive-map/assets/images/esri-logo.png`,\n logoAltText: 'Powered by Esri',\n attribution: `Tiles ${String.fromCodePoint(COMPANY_SYMBOL_CODE)} Esri — Source: Esri, Maxar, Earthstar Geographics, and the GIS User Community ${new Date().getFullYear()}`\n }\n ]\n }),\n interactPlugin,\n createSearchPlugin({\n osNamesURL: `${apiPath}/geocode-proxy?query={query}`,\n width: '300px',\n showMarker: false\n }),\n createScaleBarPlugin({\n units: 'metric'\n }),\n ...(initConfig.plugins ?? [])\n ]\n })\n\n return { map, interactPlugin }\n}\n\n/**\n * Updates the marker position and moves the map view port the new location\n * @param {InteractiveMap} map - the map component instance (of InteractiveMap)\n * @param {MapLibreMap} mapProvider - the map provider instance (of MapLibreMap)\n * @param {MapCenter} center - the point\n */\nexport function centerMap(map, mapProvider, center) {\n // Move the 'location' marker to the new point\n map.addMarker('location', center)\n\n // Pan & zoom the map to the new valid location\n mapProvider.flyTo({\n center,\n zoom: 14,\n essential: true\n })\n}\n\n/**\n * Parse CSV string layers\n * @param {string | undefined} layers\n * @returns {string[]}\n */\nexport function getMapLayers(layers) {\n const trimmed = layers?.trim()\n return trimmed ? trimmed.split(',') : []\n}\n\n/**\n * Adds the country layers to a datasets array\n * @param {string} apiPath\n * @param {string} [country]\n */\nexport function getMapCountryLayers(apiPath, country) {\n /** @type {any[]} */\n const datasets = []\n\n if (country) {\n // Add the country bounds to the datasets array to show the valid area on the map\n // and provide feedback to the user when they add features outside of the bounds.\n datasets.push(\n {\n id: 'invalid-area',\n label: 'Invalid areas',\n geojson: `${apiPath}/maps/countries.geojson?omit=${country}`,\n showInKey: false,\n showInMenu: false,\n style: {\n stroke: 'gray',\n strokeWidth: 1,\n fill: 'rgba(211,211,211,0.8)'\n }\n },\n {\n id: 'valid-area',\n label: 'Valid areas',\n geojson: `${apiPath}/maps/countries.geojson?only=${country}`,\n showInKey: false,\n showInMenu: false,\n style: {\n stroke: 'rgba(0,112,60,1)',\n strokeWidth: 1\n }\n }\n )\n }\n\n return datasets\n}\n\n/**\n * @typedef {object} InteractiveMap - an instance of a InteractiveMap\n * @property {Function} on - register callback listeners to map events\n * @property {Function} addPanel - adds a new panel to the map\n * @property {Function} addMarker - adds/updates a marker\n * @property {Function} removeMarker - removes a marker\n * @property {Function} addButton - adds/updates a button\n * @property {Function} toggleButtonState - toggle the state of a button\n */\n\n/**\n * @typedef {object} MapLibreMap\n * @property {Function} flyTo - pans/zooms to a new location\n * @property {Function} fitBounds - fits the my to the new bounds\n */\n\n/**\n * @typedef {[number, number]} MapCenter - Map center point as [long, lat]\n */\n\n/**\n * @typedef {object} InteractiveMapInitConfig - additional config that can be provided to InteractiveMap\n * @property {string} zoom - the zoom level of the map\n * @property {MapCenter} center - the center point of the map\n * @property {{ id: string, coords: MapCenter }[]} [markers] - the markers to add to the map\n * @property {any[]} [plugins] - additional plugins\n */\n\n/**\n * @typedef {object} TileData\n * @property {string} VTS_OUTDOOR_URL - the outdoor tile URL\n * @property {string} VTS_DARK_URL - the dark tile URL\n * @property {string} VTS_BLACK_AND_WHITE_URL - the black and white tile URL\n * @property {string} VTS_AERIAL_URL - the aerial tile URL\n */\n\n/**\n * @typedef {object} MapsEnvironmentConfig\n * @property {string} assetPath - the root asset path\n * @property {string} apiPath - the root API path\n * @property {TileData} data - the tile data config\n */\n\n/**\n * @typedef {object} UIManagerOptions\n * @property {string} [geometryTypes] - the CSV list of geometry types that a user can create\n */\n\n/**\n * @import { Feature } from '~/src/server/plugins/engine/types.js'\n */\n"],"mappings":"AAAA;AACA,OAAOA,cAAc,MAAM,wBAAwB;AACnD;AACA,OAAOC,oB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K,EAAE;QACLC,MAAM,EAAE,MAAM;QACdC,WAAW,EAAE,CAAC;QACdC,IAAI,EAAE;MACR;IACF,CAAC,EACD;MACEnC,EAAE,EAAE,YAAY;MAChBC,KAAK,EAAE,aAAa;MACpB4B,OAAO,EAAE,GAAGjF,OAAO,gCAAgC8E,OAAO,EAAE;MAC5DI,SAAS,EAAE,KAAK;MAChBC,UAAU,EAAE,KAAK;MACjBC,KAAK,EAAE;QACLC,MAAM,EAAE,kBAAkB;QAC1BC,WAAW,EAAE;MACf;IACF,CACF,CAAC;EACH;EAEA,OAAOP,QAAQ;AACjB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"map.js","names":["InteractiveMap","createInteractPlugin","createMapStylesPlugin","createScaleBarPlugin","createSearchPlugin","maplibreProvider","centroid","OsGridRef","LatLon","processGeospatial","processLocation","DEFAULT_LAT","DEFAULT_LONG","COMPANY_SYMBOL_CODE","defaultData","VTS_OUTDOOR_URL","VTS_DARK_URL","VTS_BLACK_AND_WHITE_URL","VTS_AERIAL_URL","latLongToEastingNorthing","lat","long","point","toOsGrid","eastingNorthingToLatLong","easting","northing","latLong","toLatLon","latitude","longitude","latLongToOsGridRef","toString","osGridRefToLatLong","osGridRef","parse","getCoordinateGridRef","feature","geometry","type","coordinates","getCentroidGridRef","centre","defaultConfig","zoom","center","EVENTS","mapReady","interactMarkerChange","drawReady","drawCreated","drawEdited","drawCancelled","formSubmitFactory","buttons","onFormSubmit","e","submitter","HTMLButtonElement","includes","preventDefault","initMaps","config","assetPath","apiPath","data","locations","document","querySelectorAll","geospatials","length","form","closest","Array","from","addEventListener","forEach","location","index","geospatial","makeTileRequestTransformer","transformTileRequest","url","resourceType","startsWith","replace","window","origin","headers","encodeURIComponent","spritesPath","path","substring","createMap","mapId","initConfig","mapsConfig","logoAltText","interactPlugin","markerColor","outdoor","dark","interactionModes","multiSelect","map","enableFullscreen","autoColorScheme","mapProvider","behaviour","minZoom","maxZoom","containerHeight","enableZoomControls","transformRequest","plugins","mapStyles","id","label","thumbnail","logo","attribution","String","fromCodePoint","Date","getFullYear","backgroundColor","mapColorScheme","appColorScheme","osNamesURL","width","showMarker","units","centerMap","addMarker","flyTo","essential","getMapLayers","layers","trimmed","trim","split","getMapCountryLayers","country","datasets","push","geojson","showInKey","showInMenu","style","stroke","strokeWidth","fill"],"sources":["../../../src/client/javascripts/map.js"],"sourcesContent":["// @ts-expect-error - no types\nimport InteractiveMap from '@defra/interactive-map'\n// @ts-expect-error - no types\nimport createInteractPlugin from '@defra/interactive-map/plugins/interact'\n// @ts-expect-error - no types\nimport createMapStylesPlugin from '@defra/interactive-map/plugins/map-styles'\n// @ts-expect-error - no types\nimport createScaleBarPlugin from '@defra/interactive-map/plugins/scale-bar'\n// @ts-expect-error - no types\nimport createSearchPlugin from '@defra/interactive-map/plugins/search'\n// @ts-expect-error - no types\nimport maplibreProvider from '@defra/interactive-map/providers/maplibre'\nimport { centroid } from '@turf/centroid'\n// @ts-expect-error - no types\nimport OsGridRef, { LatLon } from 'geodesy/osgridref.js'\n\nimport { processGeospatial } from '~/src/client/javascripts/geospatial-map.js'\nimport { processLocation } from '~/src/client/javascripts/location-map.js'\n\n// Center of UK\nconst DEFAULT_LAT = 53.825564\nconst DEFAULT_LONG = -2.421975\nconst COMPANY_SYMBOL_CODE = 169\n\nconst defaultData = {\n VTS_OUTDOOR_URL: '/api/maps/vts/OS_VTS_3857_Outdoor.json',\n VTS_DARK_URL: '/api/maps/vts/OS_VTS_3857_Dark.json',\n VTS_BLACK_AND_WHITE_URL: '/api/maps/vts/OS_VTS_3857_Black_and_White.json',\n VTS_AERIAL_URL: '/api/maps/vts/esri-aerial.json'\n}\n\n/**\n * Converts lat long to easting and northing\n * @param {object} param\n * @param {number} param.lat\n * @param {number} param.long\n * @returns {{ easting: number, northing: number }}\n */\nexport function latLongToEastingNorthing({ lat, long }) {\n const point = new LatLon(lat, long)\n\n return point.toOsGrid()\n}\n\n/**\n * Converts easting and northing to lat long\n * @param {object} param\n * @param {number} param.easting\n * @param {number} param.northing\n * @returns {{ lat: number, long: number }}\n */\nexport function eastingNorthingToLatLong({ easting, northing }) {\n const point = new OsGridRef(easting, northing)\n const latLong = point.toLatLon()\n\n return { lat: latLong.latitude, long: latLong.longitude }\n}\n\n/**\n * Converts lat long to an ordnance survey grid reference\n * @param {object} param\n * @param {number} param.lat\n * @param {number} param.long\n * @returns {string}\n */\nexport function latLongToOsGridRef({ lat, long }) {\n const point = new LatLon(lat, long)\n\n return point.toOsGrid().toString()\n}\n\n/**\n * Converts an ordnance survey grid reference to lat long\n * @param {string} osGridRef\n * @returns {{ lat: number, long: number }}\n */\nexport function osGridRefToLatLong(osGridRef) {\n const point = OsGridRef.parse(osGridRef)\n const latLong = point.toLatLon()\n\n return { lat: latLong.latitude, long: latLong.longitude }\n}\n\n/**\n * Get the grid ref from the first coordinate of a long/lat feature\n * @param {Feature} feature\n */\nexport function getCoordinateGridRef(feature) {\n if (feature.geometry.type === 'Point') {\n const [long, lat] = feature.geometry.coordinates\n const point = new LatLon(lat, long)\n\n return point.toOsGrid().toString()\n } else if (feature.geometry.type === 'LineString') {\n const [long, lat] = feature.geometry.coordinates[0]\n const point = new LatLon(lat, long)\n\n return point.toOsGrid().toString()\n } else {\n const [long, lat] = feature.geometry.coordinates[0][0]\n const point = new LatLon(lat, long)\n\n return point.toOsGrid().toString()\n }\n}\n\n/**\n * Get the centroid grid ref from a long/lat feature\n * @param {Feature} feature\n */\nexport function getCentroidGridRef(feature) {\n if (feature.geometry.type === 'Point') {\n const [long, lat] = feature.geometry.coordinates\n const point = new LatLon(lat, long)\n\n return point.toOsGrid().toString()\n } else {\n const centre = centroid(feature)\n const [long, lat] = centre.geometry.coordinates\n const point = new LatLon(lat, long)\n\n return point.toOsGrid().toString()\n }\n}\n\n/** @type {InteractiveMapInitConfig} */\nexport const defaultConfig = {\n zoom: '6',\n center: [DEFAULT_LONG, DEFAULT_LAT]\n}\n\nexport const EVENTS = {\n mapReady: 'map:ready',\n interactMarkerChange: 'interact:markerchange',\n drawReady: 'draw:ready',\n drawCreated: 'draw:created',\n drawEdited: 'draw:edited',\n drawCancelled: 'draw:cancelled'\n}\n\n/**\n * Make a form submit handler that only allows submissions from allowed buttons\n * @param {HTMLButtonElement[]} buttons - the form buttons to allow submissions\n */\nexport function formSubmitFactory(buttons) {\n /**\n * The submit handler\n * @param {SubmitEvent} e\n */\n const onFormSubmit = function (e) {\n if (\n !(e.submitter instanceof HTMLButtonElement) ||\n !buttons.includes(e.submitter)\n ) {\n e.preventDefault()\n }\n }\n\n return onFormSubmit\n}\n\n/**\n * Initialise location maps\n * @param {Partial<MapsEnvironmentConfig>} config - the map configuration\n */\nexport function initMaps(config = {}) {\n const {\n assetPath = '/assets',\n apiPath = '/form/api',\n data = defaultData\n } = config\n const locations = document.querySelectorAll('.app-location-field')\n const geospatials = document.querySelectorAll('.app-geospatial-field')\n\n // TODO: Fix this in `interactive-map`\n // If there are location components on the page fix up the main form submit\n // handler so it doesn't fire when using the integrated map search feature\n if (locations.length) {\n const form = locations[0].closest('form')\n\n if (form === null) {\n return\n }\n\n const buttons = Array.from(form.querySelectorAll('button'))\n form.addEventListener('submit', formSubmitFactory(buttons), false)\n }\n\n if (geospatials.length) {\n const form = geospatials[0].closest('form')\n\n if (form === null) {\n return\n }\n\n const buttons = Array.from(form.querySelectorAll('button'))\n form.addEventListener('submit', formSubmitFactory(buttons), false)\n }\n\n locations.forEach((location, index) => {\n processLocation({ assetPath, apiPath, data }, location, index)\n })\n\n geospatials.forEach((geospatial, index) => {\n processGeospatial({ assetPath, apiPath, data }, geospatial, index)\n })\n}\n\n/**\n * OS API request proxy factory\n * @param {string} apiPath - the root API path\n */\nexport function makeTileRequestTransformer(apiPath) {\n /**\n * Proxy OS API requests via our server\n * @param {string} url - the request URL\n * @param {string} resourceType - the resource type\n */\n return function transformTileRequest(url, resourceType) {\n if (url.startsWith('https://api.os.uk')) {\n if (resourceType === 'Tile') {\n return {\n url: url.replace(\n 'https://api.os.uk/maps/vector/v1/vts',\n `${window.location.origin}${apiPath}`\n ),\n headers: {}\n }\n }\n\n if (resourceType !== 'Style') {\n return {\n url: `${apiPath}/map-proxy?url=${encodeURIComponent(url)}`,\n headers: {}\n }\n }\n }\n\n const spritesPath =\n 'https://raw.githubusercontent.com/OrdnanceSurvey/OS-Vector-Tile-API-Stylesheets/main'\n\n // Proxy sprite requests\n if (url.startsWith(spritesPath)) {\n const path = url.substring(spritesPath.length)\n return {\n url: `${apiPath}/maps/vts${path}`,\n headers: {}\n }\n }\n\n return { url, headers: {} }\n }\n}\n\n/**\n * Create a Defra map instance\n * @param {string} mapId - the map id\n * @param {InteractiveMapInitConfig} initConfig - the map initial configuration\n * @param {MapsEnvironmentConfig} mapsConfig - the map environment params\n */\nexport function createMap(mapId, initConfig, mapsConfig) {\n const { assetPath, apiPath, data = defaultData } = mapsConfig\n const logoAltText = 'Ordnance survey logo'\n const interactPlugin = createInteractPlugin({\n markerColor: { outdoor: '#ff0000', dark: '#00ff00' },\n interactionModes: ['placeMarker'],\n multiSelect: false\n })\n\n /** @type {InteractiveMap} */\n const map = new InteractiveMap(mapId, {\n enableFullscreen: true,\n autoColorScheme: false,\n mapProvider: maplibreProvider(),\n behaviour: 'inline',\n minZoom: 6,\n maxZoom: 18,\n containerHeight: '400px',\n enableZoomControls: true,\n transformRequest: makeTileRequestTransformer(apiPath),\n ...initConfig,\n plugins: [\n createMapStylesPlugin({\n mapStyles: [\n {\n id: 'outdoor',\n label: 'Outdoor',\n url: data.VTS_OUTDOOR_URL,\n thumbnail: `${assetPath}/interactive-map/assets/images/outdoor-map-thumb.jpg`,\n logo: `${assetPath}/interactive-map/assets/images/os-logo.svg`,\n logoAltText,\n attribution: `Contains OS data ${String.fromCodePoint(COMPANY_SYMBOL_CODE)} Crown copyright and database rights ${new Date().getFullYear()}`,\n backgroundColor: '#f5f5f0'\n },\n {\n id: 'dark',\n label: 'Dark',\n url: data.VTS_DARK_URL,\n mapColorScheme: 'dark',\n appColorScheme: 'dark',\n thumbnail: `${assetPath}/interactive-map/assets/images/dark-map-thumb.jpg`,\n logo: `${assetPath}/interactive-map/assets/images/os-logo-white.svg`,\n logoAltText,\n attribution: `Contains OS data ${String.fromCodePoint(COMPANY_SYMBOL_CODE)} Crown copyright and database rights ${new Date().getFullYear()}`\n },\n {\n id: 'black-and-white',\n label: 'Black/White',\n url: data.VTS_BLACK_AND_WHITE_URL,\n thumbnail: `${assetPath}/interactive-map/assets/images/black-and-white-map-thumb.jpg`,\n logo: `${assetPath}/interactive-map/assets/images/os-logo-black.svg`,\n logoAltText,\n attribution: `Contains OS data ${String.fromCodePoint(COMPANY_SYMBOL_CODE)} Crown copyright and database rights ${new Date().getFullYear()}`\n },\n {\n id: 'aerial',\n label: 'Aerial',\n url: data.VTS_AERIAL_URL,\n thumbnail: `${assetPath}/interactive-map/assets/images/aerial-map-thumb.jpg`,\n logo: `${assetPath}/interactive-map/assets/images/esri-logo.png`,\n logoAltText: 'Powered by Esri',\n attribution: `Tiles ${String.fromCodePoint(COMPANY_SYMBOL_CODE)} Esri — Source: Esri, Maxar, Earthstar Geographics, and the GIS User Community ${new Date().getFullYear()}`\n }\n ]\n }),\n interactPlugin,\n createSearchPlugin({\n osNamesURL: `${apiPath}/geocode-proxy?query={query}`,\n width: '300px',\n showMarker: false\n }),\n createScaleBarPlugin({\n units: 'metric'\n }),\n ...(initConfig.plugins ?? [])\n ]\n })\n\n return { map, interactPlugin }\n}\n\n/**\n * Updates the marker position and moves the map view port the new location\n * @param {InteractiveMap} map - the map component instance (of InteractiveMap)\n * @param {MapLibreMap} mapProvider - the map provider instance (of MapLibreMap)\n * @param {MapCenter} center - the point\n */\nexport function centerMap(map, mapProvider, center) {\n // Move the 'location' marker to the new point\n map.addMarker('location', center)\n\n // Pan & zoom the map to the new valid location\n mapProvider.flyTo({\n center,\n zoom: 14,\n essential: true\n })\n}\n\n/**\n * Parse CSV string layers\n * @param {string | undefined} layers\n * @returns {string[]}\n */\nexport function getMapLayers(layers) {\n const trimmed = layers?.trim()\n return trimmed ? trimmed.split(',') : []\n}\n\n/**\n * Adds the country layers to a datasets array\n * @param {string} apiPath\n * @param {string} [country]\n */\nexport function getMapCountryLayers(apiPath, country) {\n /** @type {any[]} */\n const datasets = []\n\n if (country) {\n // Add the country bounds to the datasets array to show the valid area on the map\n // and provide feedback to the user when they add features outside of the bounds.\n datasets.push(\n {\n id: 'invalid-area',\n label: 'Invalid areas',\n geojson: `${apiPath}/maps/countries.geojson?omit=${country}`,\n showInKey: false,\n showInMenu: false,\n style: {\n stroke: 'gray',\n strokeWidth: 1,\n fill: 'rgba(211,211,211,0.8)'\n }\n },\n {\n id: 'valid-area',\n label: 'Valid areas',\n geojson: `${apiPath}/maps/countries.geojson?only=${country}`,\n showInKey: false,\n showInMenu: false,\n style: {\n stroke: 'rgba(0,112,60,1)',\n strokeWidth: 1\n }\n }\n )\n }\n\n return datasets\n}\n\n/**\n * @typedef {object} InteractiveMap - an instance of a InteractiveMap\n * @property {Function} on - register callback listeners to map events\n * @property {Function} addPanel - adds a new panel to the map\n * @property {Function} addMarker - adds/updates a marker\n * @property {Function} removeMarker - removes a marker\n * @property {Function} addButton - adds/updates a button\n * @property {Function} toggleButtonState - toggle the state of a button\n */\n\n/**\n * @typedef {object} MapLibreMap\n * @property {Function} flyTo - pans/zooms to a new location\n * @property {Function} fitBounds - fits the my to the new bounds\n */\n\n/**\n * @typedef {[number, number]} MapCenter - Map center point as [long, lat]\n */\n\n/**\n * @typedef {object} InteractiveMapInitConfig - additional config that can be provided to InteractiveMap\n * @property {string} zoom - the zoom level of the map\n * @property {MapCenter} center - the center point of the map\n * @property {{ id: string, coords: MapCenter }[]} [markers] - the markers to add to the map\n * @property {any[]} [plugins] - additional plugins\n */\n\n/**\n * @typedef {object} TileData\n * @property {string} VTS_OUTDOOR_URL - the outdoor tile URL\n * @property {string} VTS_DARK_URL - the dark tile URL\n * @property {string} VTS_BLACK_AND_WHITE_URL - the black and white tile URL\n * @property {string} VTS_AERIAL_URL - the aerial tile URL\n */\n\n/**\n * @typedef {object} MapsEnvironmentConfig\n * @property {string} assetPath - the root asset path\n * @property {string} apiPath - the root API path\n * @property {TileData} data - the tile data config\n */\n\n/**\n * @typedef {object} UIManagerOptions\n * @property {string} [geometryTypes] - the CSV list of geometry types that a user can create\n */\n\n/**\n * @import { Feature } from '~/src/server/plugins/engine/types.js'\n */\n\n/**\n * Supported language codes\n * @typedef {('en-GB'|'cy')} LanguageCode\n */\n"],"mappings":"AAAA;AACA,OAAOA,cAAc,MAAM,wBAAwB;AACnD;AACA,OAAOC,oBAAoB,MAAM,yCAAyC;AAC1E;AACA,OAAOC,qBAAqB,MAAM,2CAA2C;AAC7E;AACA,OAAOC,oBAAoB,MAAM,0CAA0C;AAC3E;AACA,OAAOC,kBAAkB,MAAM,uCAAuC;AACtE;AACA,OAAOC,gBAAgB,MAAM,2CAA2C;AACxE,SAASC,QAAQ,QAAQ,gBAAgB;AACzC;AACA,OAAOC,SAAS,IAAIC,MAAM,QAAQ,sBAAsB;AAExD,SAASC,iBAAiB;AAC1B,SAASC,eAAe;;AAExB;AACA,MAAMC,WAAW,GAAG,SAAS;AAC7B,MAAMC,YAAY,GAAG,CAAC,QAAQ;AAC9B,MAAMC,mBAAmB,GAAG,GAAG;AAE/B,MAAMC,WAAW,GAAG;EAClBC,eAAe,EAAE,wCAAwC;EACzDC,YAAY,EAAE,qCAAqC;EACnDC,uBAAuB,EAAE,gDAAgD;EACzEC,cAAc,EAAE;AAClB,CAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,wBAAwBA,CAAC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
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { type FormDefinition } from '@defra/forms-model';
|
|
2
|
+
/**
|
|
3
|
+
* A minimal, schema-valid V2 definition: one YesNo question page and a
|
|
4
|
+
* summary page. Each call returns a fresh object, so tests can mutate their
|
|
5
|
+
* copy freely without affecting each other.
|
|
6
|
+
*/
|
|
7
|
+
export declare function buildDefinition(): FormDefinition;
|
|
8
|
+
/**
|
|
9
|
+
* A definition that passes schema validation but cannot be used by the
|
|
10
|
+
* engine: a ListItemRef condition points at the YesNoField (boolean), so the
|
|
11
|
+
* condition expression builder produces an unparseable expression. Distilled
|
|
12
|
+
* from a real production incident.
|
|
13
|
+
*/
|
|
14
|
+
export declare function buildBrokenConditionDefinition(): FormDefinition;
|
|
15
|
+
/**
|
|
16
|
+
* A schema-valid definition whose first page names a controller that is
|
|
17
|
+
* neither built in nor registered by the host application.
|
|
18
|
+
*/
|
|
19
|
+
export declare function buildUnknownControllerDefinition(): FormDefinition;
|
|
20
|
+
/**
|
|
21
|
+
* Schema-valid (component types are free strings in the schema), but the
|
|
22
|
+
* question uses a type the engine has no component class for.
|
|
23
|
+
*/
|
|
24
|
+
export declare function buildUnknownComponentDefinition(): FormDefinition;
|
|
25
|
+
/**
|
|
26
|
+
* A definition that fails schema validation: the question page appears
|
|
27
|
+
* twice, violating the pages uniqueness rule.
|
|
28
|
+
*/
|
|
29
|
+
export declare function buildSchemaInvalidDefinition(): FormDefinition;
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { ComponentType, ConditionType, ControllerType, Engine, OperatorName, SchemaVersion } from '@defra/forms-model';
|
|
2
|
+
const YES_NO_COMPONENT_ID = 'a7c0242f-2a31-45b2-8c71-ff2ac7f53288';
|
|
3
|
+
const USER_TYPE_LIST_ID = '4fa26e9c-07cf-47cd-a9dd-5cec0dd3f544';
|
|
4
|
+
const EXISTING_USER_ITEM_ID = '55fe0067-d011-4d33-886c-e1aa266637c3';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* A minimal, schema-valid V2 definition: one YesNo question page and a
|
|
8
|
+
* summary page. Each call returns a fresh object, so tests can mutate their
|
|
9
|
+
* copy freely without affecting each other.
|
|
10
|
+
*/
|
|
11
|
+
export function buildDefinition() {
|
|
12
|
+
return {
|
|
13
|
+
name: 'Stub definition',
|
|
14
|
+
engine: Engine.V2,
|
|
15
|
+
schema: SchemaVersion.V2,
|
|
16
|
+
startPage: '/summary',
|
|
17
|
+
pages: [{
|
|
18
|
+
id: '449c053b-9201-4312-9a75-187afc6ba48b',
|
|
19
|
+
path: '/licence',
|
|
20
|
+
title: 'Licence',
|
|
21
|
+
components: [{
|
|
22
|
+
id: YES_NO_COMPONENT_ID,
|
|
23
|
+
name: 'xVrYaJ',
|
|
24
|
+
type: ComponentType.YesNoField,
|
|
25
|
+
title: 'Do you have a licence?',
|
|
26
|
+
shortDescription: 'Licence',
|
|
27
|
+
options: {
|
|
28
|
+
required: true
|
|
29
|
+
}
|
|
30
|
+
}],
|
|
31
|
+
next: []
|
|
32
|
+
}, {
|
|
33
|
+
id: '449c053b-9201-4312-9a75-187afc6ba48c',
|
|
34
|
+
path: '/summary',
|
|
35
|
+
title: 'Summary',
|
|
36
|
+
controller: ControllerType.Summary,
|
|
37
|
+
components: []
|
|
38
|
+
}],
|
|
39
|
+
lists: [],
|
|
40
|
+
sections: [],
|
|
41
|
+
conditions: []
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* A definition that passes schema validation but cannot be used by the
|
|
47
|
+
* engine: a ListItemRef condition points at the YesNoField (boolean), so the
|
|
48
|
+
* condition expression builder produces an unparseable expression. Distilled
|
|
49
|
+
* from a real production incident.
|
|
50
|
+
*/
|
|
51
|
+
export function buildBrokenConditionDefinition() {
|
|
52
|
+
const definition = buildDefinition();
|
|
53
|
+
definition.name = 'Broken condition fixture';
|
|
54
|
+
const questionPage = definition.pages[0]
|
|
55
|
+
// A YesNoField cannot legitimately carry a custom list — that is the
|
|
56
|
+
// corruption this fixture models — so the TS component types (rightly)
|
|
57
|
+
// have no `list` property here and a cast is required.
|
|
58
|
+
;
|
|
59
|
+
questionPage.components[0].list = USER_TYPE_LIST_ID;
|
|
60
|
+
definition.lists = [{
|
|
61
|
+
id: USER_TYPE_LIST_ID,
|
|
62
|
+
name: 'XtfRYR',
|
|
63
|
+
title: 'User type list',
|
|
64
|
+
type: 'string',
|
|
65
|
+
items: [{
|
|
66
|
+
id: EXISTING_USER_ITEM_ID,
|
|
67
|
+
text: 'existing user',
|
|
68
|
+
value: 'existing user'
|
|
69
|
+
}, {
|
|
70
|
+
id: '2277c7e5-7fef-46c6-993b-d294116d6d6b',
|
|
71
|
+
text: 'new user',
|
|
72
|
+
value: 'new user'
|
|
73
|
+
}]
|
|
74
|
+
}];
|
|
75
|
+
definition.conditions = [{
|
|
76
|
+
id: '3f9d3a35-6dee-4706-806c-3f776129f631',
|
|
77
|
+
displayName: 'Existing user',
|
|
78
|
+
items: [{
|
|
79
|
+
id: '7d7f58ee-c860-4d24-8a13-de5cb9af53d8',
|
|
80
|
+
componentId: YES_NO_COMPONENT_ID,
|
|
81
|
+
operator: OperatorName.Is,
|
|
82
|
+
type: ConditionType.ListItemRef,
|
|
83
|
+
value: {
|
|
84
|
+
listId: USER_TYPE_LIST_ID,
|
|
85
|
+
itemId: [EXISTING_USER_ITEM_ID]
|
|
86
|
+
}
|
|
87
|
+
}]
|
|
88
|
+
}];
|
|
89
|
+
return definition;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* A schema-valid definition whose first page names a controller that is
|
|
94
|
+
* neither built in nor registered by the host application.
|
|
95
|
+
*/
|
|
96
|
+
export function buildUnknownControllerDefinition() {
|
|
97
|
+
const definition = buildDefinition();
|
|
98
|
+
definition.name = 'Unknown controller fixture';
|
|
99
|
+
definition.pages[0].controller = 'NoSuchPageController';
|
|
100
|
+
return definition;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Schema-valid (component types are free strings in the schema), but the
|
|
105
|
+
* question uses a type the engine has no component class for.
|
|
106
|
+
*/
|
|
107
|
+
export function buildUnknownComponentDefinition() {
|
|
108
|
+
const definition = buildDefinition();
|
|
109
|
+
definition.name = 'Unknown component fixture';
|
|
110
|
+
const questionPage = definition.pages[0];
|
|
111
|
+
questionPage.components[0].type = 'MyUnknownField';
|
|
112
|
+
return definition;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* A definition that fails schema validation: the question page appears
|
|
117
|
+
* twice, violating the pages uniqueness rule.
|
|
118
|
+
*/
|
|
119
|
+
export function buildSchemaInvalidDefinition() {
|
|
120
|
+
const definition = buildDefinition();
|
|
121
|
+
definition.name = 'Schema invalid fixture';
|
|
122
|
+
definition.pages.push(buildDefinition().pages[0]);
|
|
123
|
+
return definition;
|
|
124
|
+
}
|
|
125
|
+
//# sourceMappingURL=definitions.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"definitions.js","names":["ComponentType","ConditionType","ControllerType","Engine","OperatorName","SchemaVersion","YES_NO_COMPONENT_ID","USER_TYPE_LIST_ID","EXISTING_USER_ITEM_ID","buildDefinition","name","engine","V2","schema","startPage","pages","id","path","title","components","type","YesNoField","shortDescription","options","required","next","controller","Summary","lists","sections","conditions","buildBrokenConditionDefinition","definition","questionPage","list","items","text","value","displayName","componentId","operator","Is","ListItemRef","listId","itemId","buildUnknownControllerDefinition","buildUnknownComponentDefinition","buildSchemaInvalidDefinition","push"],"sources":["../../../../../src/server/plugins/engine/__stubs__/definitions.ts"],"sourcesContent":["import {\n ComponentType,\n ConditionType,\n ControllerType,\n Engine,\n OperatorName,\n SchemaVersion,\n type FormDefinition,\n type PageQuestion\n} from '@defra/forms-model'\n\nconst YES_NO_COMPONENT_ID = 'a7c0242f-2a31-45b2-8c71-ff2ac7f53288'\nconst USER_TYPE_LIST_ID = '4fa26e9c-07cf-47cd-a9dd-5cec0dd3f544'\nconst EXISTING_USER_ITEM_ID = '55fe0067-d011-4d33-886c-e1aa266637c3'\n\n/**\n * A minimal, schema-valid V2 definition: one YesNo question page and a\n * summary page. Each call returns a fresh object, so tests can mutate their\n * copy freely without affecting each other.\n */\nexport function buildDefinition(): FormDefinition {\n return {\n name: 'Stub definition',\n engine: Engine.V2,\n schema: SchemaVersion.V2,\n startPage: '/summary',\n pages: [\n {\n id: '449c053b-9201-4312-9a75-187afc6ba48b',\n path: '/licence',\n title: 'Licence',\n components: [\n {\n id: YES_NO_COMPONENT_ID,\n name: 'xVrYaJ',\n type: ComponentType.YesNoField,\n title: 'Do you have a licence?',\n shortDescription: 'Licence',\n options: { required: true }\n }\n ],\n next: []\n },\n {\n id: '449c053b-9201-4312-9a75-187afc6ba48c',\n path: '/summary',\n title: 'Summary',\n controller: ControllerType.Summary,\n components: []\n }\n ],\n lists: [],\n sections: [],\n conditions: []\n }\n}\n\n/**\n * A definition that passes schema validation but cannot be used by the\n * engine: a ListItemRef condition points at the YesNoField (boolean), so the\n * condition expression builder produces an unparseable expression. Distilled\n * from a real production incident.\n */\nexport function buildBrokenConditionDefinition(): FormDefinition {\n const definition = buildDefinition()\n\n definition.name = 'Broken condition fixture'\n\n const questionPage = definition.pages[0] as PageQuestion\n // A YesNoField cannot legitimately carry a custom list — that is the\n // corruption this fixture models — so the TS component types (rightly)\n // have no `list` property here and a cast is required.\n ;(questionPage.components[0] as { list?: string }).list = USER_TYPE_LIST_ID\n definition.lists = [\n {\n id: USER_TYPE_LIST_ID,\n name: 'XtfRYR',\n title: 'User type list',\n type: 'string',\n items: [\n {\n id: EXISTING_USER_ITEM_ID,\n text: 'existing user',\n value: 'existing user'\n },\n {\n id: '2277c7e5-7fef-46c6-993b-d294116d6d6b',\n text: 'new user',\n value: 'new user'\n }\n ]\n }\n ]\n definition.conditions = [\n {\n id: '3f9d3a35-6dee-4706-806c-3f776129f631',\n displayName: 'Existing user',\n items: [\n {\n id: '7d7f58ee-c860-4d24-8a13-de5cb9af53d8',\n componentId: YES_NO_COMPONENT_ID,\n operator: OperatorName.Is,\n type: ConditionType.ListItemRef,\n value: {\n listId: USER_TYPE_LIST_ID,\n itemId: [EXISTING_USER_ITEM_ID]\n }\n }\n ]\n }\n ]\n\n return definition\n}\n\n/**\n * A schema-valid definition whose first page names a controller that is\n * neither built in nor registered by the host application.\n */\nexport function buildUnknownControllerDefinition(): FormDefinition {\n const definition = buildDefinition()\n\n definition.name = 'Unknown controller fixture'\n definition.pages[0].controller =\n 'NoSuchPageController' as unknown as ControllerType\n\n return definition\n}\n\n/**\n * Schema-valid (component types are free strings in the schema), but the\n * question uses a type the engine has no component class for.\n */\nexport function buildUnknownComponentDefinition(): FormDefinition {\n const definition = buildDefinition()\n\n definition.name = 'Unknown component fixture'\n const questionPage = definition.pages[0] as PageQuestion\n questionPage.components[0].type = 'MyUnknownField' as unknown as ComponentType\n\n return definition\n}\n\n/**\n * A definition that fails schema validation: the question page appears\n * twice, violating the pages uniqueness rule.\n */\nexport function buildSchemaInvalidDefinition(): FormDefinition {\n const definition = buildDefinition()\n\n definition.name = 'Schema invalid fixture'\n definition.pages.push(buildDefinition().pages[0])\n\n return definition\n}\n"],"mappings":"AAAA,SACEA,aAAa,EACbC,aAAa,EACbC,cAAc,EACdC,MAAM,EACNC,YAAY,EACZC,aAAa,QAGR,oBAAoB;AAE3B,MAAMC,mBAAmB,GAAG,sCAAsC;AAClE,MAAMC,iBAAiB,GAAG,sCAAsC;AAChE,MAAMC,qBAAqB,GAAG,sCAAsC;;AAEpE;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,eAAeA,CAAA,EAAmB;EAChD,OAAO;IACLC,IAAI,EAAE,iBAAiB;IACvBC,MAAM,EAAER,MAAM,CAACS,EAAE;IACjBC,MAAM,EAAER,aAAa,CAACO,EAAE;IACxBE,SAAS,EAAE,UAAU;IACrBC,KAAK,EAAE,CACL;MACEC,EAAE,EAAE,sCAAsC;MAC1CC,IAAI,EA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,UAAU;AACnB","ignoreList":[]}
|
|
@@ -24,6 +24,7 @@ export declare class EastingNorthingField extends FormComponent {
|
|
|
24
24
|
items: import("../../../../server/plugins/engine/components/types.js").DateInputItem[];
|
|
25
25
|
mapLayers: string;
|
|
26
26
|
country: import("@defra/forms-model").GeospatialFieldOptionsCountry | undefined;
|
|
27
|
+
lang: string;
|
|
27
28
|
label: import("../../../../server/plugins/engine/components/types.js").Label;
|
|
28
29
|
type?: string;
|
|
29
30
|
id: string;
|
|
@@ -76,6 +77,7 @@ export declare class EastingNorthingField extends FormComponent {
|
|
|
76
77
|
items: import("../../../../server/plugins/engine/components/types.js").DateInputItem[];
|
|
77
78
|
mapLayers: string;
|
|
78
79
|
country: import("@defra/forms-model").GeospatialFieldOptionsCountry | undefined;
|
|
80
|
+
lang: string;
|
|
79
81
|
label: import("../../../../server/plugins/engine/components/types.js").Label;
|
|
80
82
|
type?: string;
|
|
81
83
|
id: string;
|
|
@@ -22,6 +22,7 @@ export declare class GeospatialField extends FormComponent {
|
|
|
22
22
|
getContextValueFromFormValue(features: GeospatialState | undefined): string[] | null;
|
|
23
23
|
getContextValueFromState(state: FormSubmissionState): string[] | null;
|
|
24
24
|
getViewModel(context: RenderContext): {
|
|
25
|
+
lang: string;
|
|
25
26
|
country: import("@defra/forms-model").GeospatialFieldOptionsCountry | undefined;
|
|
26
27
|
geometryTypes: import("@defra/forms-model").GeospatialFieldGeometryTypesEnum[] | undefined;
|
|
27
28
|
mapLayers: string;
|
|
@@ -57,6 +57,7 @@ export class GeospatialField extends FormComponent {
|
|
|
57
57
|
const value = typeof viewModel.value === 'string' ? viewModel.value : JSON.stringify(viewModel.value, null, 2);
|
|
58
58
|
return {
|
|
59
59
|
...viewModel,
|
|
60
|
+
lang: context.translator.language,
|
|
60
61
|
country: this.options.countries?.at(0),
|
|
61
62
|
geometryTypes: this.options.geometryTypes,
|
|
62
63
|
mapLayers: getMapLayers(this),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"GeospatialField.js","names":["EN_GB","FormComponent","isGeospatialState","getMapLayers","determineLimits","getGeospatialSchema","t","tPlugin","messageTemplate","GeospatialField","constructor","def","props","options","formSchema","label","isOptional","required","limits","messages","buildErrorMessages","stateSchema","default","allow","getFormValueFromState","state","name","getFormValue","value","isValue","undefined","getDisplayStringFromFormValue","features","translator","length","count","getDisplayStringFromState","getContextValueFromFormValue","map","id","getContextValueFromState","getViewModel","context","viewModel","JSON","stringify","country","countries","at","geometryTypes","mapLayers","getErrors","errors","fieldErrors","forEach","err","href","path","text","Number","getViewErrors","getValidationMessagesOverride","language","getAllPossibleErrors","staticErrors","advancedSettingsErrors","baseErrors","type","template","selectRequired","format","min","max"],"sources":["../../../../../src/server/plugins/engine/components/GeospatialField.ts"],"sourcesContent":["import { type GeospatialFieldComponent } from '@defra/forms-model'\nimport { type ArraySchema } from 'joi'\n\nimport { EN_GB } from '~/src/server/constants.js'\nimport { type ComponentBase } from '~/src/server/plugins/engine/components/ComponentBase.js'\nimport {\n FormComponent,\n isGeospatialState\n} from '~/src/server/plugins/engine/components/FormComponent.js'\nimport { getMapLayers } from '~/src/server/plugins/engine/components/LocationFieldHelpers.js'\nimport {\n determineLimits,\n getGeospatialSchema\n} from '~/src/server/plugins/engine/components/helpers/geospatial.js'\nimport { type RenderContext } from '~/src/server/plugins/engine/components/types.js'\nimport { t as tPlugin } from '~/src/server/plugins/engine/i18n/index.js'\nimport { type Translator } from '~/src/server/plugins/engine/i18n/types.js'\nimport { messageTemplate } from '~/src/server/plugins/engine/pageControllers/validationOptions.js'\nimport {\n type ErrorMessageTemplateList,\n type FormState,\n type FormStateValue,\n type FormSubmissionError,\n type FormSubmissionState,\n type GeospatialState\n} from '~/src/server/plugins/engine/types.js'\n\nexport class GeospatialField extends FormComponent {\n declare options: GeospatialFieldComponent['options']\n declare formSchema: ArraySchema<GeospatialState>\n declare stateSchema: ArraySchema<GeospatialState>\n declare limits: { min?: number; max?: number; length?: number }\n\n constructor(\n def: GeospatialFieldComponent,\n props: ConstructorParameters<typeof ComponentBase>[1]\n ) {\n super(def, props)\n\n const { options } = def\n\n let formSchema = getGeospatialSchema(def).label(this.label)\n\n const isOptional = options.required === false\n const limits = determineLimits(def, isOptional)\n\n formSchema = formSchema.messages(\n GeospatialField.buildErrorMessages(EN_GB, limits)\n )\n\n this.formSchema = formSchema\n this.stateSchema = formSchema.default(null)\n\n if (isOptional) {\n this.stateSchema = this.stateSchema.allow(null)\n }\n\n this.options = options\n this.limits = limits\n }\n\n getFormValueFromState(state: FormSubmissionState) {\n const { name } = this\n return this.getFormValue(state[name])\n }\n\n getFormValue(value?: FormStateValue | FormState) {\n return this.isValue(value) ? value : undefined\n }\n\n getDisplayStringFromFormValue(\n features: GeospatialState | undefined,\n translator: Translator\n ): string {\n if (!features?.length) {\n return ''\n }\n\n return translator.t('components.geospatialField.added', {\n count: features.length\n })\n }\n\n getDisplayStringFromState(\n state: FormSubmissionState,\n translator: Translator\n ) {\n const features = this.getFormValueFromState(state)\n\n return this.getDisplayStringFromFormValue(features, translator)\n }\n\n getContextValueFromFormValue(\n features: GeospatialState | undefined\n ): string[] | null {\n return features?.map(({ id }) => id) ?? null\n }\n\n getContextValueFromState(state: FormSubmissionState) {\n const features = this.getFormValueFromState(state)\n\n return this.getContextValueFromFormValue(features)\n }\n\n getViewModel(context: RenderContext) {\n const viewModel = super.getViewModel(context)\n const value =\n typeof viewModel.value === 'string'\n ? viewModel.value\n : JSON.stringify(viewModel.value, null, 2)\n\n return {\n ...viewModel,\n country: this.options.countries?.at(0),\n geometryTypes: this.options.geometryTypes,\n mapLayers: getMapLayers(this),\n value\n }\n }\n\n getErrors(\n translator: Translator,\n errors?: FormSubmissionError[]\n ): FormSubmissionError[] | undefined {\n const fieldErrors = super.getErrors(translator, errors)\n\n fieldErrors?.forEach((err) => {\n if (err.name === 'description') {\n err.href = `#description_${err.path[1]}`\n err.text = translator.t(\n 'components.geospatialField.validation.descriptionRequired',\n { count: Number(err.path[1]) + 1 }\n )\n } else if (typeof err.name === 'number' && err.context?.country) {\n err.href = `#description_${err.path[1]}`\n err.text = translator.t(\n 'components.geospatialField.validation.wrongCountry',\n {\n count: Number(err.path[1]) + 1,\n country: translator.t(`common.${err.context.country}`)\n }\n )\n }\n })\n\n return fieldErrors\n }\n\n getViewErrors(\n translator: Translator,\n errors?: FormSubmissionError[]\n ): FormSubmissionError[] | undefined {\n return this.getErrors(translator, errors)\n }\n\n isValue(value?: FormStateValue | FormState): value is GeospatialState {\n return isGeospatialState(value)\n }\n\n getValidationMessagesOverride(translator: Translator) {\n const { language } = translator\n return {\n [this.name]: GeospatialField.buildErrorMessages(language, this.limits)\n }\n }\n\n /**\n * For error preview page that shows all possible errors on a component\n */\n getAllPossibleErrors(): ErrorMessageTemplateList {\n const staticErrors = GeospatialField.getAllPossibleErrors()\n return {\n ...staticErrors,\n advancedSettingsErrors: [...staticErrors.advancedSettingsErrors]\n }\n }\n\n /**\n * Static version of getAllPossibleErrors that doesn't require a component instance.\n */\n static getAllPossibleErrors(): ErrorMessageTemplateList {\n return {\n baseErrors: [\n { type: 'required', template: messageTemplate.selectRequired },\n {\n type: 'array.min',\n template: '{{#title}} must contain at least 1 item'\n },\n { type: 'object.invalidjson', template: messageTemplate.format }\n ],\n advancedSettingsErrors: []\n }\n }\n\n static buildErrorMessages(\n language: string,\n limits: { min?: number; max?: number; length?: number } = {}\n ) {\n return {\n 'array.min': tPlugin('validation.featuresMin', language, {\n count: limits.min ?? 1\n }),\n 'array.max': tPlugin('validation.featuresMax', language, {\n count: limits.max ?? 1\n }),\n 'array.length': tPlugin('validation.featuresLength', language, {\n count: limits.length ?? 1\n })\n }\n }\n}\n"],"mappings":"AAGA,SAASA,KAAK;AAEd,SACEC,aAAa,EACbC,iBAAiB;AAEnB,SAASC,YAAY;AACrB,SACEC,eAAe,EACfC,mBAAmB;AAGrB,SAASC,CAAC,IAAIC,OAAO;AAErB,SAASC,eAAe;AAUxB,OAAO,MAAMC,eAAe,SAASR,a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A;AACF;AACA;EACE6C,oBAAoBA,CAAA,EAA6B;IAC/C,MAAMC,YAAY,GAAGvD,eAAe,CAACsD,oBAAoB,CAAC,CAAC;IAC3D,OAAO;MACL,GAAGC,YAAY;MACfC,sBAAsB,EAAE,CAAC,GAAGD,YAAY,CAACC,sBAAsB;IACjE,CAAC;EACH;;EAEA;AACF;AACA;EACE,OAAOF,oBAAoBA,CAAA,EAA6B;IACtD,OAAO;MACLG,UAAU,EAAE,CACV;QAAEC,IAAI,EAAE,UAAU;QAAEC,QAAQ,EAAE5D,eAAe,CAAC6D;MAAe,CAAC,EAC9D;QACEF,IAAI,EAAE,WAAW;QACjBC,QAAQ,EAAE;MACZ,CAAC,EACD;QAAED,IAAI,EAAE,oBAAoB;QAAEC,QAAQ,EAAE5D,eAAe,CAAC8D;MAAO,CAAC,CACjE;MACDL,sBAAsB,EAAE;IAC1B,CAAC;EACH;EAEA,OAAO7C,kBAAkBA,CACvB0C,QAAgB,EAChB5C,MAAuD,GAAG,CAAC,CAAC,EAC5D;IACA,OAAO;MACL,WAAW,EAAEX,OAAO,CAAC,wBAAwB,EAAEuD,QAAQ,EAAE;QACvD3B,KAAK,EAAEjB,MAAM,CAACqD,GAAG,IAAI;MACvB,CAAC,CAAC;MACF,WAAW,EAAEhE,OAAO,CAAC,wBAAwB,EAAEuD,QAAQ,EAAE;QACvD3B,KAAK,EAAEjB,MAAM,CAACsD,GAAG,IAAI;MACvB,CAAC,CAAC;MACF,cAAc,EAAEjE,OAAO,CAAC,2BAA2B,EAAEuD,QAAQ,EAAE;QAC7D3B,KAAK,EAAEjB,MAAM,CAACgB,MAAM,IAAI;MAC1B,CAAC;IACH,CAAC;EACH;AACF","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"GeospatialField.js","names":["EN_GB","FormComponent","isGeospatialState","getMapLayers","determineLimits","getGeospatialSchema","t","tPlugin","messageTemplate","GeospatialField","constructor","def","props","options","formSchema","label","isOptional","required","limits","messages","buildErrorMessages","stateSchema","default","allow","getFormValueFromState","state","name","getFormValue","value","isValue","undefined","getDisplayStringFromFormValue","features","translator","length","count","getDisplayStringFromState","getContextValueFromFormValue","map","id","getContextValueFromState","getViewModel","context","viewModel","JSON","stringify","lang","language","country","countries","at","geometryTypes","mapLayers","getErrors","errors","fieldErrors","forEach","err","href","path","text","Number","getViewErrors","getValidationMessagesOverride","getAllPossibleErrors","staticErrors","advancedSettingsErrors","baseErrors","type","template","selectRequired","format","min","max"],"sources":["../../../../../src/server/plugins/engine/components/GeospatialField.ts"],"sourcesContent":["import { type GeospatialFieldComponent } from '@defra/forms-model'\nimport { type ArraySchema } from 'joi'\n\nimport { EN_GB } from '~/src/server/constants.js'\nimport { type ComponentBase } from '~/src/server/plugins/engine/components/ComponentBase.js'\nimport {\n FormComponent,\n isGeospatialState\n} from '~/src/server/plugins/engine/components/FormComponent.js'\nimport { getMapLayers } from '~/src/server/plugins/engine/components/LocationFieldHelpers.js'\nimport {\n determineLimits,\n getGeospatialSchema\n} from '~/src/server/plugins/engine/components/helpers/geospatial.js'\nimport { type RenderContext } from '~/src/server/plugins/engine/components/types.js'\nimport { t as tPlugin } from '~/src/server/plugins/engine/i18n/index.js'\nimport { type Translator } from '~/src/server/plugins/engine/i18n/types.js'\nimport { messageTemplate } from '~/src/server/plugins/engine/pageControllers/validationOptions.js'\nimport {\n type ErrorMessageTemplateList,\n type FormState,\n type FormStateValue,\n type FormSubmissionError,\n type FormSubmissionState,\n type GeospatialState\n} from '~/src/server/plugins/engine/types.js'\n\nexport class GeospatialField extends FormComponent {\n declare options: GeospatialFieldComponent['options']\n declare formSchema: ArraySchema<GeospatialState>\n declare stateSchema: ArraySchema<GeospatialState>\n declare limits: { min?: number; max?: number; length?: number }\n\n constructor(\n def: GeospatialFieldComponent,\n props: ConstructorParameters<typeof ComponentBase>[1]\n ) {\n super(def, props)\n\n const { options } = def\n\n let formSchema = getGeospatialSchema(def).label(this.label)\n\n const isOptional = options.required === false\n const limits = determineLimits(def, isOptional)\n\n formSchema = formSchema.messages(\n GeospatialField.buildErrorMessages(EN_GB, limits)\n )\n\n this.formSchema = formSchema\n this.stateSchema = formSchema.default(null)\n\n if (isOptional) {\n this.stateSchema = this.stateSchema.allow(null)\n }\n\n this.options = options\n this.limits = limits\n }\n\n getFormValueFromState(state: FormSubmissionState) {\n const { name } = this\n return this.getFormValue(state[name])\n }\n\n getFormValue(value?: FormStateValue | FormState) {\n return this.isValue(value) ? value : undefined\n }\n\n getDisplayStringFromFormValue(\n features: GeospatialState | undefined,\n translator: Translator\n ): string {\n if (!features?.length) {\n return ''\n }\n\n return translator.t('components.geospatialField.added', {\n count: features.length\n })\n }\n\n getDisplayStringFromState(\n state: FormSubmissionState,\n translator: Translator\n ) {\n const features = this.getFormValueFromState(state)\n\n return this.getDisplayStringFromFormValue(features, translator)\n }\n\n getContextValueFromFormValue(\n features: GeospatialState | undefined\n ): string[] | null {\n return features?.map(({ id }) => id) ?? null\n }\n\n getContextValueFromState(state: FormSubmissionState) {\n const features = this.getFormValueFromState(state)\n\n return this.getContextValueFromFormValue(features)\n }\n\n getViewModel(context: RenderContext) {\n const viewModel = super.getViewModel(context)\n const value =\n typeof viewModel.value === 'string'\n ? viewModel.value\n : JSON.stringify(viewModel.value, null, 2)\n\n return {\n ...viewModel,\n lang: context.translator.language,\n country: this.options.countries?.at(0),\n geometryTypes: this.options.geometryTypes,\n mapLayers: getMapLayers(this),\n value\n }\n }\n\n getErrors(\n translator: Translator,\n errors?: FormSubmissionError[]\n ): FormSubmissionError[] | undefined {\n const fieldErrors = super.getErrors(translator, errors)\n\n fieldErrors?.forEach((err) => {\n if (err.name === 'description') {\n err.href = `#description_${err.path[1]}`\n err.text = translator.t(\n 'components.geospatialField.validation.descriptionRequired',\n { count: Number(err.path[1]) + 1 }\n )\n } else if (typeof err.name === 'number' && err.context?.country) {\n err.href = `#description_${err.path[1]}`\n err.text = translator.t(\n 'components.geospatialField.validation.wrongCountry',\n {\n count: Number(err.path[1]) + 1,\n country: translator.t(`common.${err.context.country}`)\n }\n )\n }\n })\n\n return fieldErrors\n }\n\n getViewErrors(\n translator: Translator,\n errors?: FormSubmissionError[]\n ): FormSubmissionError[] | undefined {\n return this.getErrors(translator, errors)\n }\n\n isValue(value?: FormStateValue | FormState): value is GeospatialState {\n return isGeospatialState(value)\n }\n\n getValidationMessagesOverride(translator: Translator) {\n const { language } = translator\n return {\n [this.name]: GeospatialField.buildErrorMessages(language, this.limits)\n }\n }\n\n /**\n * For error preview page that shows all possible errors on a component\n */\n getAllPossibleErrors(): ErrorMessageTemplateList {\n const staticErrors = GeospatialField.getAllPossibleErrors()\n return {\n ...staticErrors,\n advancedSettingsErrors: [...staticErrors.advancedSettingsErrors]\n }\n }\n\n /**\n * Static version of getAllPossibleErrors that doesn't require a component instance.\n */\n static getAllPossibleErrors(): ErrorMessageTemplateList {\n return {\n baseErrors: [\n { type: 'required', template: messageTemplate.selectRequired },\n {\n type: 'array.min',\n template: '{{#title}} must contain at least 1 item'\n },\n { type: 'object.invalidjson', template: messageTemplate.format }\n ],\n advancedSettingsErrors: []\n }\n }\n\n static buildErrorMessages(\n language: string,\n limits: { min?: number; max?: number; length?: number } = {}\n ) {\n return {\n 'array.min': tPlugin('validation.featuresMin', language, {\n count: limits.min ?? 1\n }),\n 'array.max': tPlugin('validation.featuresMax', language, {\n count: limits.max ?? 1\n }),\n 'array.length': tPlugin('validation.featuresLength', language, {\n count: limits.length ?? 1\n })\n }\n }\n}\n"],"mappings":"AAGA,SAASA,KAAK;AAEd,SACEC,aAAa,EACbC,iBAAiB;AAEnB,SAASC,YAAY;AACrB,SACEC,eAAe,EACfC,mBAAmB;AAGrB,SAASC,CAAC,IAAIC,OAAO;AAErB,SAASC,eAAe;AAUxB,OAAO,MAAMC,eAAe,SAASR,aAAa,CAAC;EAMjDS,WAAWA,CACTC,GAA6B,EAC7BC,KAAqD,EACrD;IACA,KAAK,CAACD,GAAG,EAAEC,KAAK,CAAC;IAEjB,MAAM;MAAEC;IAAQ,CAAC,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AAoB,CAAC,CAAC;IAC3D,OAAO;MACL,GAAGC,YAAY;MACfC,sBAAsB,EAAE,CAAC,GAAGD,YAAY,CAACC,sBAAsB;IACjE,CAAC;EACH;;EAEA;AACF;AACA;EACE,OAAOF,oBAAoBA,CAAA,EAA6B;IACtD,OAAO;MACLG,UAAU,EAAE,CACV;QAAEC,IAAI,EAAE,UAAU;QAAEC,QAAQ,EAAE7D,eAAe,CAAC8D;MAAe,CAAC,EAC9D;QACEF,IAAI,EAAE,WAAW;QACjBC,QAAQ,EAAE;MACZ,CAAC,EACD;QAAED,IAAI,EAAE,oBAAoB;QAAEC,QAAQ,EAAE7D,eAAe,CAAC+D;MAAO,CAAC,CACjE;MACDL,sBAAsB,EAAE;IAC1B,CAAC;EACH;EAEA,OAAO9C,kBAAkBA,CACvB2B,QAAgB,EAChB7B,MAAuD,GAAG,CAAC,CAAC,EAC5D;IACA,OAAO;MACL,WAAW,EAAEX,OAAO,CAAC,wBAAwB,EAAEwC,QAAQ,EAAE;QACvDZ,KAAK,EAAEjB,MAAM,CAACsD,GAAG,IAAI;MACvB,CAAC,CAAC;MACF,WAAW,EAAEjE,OAAO,CAAC,wBAAwB,EAAEwC,QAAQ,EAAE;QACvDZ,KAAK,EAAEjB,MAAM,CAACuD,GAAG,IAAI;MACvB,CAAC,CAAC;MACF,cAAc,EAAElE,OAAO,CAAC,2BAA2B,EAAEwC,QAAQ,EAAE;QAC7DZ,KAAK,EAAEjB,MAAM,CAACgB,MAAM,IAAI;MAC1B,CAAC;IACH,CAAC;EACH;AACF","ignoreList":[]}
|
|
@@ -24,6 +24,7 @@ export declare class LatLongField extends FormComponent {
|
|
|
24
24
|
items: import("../../../../server/plugins/engine/components/types.js").DateInputItem[];
|
|
25
25
|
mapLayers: string;
|
|
26
26
|
country: import("@defra/forms-model").GeospatialFieldOptionsCountry | undefined;
|
|
27
|
+
lang: string;
|
|
27
28
|
label: import("../../../../server/plugins/engine/components/types.js").Label;
|
|
28
29
|
type?: string;
|
|
29
30
|
id: string;
|
|
@@ -76,6 +77,7 @@ export declare class LatLongField extends FormComponent {
|
|
|
76
77
|
items: import("../../../../server/plugins/engine/components/types.js").DateInputItem[];
|
|
77
78
|
mapLayers: string;
|
|
78
79
|
country: import("@defra/forms-model").GeospatialFieldOptionsCountry | undefined;
|
|
80
|
+
lang: string;
|
|
79
81
|
label: import("../../../../server/plugins/engine/components/types.js").Label;
|
|
80
82
|
type?: string;
|
|
81
83
|
id: string;
|
|
@@ -56,6 +56,9 @@ export class LocationFieldBase extends FormComponent {
|
|
|
56
56
|
}
|
|
57
57
|
getViewModel(context) {
|
|
58
58
|
const viewModel = super.getViewModel(context);
|
|
59
|
+
Object.assign(viewModel, {
|
|
60
|
+
lang: context.translator.language
|
|
61
|
+
});
|
|
59
62
|
if (this.instructionText) {
|
|
60
63
|
const {
|
|
61
64
|
tComponent
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"LocationFieldBase.js","names":["joi","FormComponent","isFormValue","addClassOptionIfNone","buildValidationMessages","messageTemplate","LocationFieldBase","instructionText","constructor","def","props","options","locationOptions","config","getValidationConfig","undefined","requiredMessage","required","messages","patternErrorMessage","formSchema","string","trim","label","pattern","allow","customValidationMessage","message","messageKeys","reduce","acc","key","customValidationMessages","default","stateSchema","getFormValueFromState","state","name","getFormValue","value","isValue","isText","getViewModel","context","viewModel","
|
|
1
|
+
{"version":3,"file":"LocationFieldBase.js","names":["joi","FormComponent","isFormValue","addClassOptionIfNone","buildValidationMessages","messageTemplate","LocationFieldBase","instructionText","constructor","def","props","options","locationOptions","config","getValidationConfig","undefined","requiredMessage","required","messages","patternErrorMessage","formSchema","string","trim","label","pattern","allow","customValidationMessage","message","messageKeys","reduce","acc","key","customValidationMessages","default","stateSchema","getFormValueFromState","state","name","getFormValue","value","isValue","isText","getViewModel","context","viewModel","Object","assign","lang","translator","language","tComponent","getValidationMessagesOverride","t","objectRequired","getAllPossibleErrors","baseErrors","type","template","getErrorTemplates","advancedSettingsErrors"],"sources":["../../../../../src/server/plugins/engine/components/LocationFieldBase.ts"],"sourcesContent":["import { type FormComponentsDef } from '@defra/forms-model'\nimport joi, {\n type JoiExpression,\n type LanguageMessages,\n type StringSchema\n} from 'joi'\n\nimport {\n FormComponent,\n isFormValue\n} from '~/src/server/plugins/engine/components/FormComponent.js'\nimport { addClassOptionIfNone } from '~/src/server/plugins/engine/components/helpers/index.js'\nimport { type RenderContext } from '~/src/server/plugins/engine/components/types.js'\nimport { buildValidationMessages } from '~/src/server/plugins/engine/i18n/buildValidationMessages.js'\nimport { messageTemplate } from '~/src/server/plugins/engine/pageControllers/validationOptions.js'\nimport { type Translator } from '~/src/server/plugins/engine/types/index.js'\nimport {\n type ErrorMessageTemplateList,\n type FormState,\n type FormStateValue,\n type FormSubmissionState\n} from '~/src/server/plugins/engine/types.js'\n\ninterface LocationFieldOptions {\n instructionText?: string\n required?: boolean\n customValidationMessage?: string\n customValidationMessages?: LanguageMessages\n classes?: string\n}\n\ninterface ValidationConfig {\n pattern: RegExp\n patternErrorMessage: JoiExpression\n requiredMessage?: JoiExpression\n}\n\n/**\n * Abstract base class for location-based field components\n */\nexport abstract class LocationFieldBase extends FormComponent {\n declare options: LocationFieldOptions\n declare formSchema: StringSchema\n declare stateSchema: StringSchema\n instructionText?: string\n\n protected abstract getValidationConfig(\n translator: Translator | undefined\n ): ValidationConfig\n protected abstract getErrorTemplates(): {\n type: string\n template: JoiExpression\n }[]\n\n constructor(\n def: FormComponentsDef,\n props: ConstructorParameters<typeof FormComponent>[1]\n ) {\n super(def, props)\n\n const { options } = def\n const locationOptions = options as LocationFieldOptions\n this.instructionText = locationOptions.instructionText\n\n addClassOptionIfNone(locationOptions, 'govuk-input--width-10')\n\n const config = this.getValidationConfig(undefined)\n const requiredMessage = config.requiredMessage ?? messageTemplate.required\n\n const messages = {\n 'any.required': requiredMessage,\n 'string.empty': requiredMessage,\n 'string.pattern.base': config.patternErrorMessage\n } as LanguageMessages\n\n let formSchema = joi\n .string()\n .trim()\n .label(this.label)\n .required()\n .pattern(config.pattern)\n .messages(messages)\n\n if (locationOptions.required === false) {\n formSchema = formSchema.allow('')\n }\n\n if (locationOptions.customValidationMessage) {\n const message = locationOptions.customValidationMessage\n const messageKeys = [\n 'any.required',\n 'string.empty',\n 'string.pattern.base'\n ]\n\n const messages = messageKeys.reduce<LanguageMessages>((acc, key) => {\n acc[key] = message\n return acc\n }, {})\n\n formSchema = formSchema.messages(messages)\n } else if (locationOptions.customValidationMessages) {\n formSchema = formSchema.messages(locationOptions.customValidationMessages)\n }\n\n this.formSchema = formSchema.default('')\n this.stateSchema = formSchema.default(null).allow(null)\n this.options = locationOptions\n }\n\n getFormValueFromState(state: FormSubmissionState) {\n const { name } = this\n return this.getFormValue(state[name])\n }\n\n getFormValue(value?: FormStateValue | FormState) {\n return this.isValue(value) ? value : undefined\n }\n\n isValue(value?: FormStateValue | FormState): value is string {\n return LocationFieldBase.isText(value)\n }\n\n getViewModel(context: RenderContext) {\n const viewModel = super.getViewModel(context)\n\n Object.assign(viewModel, {\n lang: context.translator.language\n })\n\n if (this.instructionText) {\n const { tComponent } = context.translator\n return {\n ...viewModel,\n instructionText:\n tComponent(this.def, 'instructionText') || this.instructionText\n }\n }\n\n return viewModel\n }\n\n getValidationMessagesOverride(translator: Translator) {\n const { t } = translator\n const config = this.getValidationConfig(translator)\n return {\n [this.name]: {\n 'any.required':\n config.requiredMessage ?? buildValidationMessages(t).objectRequired,\n 'string.empty':\n config.requiredMessage ?? buildValidationMessages(t).objectRequired,\n 'string.pattern.base': config.patternErrorMessage\n } as LanguageMessages\n }\n }\n\n getAllPossibleErrors(): ErrorMessageTemplateList {\n const config = this.getValidationConfig(undefined)\n\n return {\n baseErrors: [\n {\n type: 'required',\n template: config.requiredMessage ?? messageTemplate.required\n },\n ...this.getErrorTemplates()\n ],\n advancedSettingsErrors: []\n }\n }\n\n static isText(value?: FormStateValue | FormState): value is string {\n return isFormValue(value) && typeof value === 'string'\n }\n}\n"],"m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AGP,OAAO,CAACK,UAAU;MACzC,OAAO;QACL,GAAGJ,SAAS;QACZrC,eAAe,EACb2C,UAAU,CAAC,IAAI,CAACzC,GAAG,EAAE,iBAAiB,CAAC,IAAI,IAAI,CAACF;MACpD,CAAC;IACH;IAEA,OAAOqC,SAAS;EAClB;EAEAO,6BAA6BA,CAACH,UAAsB,EAAE;IACpD,MAAM;MAAEI;IAAE,CAAC,GAAGJ,UAAU;IACxB,MAAMnC,MAAM,GAAG,IAAI,CAACC,mBAAmB,CAACkC,UAAU,CAAC;IACnD,OAAO;MACL,CAAC,IAAI,CAACX,IAAI,GAAG;QACX,cAAc,EACZxB,MAAM,CAACG,eAAe,IAAIZ,uBAAuB,CAACgD,CAAC,CAAC,CAACC,cAAc;QACrE,cAAc,EACZxC,MAAM,CAACG,eAAe,IAAIZ,uBAAuB,CAACgD,CAAC,CAAC,CAACC,cAAc;QACrE,qBAAqB,EAAExC,MAAM,CAACM;MAChC;IACF,CAAC;EACH;EAEAmC,oBAAoBA,CAAA,EAA6B;IAC/C,MAAMzC,MAAM,GAAG,IAAI,CAACC,mBAAmB,CAACC,SAAS,CAAC;IAElD,OAAO;MACLwC,UAAU,EAAE,CACV;QACEC,IAAI,EAAE,UAAU;QAChBC,QAAQ,EAAE5C,MAAM,CAACG,eAAe,IAAIX,eAAe,CAACY;MACtD,CAAC,EACD,GAAG,IAAI,CAACyC,iBAAiB,CAAC,CAAC,CAC5B;MACDC,sBAAsB,EAAE;IAC1B,CAAC;EACH;EAEA,OAAOlB,MAAMA,CAACF,KAAkC,EAAmB;IACjE,OAAOrC,WAAW,CAACqC,KAAK,CAAC,IAAI,OAAOA,KAAK,KAAK,QAAQ;EACxD;AACF","ignoreList":[]}
|
|
@@ -25,6 +25,7 @@ export declare function getLocationFieldViewModel(component: LocationField, view
|
|
|
25
25
|
items: DateInputItem[];
|
|
26
26
|
mapLayers: string;
|
|
27
27
|
country: import("@defra/forms-model").GeospatialFieldOptionsCountry | undefined;
|
|
28
|
+
lang: string;
|
|
28
29
|
label: Label;
|
|
29
30
|
type?: string;
|
|
30
31
|
id: string;
|
|
@@ -77,6 +78,7 @@ export declare function getLocationFieldViewModel(component: LocationField, view
|
|
|
77
78
|
items: DateInputItem[];
|
|
78
79
|
mapLayers: string;
|
|
79
80
|
country: import("@defra/forms-model").GeospatialFieldOptionsCountry | undefined;
|
|
81
|
+
lang: string;
|
|
80
82
|
label: Label;
|
|
81
83
|
type?: string;
|
|
82
84
|
id: string;
|
|
@@ -124,7 +124,8 @@ export function getLocationFieldViewModel(component, viewModel, context) {
|
|
|
124
124
|
fieldset,
|
|
125
125
|
items,
|
|
126
126
|
mapLayers: getMapLayers(component),
|
|
127
|
-
country: component instanceof EastingNorthingField ? component.options.countries?.at(0) : undefined
|
|
127
|
+
country: component instanceof EastingNorthingField ? component.options.countries?.at(0) : undefined,
|
|
128
|
+
lang: context.translator.language
|
|
128
129
|
};
|
|
129
130
|
if (component.options.instructionText) {
|
|
130
131
|
const {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"LocationFieldHelpers.js","names":["EastingNorthingField","isFormValue","lowercaseMessageStart","message","charAt","toLowerCase","slice","joinWithAnd","items","translator","t","length","leading","join","last","formatErrorList","messages","formattedMessages","map","msg","index","mergeCssClasses","classNames","tokens","flatMap","name","split","token","trim","filter","Boolean","undefined","Array","from","Set","deduplicateErrorsByHref","errors","error","self","findIndex","err","href","getMapLayers","component","mapLayers","options","layers","sssi","push","getLocationFieldViewModel","viewModel","context","collection","fieldset","existingFieldset","label","subViewModels","getViewModel","fieldErrors","forEach","model","errorMessage","text","hasFieldErrors","type","value","classes","prefix","suffix","toString","baseItem","id","showFieldsetError","legend","result","country","countries","at","instructionText","tComponent","instructionSummary","def","createLocationFieldValidator","payload","helpers","values","getFormValueFromState","getStateFromValidForm","missing","keys","key","isState","required"],"sources":["../../../../../src/server/plugins/engine/components/LocationFieldHelpers.ts"],"sourcesContent":["import { type Context, type CustomValidator } from 'joi'\n\nimport { EastingNorthingField } from '~/src/server/plugins/engine/components/EastingNorthingField.js'\nimport { isFormValue } from '~/src/server/plugins/engine/components/FormComponent.js'\nimport { type GeospatialField } from '~/src/server/plugins/engine/components/GeospatialField.js'\nimport { type LatLongField } from '~/src/server/plugins/engine/components/LatLongField.js'\nimport { type OsGridRefField } from '~/src/server/plugins/engine/components/OsGridRefField.js'\nimport {\n type DateInputItem,\n type Label,\n type RenderContext,\n type ViewModel\n} from '~/src/server/plugins/engine/components/types.js'\nimport { type Translator } from '~/src/server/plugins/engine/i18n/types.js'\nimport {\n type FormPayload,\n type FormSubmissionError,\n type FormValue\n} from '~/src/server/plugins/engine/types.js'\n\nexport type LocationField =\n | InstanceType<typeof EastingNorthingField>\n | InstanceType<typeof LatLongField>\n\n/**\n * Lowercases the start of a message for concatenation.\n * Handles patterns like:\n * - \"Enter latitude\" -> \"enter latitude\"\n * - \"Enter a valid latitude...\" -> \"enter a valid latitude...\"\n * - \"latitude must be...\" -> \"latitude must be...\"\n */\nfunction lowercaseMessageStart(message: string): string {\n // Lowercase first character for a message\n return message.charAt(0).toLowerCase() + message.slice(1)\n}\n\nexport function joinWithAnd(items: string[], translator: Translator): string {\n const { t } = translator\n if (items.length === 2) {\n return `${items[0]} ${t('common.and')} ${items[1]}`\n }\n\n const leading = items.slice(0, -1).join(', ')\n const last = items[items.length - 1]\n return `${leading} ${t('common.and')} ${last}`\n}\n\nexport function formatErrorList(\n messages: string[],\n translator: Translator\n): string {\n if (!messages.length) {\n return ''\n }\n\n if (messages.length === 1) {\n return messages[0]\n }\n\n const formattedMessages = messages.map((msg, index) =>\n index === 0 ? msg : lowercaseMessageStart(msg)\n )\n\n return joinWithAnd(formattedMessages, translator)\n}\n\nexport function mergeCssClasses(...classNames: (string | undefined)[]) {\n const tokens = classNames\n .flatMap((name) => name?.split(/\\s+/) ?? [])\n .map((token) => token.trim())\n .filter(Boolean)\n\n if (!tokens.length) {\n return undefined\n }\n\n return Array.from(new Set(tokens)).join(' ')\n}\n\nexport function deduplicateErrorsByHref(\n errors?: FormSubmissionError[]\n): FormSubmissionError[] | undefined {\n if (!errors?.length) {\n return undefined\n }\n\n return errors.filter(\n (error, index, self) =>\n index === self.findIndex((err) => err.href === error.href)\n )\n}\n\nexport function getMapLayers(\n component:\n | GeospatialField\n | OsGridRefField\n | LatLongField\n | EastingNorthingField\n) {\n const { mapLayers } = component.options\n const layers = []\n\n if (mapLayers?.sssi) {\n layers.push('sssi')\n }\n\n return layers.join(',')\n}\n\nexport function getLocationFieldViewModel(\n component: LocationField,\n viewModel: ViewModel & {\n label: Label\n id: string\n name: string\n value: FormValue\n },\n context: RenderContext\n) {\n const { collection } = component\n const { fieldset: existingFieldset, label } = viewModel\n\n const subViewModels = collection.getViewModel(context)\n\n const fieldErrors: string[] = []\n subViewModels.forEach(({ model }) => {\n if (model.errorMessage?.text) {\n fieldErrors.push(model.errorMessage.text)\n }\n })\n\n const hasFieldErrors = fieldErrors.length > 0\n\n const items: DateInputItem[] = subViewModels.map(\n ({ model }): DateInputItem => {\n let { label, type, value, classes, prefix, suffix, errorMessage } = model\n\n if (label) {\n label.toString = () => label.text\n }\n\n if (!isFormValue(value)) {\n value = undefined\n }\n\n const baseItem: DateInputItem = {\n label,\n id: model.id,\n name: model.name,\n type,\n value,\n classes: mergeCssClasses(\n classes,\n hasFieldErrors ? 'govuk-input--error' : undefined\n ),\n prefix,\n suffix\n }\n\n if (!hasFieldErrors && errorMessage) {\n baseItem.errorMessage = errorMessage\n }\n\n return baseItem\n }\n )\n\n const showFieldsetError =\n hasFieldErrors || Boolean(viewModel.errorMessage?.text)\n\n viewModel.showFieldsetError = showFieldsetError\n\n if (hasFieldErrors) {\n viewModel.errorMessage = {\n text:\n fieldErrors.length === 1\n ? fieldErrors[0]\n : formatErrorList(fieldErrors, context.translator)\n }\n }\n\n const fieldset = existingFieldset ?? {\n legend: {\n text: label.text,\n classes: 'govuk-fieldset__legend--m'\n }\n }\n\n const result = {\n ...viewModel,\n fieldset,\n items,\n mapLayers: getMapLayers(component),\n country:\n component instanceof EastingNorthingField\n ? component.options.countries?.at(0)\n : undefined\n }\n\n if (component.options.instructionText) {\n const { t, tComponent } = context.translator\n\n return {\n ...result,\n instructionSummary: t('components.locationFieldBase.howToFind'),\n instructionText:\n tComponent(component.def, 'instructionText') ||\n component.options.instructionText,\n t\n }\n }\n\n return result\n}\n\n/**\n * Validator factory for location-based fields.\n * This creates a validator that ensures all required fields are present.\n */\nexport function createLocationFieldValidator(\n component: LocationField\n): CustomValidator {\n return (payload: FormPayload, helpers) => {\n const { collection, name, options } = component\n\n const values = component.getFormValueFromState(\n component.getStateFromValidForm(payload)\n )\n\n const context: Context = {\n missing: collection.keys,\n key: name\n }\n\n if (!component.isState(values)) {\n return options.required !== false\n ? helpers.error('object.required', context)\n : payload\n }\n\n return payload\n }\n}\n"],"mappings":"AAEA,SAASA,oBAAoB;AAC7B,SAASC,WAAW;AAqBpB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,qBAAqBA,CAACC,OAAe,EAAU;EACtD;EACA,OAAOA,OAAO,CAACC,MAAM,CAAC,CAAC,CAAC,CAACC,WAAW,CAAC,CAAC,GAAGF,OAAO,CAACG,KAAK,CAAC,CAAC,CAAC;AAC3D;AAEA,OAAO,SAASC,WAAWA,CAACC,KAAe,EAAEC,UAAsB,EAAU;EAC3E,MAAM;IAAEC;EAAE,CAAC,GAAGD,UAAU;EACxB,IAAID,KAAK,CAACG,MAAM,KAAK,CAAC,EAAE;IACtB,OAAO,GAAGH,KAAK,CAAC,CAAC,CAAC,IAAIE,CAAC,CAAC,YAAY,CAAC,IAAIF,KAAK,CAAC,CAAC,CAAC,EAAE;EACrD;EAEA,MAAMI,OAAO,GAAGJ,KAAK,CAACF,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAACO,IAAI,CAAC,IAAI,CAAC;EAC7C,MAAMC,IAAI,GAAGN,KAAK,CAACA,KAAK,CAACG,MAAM,GAAG,CAAC,CAAC;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C,eAAe,EAAE;IACrC,MAAM;MAAEpE,CAAC;MAAEqE;IAAW,CAAC,GAAG5B,OAAO,CAAC1C,UAAU;IAE5C,OAAO;MACL,GAAGiE,MAAM;MACTM,kBAAkB,EAAEtE,CAAC,CAAC,wCAAwC,CAAC;MAC/DoE,eAAe,EACbC,UAAU,CAACpC,SAAS,CAACsC,GAAG,EAAE,iBAAiB,CAAC,IAC5CtC,SAAS,CAACE,OAAO,CAACiC,eAAe;MACnCpE;IACF,CAAC;EACH;EAEA,OAAOgE,MAAM;AACf;;AAEA;AACA;AACA;AACA;AACA,OAAO,SAASQ,4BAA4BA,CAC1CvC,SAAwB,EACP;EACjB,OAAO,CAACwC,OAAoB,EAAEC,OAAO,KAAK;IACxC,MAAM;MAAEhC,UAAU;MAAE3B,IAAI;MAAEoB;IAAQ,CAAC,GAAGF,SAAS;IAE/C,MAAM0C,MAAM,GAAG1C,SAAS,CAAC2C,qBAAqB,CAC5C3C,SAAS,CAAC4C,qBAAqB,CAACJ,OAAO,CACzC,CAAC;IAED,MAAMhC,OAAgB,GAAG;MACvBqC,OAAO,EAAEpC,UAAU,CAACqC,IAAI;MACxBC,GAAG,EAAEjE;IACP,CAAC;IAED,IAAI,CAACkB,SAAS,CAACgD,OAAO,CAACN,MAAM,CAAC,EAAE;MAC9B,OAAOxC,OAAO,CAAC+C,QAAQ,KAAK,KAAK,GAC7BR,OAAO,CAAC/C,KAAK,CAAC,iBAAiB,EAAEc,OAAO,CAAC,GACzCgC,OAAO;IACb;IAEA,OAAOA,OAAO;EAChB,CAAC;AACH","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"LocationFieldHelpers.js","names":["EastingNorthingField","isFormValue","lowercaseMessageStart","message","charAt","toLowerCase","slice","joinWithAnd","items","translator","t","length","leading","join","last","formatErrorList","messages","formattedMessages","map","msg","index","mergeCssClasses","classNames","tokens","flatMap","name","split","token","trim","filter","Boolean","undefined","Array","from","Set","deduplicateErrorsByHref","errors","error","self","findIndex","err","href","getMapLayers","component","mapLayers","options","layers","sssi","push","getLocationFieldViewModel","viewModel","context","collection","fieldset","existingFieldset","label","subViewModels","getViewModel","fieldErrors","forEach","model","errorMessage","text","hasFieldErrors","type","value","classes","prefix","suffix","toString","baseItem","id","showFieldsetError","legend","result","country","countries","at","lang","language","instructionText","tComponent","instructionSummary","def","createLocationFieldValidator","payload","helpers","values","getFormValueFromState","getStateFromValidForm","missing","keys","key","isState","required"],"sources":["../../../../../src/server/plugins/engine/components/LocationFieldHelpers.ts"],"sourcesContent":["import { type Context, type CustomValidator } from 'joi'\n\nimport { EastingNorthingField } from '~/src/server/plugins/engine/components/EastingNorthingField.js'\nimport { isFormValue } from '~/src/server/plugins/engine/components/FormComponent.js'\nimport { type GeospatialField } from '~/src/server/plugins/engine/components/GeospatialField.js'\nimport { type LatLongField } from '~/src/server/plugins/engine/components/LatLongField.js'\nimport { type OsGridRefField } from '~/src/server/plugins/engine/components/OsGridRefField.js'\nimport {\n type DateInputItem,\n type Label,\n type RenderContext,\n type ViewModel\n} from '~/src/server/plugins/engine/components/types.js'\nimport { type Translator } from '~/src/server/plugins/engine/i18n/types.js'\nimport {\n type FormPayload,\n type FormSubmissionError,\n type FormValue\n} from '~/src/server/plugins/engine/types.js'\n\nexport type LocationField =\n | InstanceType<typeof EastingNorthingField>\n | InstanceType<typeof LatLongField>\n\n/**\n * Lowercases the start of a message for concatenation.\n * Handles patterns like:\n * - \"Enter latitude\" -> \"enter latitude\"\n * - \"Enter a valid latitude...\" -> \"enter a valid latitude...\"\n * - \"latitude must be...\" -> \"latitude must be...\"\n */\nfunction lowercaseMessageStart(message: string): string {\n // Lowercase first character for a message\n return message.charAt(0).toLowerCase() + message.slice(1)\n}\n\nexport function joinWithAnd(items: string[], translator: Translator): string {\n const { t } = translator\n if (items.length === 2) {\n return `${items[0]} ${t('common.and')} ${items[1]}`\n }\n\n const leading = items.slice(0, -1).join(', ')\n const last = items[items.length - 1]\n return `${leading} ${t('common.and')} ${last}`\n}\n\nexport function formatErrorList(\n messages: string[],\n translator: Translator\n): string {\n if (!messages.length) {\n return ''\n }\n\n if (messages.length === 1) {\n return messages[0]\n }\n\n const formattedMessages = messages.map((msg, index) =>\n index === 0 ? msg : lowercaseMessageStart(msg)\n )\n\n return joinWithAnd(formattedMessages, translator)\n}\n\nexport function mergeCssClasses(...classNames: (string | undefined)[]) {\n const tokens = classNames\n .flatMap((name) => name?.split(/\\s+/) ?? [])\n .map((token) => token.trim())\n .filter(Boolean)\n\n if (!tokens.length) {\n return undefined\n }\n\n return Array.from(new Set(tokens)).join(' ')\n}\n\nexport function deduplicateErrorsByHref(\n errors?: FormSubmissionError[]\n): FormSubmissionError[] | undefined {\n if (!errors?.length) {\n return undefined\n }\n\n return errors.filter(\n (error, index, self) =>\n index === self.findIndex((err) => err.href === error.href)\n )\n}\n\nexport function getMapLayers(\n component:\n | GeospatialField\n | OsGridRefField\n | LatLongField\n | EastingNorthingField\n) {\n const { mapLayers } = component.options\n const layers = []\n\n if (mapLayers?.sssi) {\n layers.push('sssi')\n }\n\n return layers.join(',')\n}\n\nexport function getLocationFieldViewModel(\n component: LocationField,\n viewModel: ViewModel & {\n label: Label\n id: string\n name: string\n value: FormValue\n },\n context: RenderContext\n) {\n const { collection } = component\n const { fieldset: existingFieldset, label } = viewModel\n\n const subViewModels = collection.getViewModel(context)\n\n const fieldErrors: string[] = []\n subViewModels.forEach(({ model }) => {\n if (model.errorMessage?.text) {\n fieldErrors.push(model.errorMessage.text)\n }\n })\n\n const hasFieldErrors = fieldErrors.length > 0\n\n const items: DateInputItem[] = subViewModels.map(\n ({ model }): DateInputItem => {\n let { label, type, value, classes, prefix, suffix, errorMessage } = model\n\n if (label) {\n label.toString = () => label.text\n }\n\n if (!isFormValue(value)) {\n value = undefined\n }\n\n const baseItem: DateInputItem = {\n label,\n id: model.id,\n name: model.name,\n type,\n value,\n classes: mergeCssClasses(\n classes,\n hasFieldErrors ? 'govuk-input--error' : undefined\n ),\n prefix,\n suffix\n }\n\n if (!hasFieldErrors && errorMessage) {\n baseItem.errorMessage = errorMessage\n }\n\n return baseItem\n }\n )\n\n const showFieldsetError =\n hasFieldErrors || Boolean(viewModel.errorMessage?.text)\n\n viewModel.showFieldsetError = showFieldsetError\n\n if (hasFieldErrors) {\n viewModel.errorMessage = {\n text:\n fieldErrors.length === 1\n ? fieldErrors[0]\n : formatErrorList(fieldErrors, context.translator)\n }\n }\n\n const fieldset = existingFieldset ?? {\n legend: {\n text: label.text,\n classes: 'govuk-fieldset__legend--m'\n }\n }\n\n const result = {\n ...viewModel,\n fieldset,\n items,\n mapLayers: getMapLayers(component),\n country:\n component instanceof EastingNorthingField\n ? component.options.countries?.at(0)\n : undefined,\n lang: context.translator.language\n }\n\n if (component.options.instructionText) {\n const { t, tComponent } = context.translator\n\n return {\n ...result,\n instructionSummary: t('components.locationFieldBase.howToFind'),\n instructionText:\n tComponent(component.def, 'instructionText') ||\n component.options.instructionText,\n t\n }\n }\n\n return result\n}\n\n/**\n * Validator factory for location-based fields.\n * This creates a validator that ensures all required fields are present.\n */\nexport function createLocationFieldValidator(\n component: LocationField\n): CustomValidator {\n return (payload: FormPayload, helpers) => {\n const { collection, name, options } = component\n\n const values = component.getFormValueFromState(\n component.getStateFromValidForm(payload)\n )\n\n const context: Context = {\n missing: collection.keys,\n key: name\n }\n\n if (!component.isState(values)) {\n return options.required !== false\n ? helpers.error('object.required', context)\n : payload\n }\n\n return payload\n }\n}\n"],"mappings":"AAEA,SAASA,oBAAoB;AAC7B,SAASC,WAAW;AAqBpB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,qBAAqBA,CAACC,OAAe,EAAU;EACtD;EACA,OAAOA,OAAO,CAACC,MAAM,CAAC,CAAC,CAAC,CAACC,WAAW,CAAC,CAAC,GAAGF,OAAO,CAACG,KAAK,CAAC,CAAC,CAAC;AAC3D;AAEA,OAAO,SAASC,WAAWA,CAACC,KAAe,EAAEC,UAAsB,EAAU;EAC3E,MAAM;IAAEC;EAAE,CAA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