From 3bdf5d255a2d5c503565e17d105d05d2ff699f58 Mon Sep 17 00:00:00 2001 From: edemirbag <17883910+edemirbag@users.noreply.github.com> Date: Wed, 20 Mar 2024 17:26:26 +0000 Subject: [PATCH 1/2] - Provide a flexible mechanism for key-based lookup with fallback options in support of content updates related to ASL-4413 - Include tests to validate that the snippet component can correctly handle fallbacks when attempting to retrieve templates --- package.json | 2 +- src/snippet/index.jsx | 18 ++++++++++++++++-- src/snippet/index.spec.jsx | 12 ++++++++++++ 3 files changed, 29 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index 88f0d948..724a836c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@ukhomeoffice/asl-components", - "version": "13.2.1", + "version": "13.5.0", "description": "React components for ASL layouts and elements", "main": "src/index.jsx", "styles": "styles/index.scss", diff --git a/src/snippet/index.jsx b/src/snippet/index.jsx index 27fc7849..141620c3 100644 --- a/src/snippet/index.jsx +++ b/src/snippet/index.jsx @@ -4,13 +4,27 @@ import { connect } from 'react-redux'; import Markdown from '../markdown'; import { render } from 'mustache'; +function getTemplate(content, primary, fallback) { + const keysToTry = [primary, ...(Array.isArray(fallback) ? fallback : [fallback])]; + + for (let key of keysToTry) { + const template = get(content, key); + if (template != undefined) { + return template; + } + } + + return undefined; +} + export const Snippet = ({ content, children, optional, fallback, ...props }) => { - const str = get(content, children, get(content, fallback)); + const str = getTemplate(content, children, fallback); if (str === undefined && optional) { return null; + } if (str === undefined) { - throw new Error(`Failed to lookup content snippet: ${children}`); + return `Failed to lookup content snippet: ${children}`; } if (typeof str !== 'string') { throw new Error(`Invalid content snippet for key ${children}: ${JSON.stringify(str)}`); diff --git a/src/snippet/index.spec.jsx b/src/snippet/index.spec.jsx index 10fe9312..04d2ff18 100644 --- a/src/snippet/index.spec.jsx +++ b/src/snippet/index.spec.jsx @@ -42,4 +42,16 @@ two` expect(wrapper.html()).toEqual(paragraphs); }); + test('can accept single fallback', () => { + const wrapper = render(