diff --git a/designer/client/field-edit.tsx b/designer/client/field-edit.tsx index 9fc18182b2..d8a06d3950 100644 --- a/designer/client/field-edit.tsx +++ b/designer/client/field-edit.tsx @@ -16,7 +16,12 @@ export function FieldEdit({ isContentField = false }: Props) { const { selectedComponent, errors } = state; const { name, title, hint, attrs, type, options = {} } = selectedComponent; - const { hideTitle = false, optionalText = false, required = true } = options; + const { + hideTitle = false, + optionalText = false, + required = true, + exposeToContext = false, + } = options; const isFileUploadField = selectedComponent.type === "FileUploadField"; const fieldTitle = ComponentTypes.find((componentType) => componentType.name === type) @@ -188,6 +193,35 @@ export function FieldEdit({ isContentField = false }: Props) { +
+
+ + dispatch({ + type: Actions.EDIT_OPTIONS_EXPOSE_TO_CONTEXT, + payload: e.target.checked, + }) + } + /> + + + {i18n("common.exposeToContextOption.helpText")} + +
+
); diff --git a/designer/client/i18n/translations/en.translation.json b/designer/client/i18n/translations/en.translation.json index b5eac278e1..b6e13fffe5 100644 --- a/designer/client/i18n/translations/en.translation.json +++ b/designer/client/i18n/translations/en.translation.json @@ -69,6 +69,10 @@ "detailsLink": { "title": "Additional settings" }, + "exposeToContextOption": { + "helpText": "If using additional context, choose this option to expose the field to be used by additional contexts", + "title": "Expose to context" + }, "helpTextField": { "helpText": "Enter the description to show for this field", "title": "Help text (optional)" diff --git a/designer/client/reducers/component/componentReducer.options.ts b/designer/client/reducers/component/componentReducer.options.ts index c09d350056..8b555af45b 100644 --- a/designer/client/reducers/component/componentReducer.options.ts +++ b/designer/client/reducers/component/componentReducer.options.ts @@ -128,5 +128,13 @@ export function optionsReducer(state, action: OptionsActions) { options: { ...options, maxWords: payload }, }, }; + case Options.EDIT_OPTIONS_EXPOSE_TO_CONTEXT: + return { + ...state, + selectedComponent: { + ...selectedComponent, + options: { ...options, exposeToContext: payload }, + }, + }; } } diff --git a/designer/client/reducers/component/types.ts b/designer/client/reducers/component/types.ts index ee4e8549e1..b3c2c9f08f 100644 --- a/designer/client/reducers/component/types.ts +++ b/designer/client/reducers/component/types.ts @@ -51,6 +51,7 @@ export enum Options { EDIT_OPTIONS_MAX_WORDS = "EDIT_OPTIONS_MAX_WORDS", EDIT_OPTIONS_PREFIX = "EDIT_OPTIONS_PREFIX", EDIT_OPTIONS_SUFFIX = "EDIT_OPTIONS_SUFFIX", + EDIT_OPTIONS_EXPOSE_TO_CONTEXT = "EDIT_OPTIONS_EXPOSE_TO_CONTEXT", } export const Actions = { diff --git a/docker-compose.smoke.yml b/docker-compose.smoke.yml index e72ebf0af8..81329979a3 100644 --- a/docker-compose.smoke.yml +++ b/docker-compose.smoke.yml @@ -36,6 +36,7 @@ services: - sandbox=true - PREVIEW_MODE=true - NODE_ENV=test + - ALLOW_USER_TEMPLATES=true command: yarn runner start depends_on: - redis diff --git a/docs/runner/templating.md b/docs/runner/templating.md new file mode 100644 index 0000000000..0115eaf4a3 --- /dev/null +++ b/docs/runner/templating.md @@ -0,0 +1,27 @@ +# Templating + +If you find yourself faced with a form with content that needs to appear based on different field values, and there's a lot of options to choose from, putting all of this content in conditions may be at best very time-consuming, and at worst crash your form runner. + +With this in mind, templating may be a good solution for you. + +## How it works + +You can allow fields to be exposed to the additional context by adding an `exposeToContext` flag to the component's options. This can be done manually, or through the "expose to context" field in the designer. + +Once your field is exposed, the field can be used with additional context by adding the field in titles and html components, using nunjucks templating syntax, `{{ fieldName }}`. + +You can also access additional values (such as custom html) using the additional context file. This will allow you to populate different variables based of the same user input, and these can be accessed using the format `{{ additionalContexts.contextName[fieldName].variableName }}`. + +There is an example form set up to demonstrate this. If you start your runner, and navigate to http://localhost:3009/html-templating-example, you can choose either option and see the dynamic content on the next page. + +## Adding your own additional context + +You can add your own additional context by modifying the additional context json, located at `runner/src/server/templates/additionalContexts.json`. + +Once you have added your own additionalContext namespace in the same way the example namespace is populated, you'll be able to add your context variables to your html component as stated above e.g for the example form, the list is set by referencing `{{ additionalContexts.example[contentToDisplay].listItems }}`. + +### Using nunjucks filters + +You can also apply nunjucks filters to your context, for example you may want to add the `safe` filter for printing html content. You would do this the same way you would in normal nunjucks, e.g. `{{ additionalContexts.example[contentToDisplay].listItems | safe }}`. + +For more information about what nunjucks filters are available to you, [visit the Nunjucks docs](https://mozilla.github.io/nunjucks/templating.html#filters). diff --git a/e2e/cypress/e2e/runner/htmlTemplating.feature b/e2e/cypress/e2e/runner/htmlTemplating.feature new file mode 100644 index 0000000000..5f9d53282c --- /dev/null +++ b/e2e/cypress/e2e/runner/htmlTemplating.feature @@ -0,0 +1,17 @@ +Feature: HTML templating in forms + + Scenario: Correct content should be shown for option one + When the form "html-templating-example" exists + And I choose "Answer 1" + And I continue + Then I see "This content is based on answer 1" + And I see "Item 1" + And I see "Item 2" + + Scenario: Correct content should be shown for option 2 + When the form "html-templating-example" exists + And I choose "Answer 2" + And I continue + Then I see "This content is based on answer 2" + And I see "Item 3" + And I see "Item 4" \ No newline at end of file diff --git a/e2e/cypress/fixtures/html-templating-example.json b/e2e/cypress/fixtures/html-templating-example.json new file mode 100644 index 0000000000..5052cc6eb9 --- /dev/null +++ b/e2e/cypress/fixtures/html-templating-example.json @@ -0,0 +1,63 @@ +{ + "metadata": {}, + "startPage": "/which-content-do-you-want-to-display", + "pages": [ + { + "title": "Which content do you want to display?", + "path": "/which-content-do-you-want-to-display", + "components": [ + { + "name": "contentToDisplay", + "options": { "exposeToContext": true }, + "type": "RadiosField", + "title": "Content to display", + "list": "vYTQRu", + "nameHasError": false, + "values": { "type": "listRef" }, + "schema": {} + } + ], + "next": [{ "path": "/second-page" }], + "section": "gcdSFb" + }, + { + "path": "/second-page", + "title": "Dynamic page based on your answers: {{ contentToDisplay }}", + "components": [ + { + "name": "azSyOn", + "options": {}, + "type": "Html", + "content": "

This page demonstrates how templating works.

\n

Depending on the answer you chose for the first question, you should see different content displayed below.

\n

You chosen the option: {{contentToDisplay}}

\n{{additionalContexts.example[contentToDisplay].additionalInfo | safe}}\n

The following list will have different items

\n", + "schema": {} + } + ], + "next": [{ "path": "/summary" }] + }, + { + "title": "Summary", + "path": "/summary", + "controller": "./pages/summary.js", + "components": [], + "next": [] + } + ], + "lists": [ + { + "title": "Options", + "name": "vYTQRu", + "type": "string", + "items": [ + { "text": "Answer 1", "value": "Answer 1" }, + { "text": "Answer 2", "value": "Answer 2" } + ] + } + ], + "sections": [{ "name": "gcdSFb", "title": "section" }], + "conditions": [], + "fees": [], + "outputs": [], + "version": 2, + "skipSummary": false, + "feeOptions": { "allowSubmissionWithoutPayment": true, "maxAttempts": 3 } +} diff --git a/model/src/components/types.ts b/model/src/components/types.ts index 263875e88a..3121a5e1d4 100644 --- a/model/src/components/types.ts +++ b/model/src/components/types.ts @@ -80,6 +80,7 @@ interface TextFieldBase { classes?: string; allow?: string; autocomplete?: string; + exposeToContext?: boolean; }; schema: { max?: number; @@ -99,6 +100,7 @@ interface NumberFieldBase { options: { prefix?: string; suffix?: string; + exposeToContext?: boolean; }; schema: { min?: number; @@ -119,6 +121,7 @@ interface ListFieldBase { optionalText?: boolean; classes?: string; bold?: boolean; + exposeToContext?: boolean; }; list: string; schema: {}; @@ -146,6 +149,7 @@ interface DateFieldBase { optionalText?: boolean; maxDaysInFuture?: number; maxDaysInPast?: number; + exposeToContext?: boolean; }; schema: {}; } @@ -212,6 +216,7 @@ export interface FileUploadFieldComponent { hideTitle?: boolean; multiple?: boolean; classes?: string; + exposeToContext?: boolean; }; schema: {}; } diff --git a/runner/config/custom-environment-variables.json b/runner/config/custom-environment-variables.json index 24d69490bb..c044fb0945 100644 --- a/runner/config/custom-environment-variables.json +++ b/runner/config/custom-environment-variables.json @@ -50,5 +50,6 @@ "queueDatabaseUrl": "QUEUE_DATABASE_URL", "queueDatabaseUsername": "QUEUE_DATABASE_USERNAME", "queueDatabasePassword": "QUEUE_DATABASE_PASSWORD", - "queueServicePollingInterval": "QUEUE_SERVICE_POLLING_INTERVAL" + "queueServicePollingInterval": "QUEUE_SERVICE_POLLING_INTERVAL", + "allowUserTemplates": "ALLOW_USER_TEMPLATES" } diff --git a/runner/config/default.js b/runner/config/default.js index b2944f764a..d902b0b9dc 100644 --- a/runner/config/default.js +++ b/runner/config/default.js @@ -135,4 +135,6 @@ module.exports = { enableQueueService: false, // queueDatabaseUrl: "mysql://root:root@localhost:3306/queue" queueServicePollingInterval: "500", + + allowUserTemplates: false, }; diff --git a/runner/src/server/forms/html-templating-example.json b/runner/src/server/forms/html-templating-example.json new file mode 100644 index 0000000000..5052cc6eb9 --- /dev/null +++ b/runner/src/server/forms/html-templating-example.json @@ -0,0 +1,63 @@ +{ + "metadata": {}, + "startPage": "/which-content-do-you-want-to-display", + "pages": [ + { + "title": "Which content do you want to display?", + "path": "/which-content-do-you-want-to-display", + "components": [ + { + "name": "contentToDisplay", + "options": { "exposeToContext": true }, + "type": "RadiosField", + "title": "Content to display", + "list": "vYTQRu", + "nameHasError": false, + "values": { "type": "listRef" }, + "schema": {} + } + ], + "next": [{ "path": "/second-page" }], + "section": "gcdSFb" + }, + { + "path": "/second-page", + "title": "Dynamic page based on your answers: {{ contentToDisplay }}", + "components": [ + { + "name": "azSyOn", + "options": {}, + "type": "Html", + "content": "

This page demonstrates how templating works.

\n

Depending on the answer you chose for the first question, you should see different content displayed below.

\n

You chosen the option: {{contentToDisplay}}

\n{{additionalContexts.example[contentToDisplay].additionalInfo | safe}}\n

The following list will have different items

\n", + "schema": {} + } + ], + "next": [{ "path": "/summary" }] + }, + { + "title": "Summary", + "path": "/summary", + "controller": "./pages/summary.js", + "components": [], + "next": [] + } + ], + "lists": [ + { + "title": "Options", + "name": "vYTQRu", + "type": "string", + "items": [ + { "text": "Answer 1", "value": "Answer 1" }, + { "text": "Answer 2", "value": "Answer 2" } + ] + } + ], + "sections": [{ "name": "gcdSFb", "title": "section" }], + "conditions": [], + "fees": [], + "outputs": [], + "version": 2, + "skipSummary": false, + "feeOptions": { "allowSubmissionWithoutPayment": true, "maxAttempts": 3 } +} diff --git a/runner/src/server/index.ts b/runner/src/server/index.ts index aaee242925..8476917ea7 100644 --- a/runner/src/server/index.ts +++ b/runner/src/server/index.ts @@ -114,7 +114,6 @@ async function createServer(routeConfig: RouteConfig) { WebhookService, AddressService, ]); - if (config.enableQueueService) { server.registerService([ QueueService, diff --git a/runner/src/server/plugins/engine/components/Html.ts b/runner/src/server/plugins/engine/components/Html.ts index be379e41c0..0b57ea3be0 100644 --- a/runner/src/server/plugins/engine/components/Html.ts +++ b/runner/src/server/plugins/engine/components/Html.ts @@ -1,12 +1,18 @@ import { FormData, FormSubmissionErrors } from "../types"; import { ComponentBase } from "./ComponentBase"; +import config from "../../../config"; +import nunjucks from "nunjucks"; export class Html extends ComponentBase { getViewModel(formData: FormData, errors: FormSubmissionErrors) { const { options } = this; + let content = this.content; + if (config.allowUserTemplates) { + content = nunjucks.renderString(content, { ...formData }); + } const viewModel = { ...super.getViewModel(formData, errors), - content: this.content, + content: content, }; if ("condition" in options && options.condition) { diff --git a/runner/src/server/plugins/engine/components/helpers.ts b/runner/src/server/plugins/engine/components/helpers.ts index 4b921dbcb9..77b97c0566 100644 --- a/runner/src/server/plugins/engine/components/helpers.ts +++ b/runner/src/server/plugins/engine/components/helpers.ts @@ -1,5 +1,4 @@ import joi from "joi"; -import Joi from "joi"; import { add, startOfToday, sub } from "date-fns"; /** @@ -92,12 +91,11 @@ export const addClassOptionIfNone = ( options.classes = className; } }; - export function getCustomDateValidator( maxDaysInPast?: number, maxDaysInFuture?: number ) { - return (value: Date, helpers: Joi.CustomHelpers) => { + return (value: Date, helpers: joi.CustomHelpers) => { if (maxDaysInPast) { const minDate = sub(startOfToday(), { days: maxDaysInPast }); if (value < minDate) { diff --git a/runner/src/server/plugins/engine/models/FormModel.ts b/runner/src/server/plugins/engine/models/FormModel.ts index 86145cd36d..ed051eef3d 100644 --- a/runner/src/server/plugins/engine/models/FormModel.ts +++ b/runner/src/server/plugins/engine/models/FormModel.ts @@ -16,6 +16,7 @@ import { PageControllerBase, getPageController } from "../pageControllers"; import { PageController } from "../pageControllers/PageController"; import { ExecutableCondition } from "server/plugins/engine/models/types"; import { DEFAULT_FEE_OPTIONS } from "server/plugins/engine/models/FormModel.feeOptions"; +import { ComponentCollection } from "server/plugins/engine/components"; class EvaluationContext { constructor(conditions, value) { @@ -48,6 +49,7 @@ export class FormModel { /** the id of the form used for the first url parameter eg localhost:3009/test */ basePath: string; conditions: Record | {}; + fieldsForContext: ComponentCollection; pages: any; startPage: any; @@ -108,6 +110,13 @@ export class FormModel { this.conditions[condition.name] = condition; }); + const exposedComponentDefs = def.pages.flatMap((page) => { + return page.components.filter( + (component) => component.options?.exposeToContext + ); + }); + this.fieldsForContext = new ComponentCollection(exposedComponentDefs, this); + // @ts-ignore this.pages = def.pages.map((pageDef) => this.makePage(pageDef)); this.startPage = this.pages.find((page) => page.path === def.startPage); @@ -250,4 +259,21 @@ export class FormModel { getList(name: string): List | [] { return this.lists.find((list) => list.name === name) ?? []; } + + getContextState(state: FormSubmissionState) { + const contextState = Object.keys(state).reduce((acc, curr) => { + if (typeof state[curr] === "object") { + return { + ...acc, + ...state[curr], + }; + } + return { + ...acc, + [curr]: state[curr], + }; + }, {}); + + return this.fieldsForContext.getFormDataFromState(contextState); + } } diff --git a/runner/src/server/plugins/engine/models/SummaryViewModel.ts b/runner/src/server/plugins/engine/models/SummaryViewModel.ts index 22fb0ff00b..584ee63836 100644 --- a/runner/src/server/plugins/engine/models/SummaryViewModel.ts +++ b/runner/src/server/plugins/engine/models/SummaryViewModel.ts @@ -92,11 +92,13 @@ export class SummaryViewModel { this.processErrors(result, details); } else { this.fees = FeesModel(model, state); + this._webhookData = WebhookModel( relevantPages, details, model, - this.fees + this.fees, + model.getContextState(state) ); this._webhookData = this.addFeedbackSourceDataToWebhook( this._webhookData, diff --git a/runner/src/server/plugins/engine/models/submission/WebhookModel.ts b/runner/src/server/plugins/engine/models/submission/WebhookModel.ts index e9320a6724..a998646c38 100644 --- a/runner/src/server/plugins/engine/models/submission/WebhookModel.ts +++ b/runner/src/server/plugins/engine/models/submission/WebhookModel.ts @@ -1,6 +1,7 @@ import { DetailItem } from "../types"; import { format } from "date-fns"; import config from "server/config"; +import nunjucks from "nunjucks"; function answerFromDetailItem(item) { switch (item.dataType) { @@ -25,7 +26,13 @@ function detailItemToField(item: DetailItem) { }; } -export function WebhookModel(relevantPages, details, model, fees) { +export function WebhookModel( + relevantPages, + details, + model, + fees, + contextState +) { const questions = relevantPages?.map((page) => { const isRepeatable = !!page.repeatField; @@ -52,12 +59,18 @@ export function WebhookModel(relevantPages, details, model, fees) { return fields; }); + let pageTitle = page.title; + + if (pageTitle) { + pageTitle = nunjucks.renderString(page.title.en ?? page.title, { + ...contextState, + }); + } + return { category: page.section?.name, question: - page.title?.en ?? - page.title ?? - page.components.formItems.map((item) => item.title), + pageTitle ?? page.components.formItems.map((item) => item.title), fields, index, }; diff --git a/runner/src/server/plugins/engine/pageControllers/PageControllerBase.ts b/runner/src/server/plugins/engine/pageControllers/PageControllerBase.ts index 8cf3ef46fd..f92e8a932c 100644 --- a/runner/src/server/plugins/engine/pageControllers/PageControllerBase.ts +++ b/runner/src/server/plugins/engine/pageControllers/PageControllerBase.ts @@ -23,6 +23,8 @@ import { } from "../types"; import { ComponentCollectionViewModel } from "../components/types"; import { format, parseISO } from "date-fns"; +import config from "server/config"; +import nunjucks from "nunjucks"; const FORM_SCHEMA = Symbol("FORM_SCHEMA"); const STATE_SCHEMA = Symbol("STATE_SCHEMA"); @@ -113,6 +115,11 @@ export class PageControllerBase { } { let showTitle = true; let pageTitle = this.title; + if (config.allowUserTemplates) { + pageTitle = nunjucks.renderString(pageTitle, { + ...formData, + }); + } let sectionTitle = this.section?.title; if (sectionTitle && iteration !== undefined) { sectionTitle = `${sectionTitle} ${iteration}`; @@ -269,12 +276,19 @@ export class PageControllerBase { ? values.reduce((acc: any, page: any) => ({ ...acc, ...page }), {}) : {}; - return this.components.getFormDataFromState( - newState as FormSubmissionState - ); + return { + ...this.components.getFormDataFromState( + newState as FormSubmissionState + ), + ...this.model.fieldsForContext?.getFormDataFromState( + newState as FormSubmissionState + ), + }; } - - return this.components.getFormDataFromState(pageState || {}); + return { + ...this.components.getFormDataFromState(pageState || {}), + ...this.model.getContextState(state), + }; } getStateFromValidForm(formData: FormPayload) { @@ -420,7 +434,6 @@ export class PageControllerBase { } }); } - const viewModel = this.getViewModel(formData, num); viewModel.startPage = startPage!.startsWith("http") ? redirectTo(request, h, startPage!) diff --git a/runner/src/server/plugins/engine/views/components/html.html b/runner/src/server/plugins/engine/views/components/html.html index 349b5b459b..0456cae4f0 100644 --- a/runner/src/server/plugins/engine/views/components/html.html +++ b/runner/src/server/plugins/engine/views/components/html.html @@ -1,3 +1,3 @@ {% macro Html(component) %} - {{ component.model.content | safe }} + {{ component.model.content | safe }} {% endmacro %} diff --git a/runner/src/server/plugins/engine/views/index.html b/runner/src/server/plugins/engine/views/index.html index 9dd879f798..2226e1e913 100644 --- a/runner/src/server/plugins/engine/views/index.html +++ b/runner/src/server/plugins/engine/views/index.html @@ -1,7 +1,12 @@ +{% extends 'layout.html' %} + +{% block templateImports %} + {{ super() }} +{% endblock %}} + {% from "error-summary/macro.njk" import govukErrorSummary %} -{% from "partials/components.html" import componentList %} +{% from "partials/components.html" import componentList with context %} -{% extends 'layout.html' %} {% block content %} {% set gridSize = "full" if components[0].type == 'FlashCard' else "two-thirds" %} diff --git a/runner/src/server/plugins/engine/views/partials/components.html b/runner/src/server/plugins/engine/views/partials/components.html index 32ae723acd..8288367244 100644 --- a/runner/src/server/plugins/engine/views/partials/components.html +++ b/runner/src/server/plugins/engine/views/partials/components.html @@ -1,6 +1,6 @@ {% macro componentList(components) %} {% for component in components %} - {% import "../components/" + component.type.toLowerCase() + ".html" as view %} + {% import "../components/" + component.type.toLowerCase() + ".html" as view with context %} {{ view[component.type](component) }} {% endfor %} {% endmacro %} diff --git a/runner/src/server/plugins/views.ts b/runner/src/server/plugins/views.ts index 92544d2212..1a1544bcdd 100644 --- a/runner/src/server/plugins/views.ts +++ b/runner/src/server/plugins/views.ts @@ -7,6 +7,7 @@ import { capitalize } from "lodash"; import pkg from "../../../package.json"; import config from "../config"; import { HapiRequest } from "../types"; +import additionalContexts from "../templates/additionalContexts.json"; const basedir = path.join(process.cwd(), ".."); @@ -41,6 +42,7 @@ export default { autoescape: true, watch: false, }); + environment.addGlobal("additionalContexts", additionalContexts); environment.addFilter("isArray", (x) => Array.isArray(x)); options.compileOptions.environment = environment; diff --git a/runner/src/server/templates/additionalContexts.json b/runner/src/server/templates/additionalContexts.json new file mode 100644 index 0000000000..a531e049cc --- /dev/null +++ b/runner/src/server/templates/additionalContexts.json @@ -0,0 +1,12 @@ +{ + "example": { + "Answer 1": { + "additionalInfo": "

This content is based on answer 1

", + "listItems": "
  • Item 1
  • Item 2
  • " + }, + "Answer 2": { + "additionalInfo": "

    This content is based on answer 2

    ", + "listItems": "
  • Item 3
  • Item 4
  • " + } + } +} diff --git a/runner/src/server/utils/configSchema.ts b/runner/src/server/utils/configSchema.ts index 99e78b0b8b..70249811ae 100644 --- a/runner/src/server/utils/configSchema.ts +++ b/runner/src/server/utils/configSchema.ts @@ -113,6 +113,7 @@ export const configSchema = Joi.object({ then: Joi.required(), otherwise: Joi.optional(), }), + allowUserTemplates: Joi.boolean().optional(), }); export function buildConfig(config) { diff --git a/runner/tsconfig.json b/runner/tsconfig.json index 878beb1d58..5078d8c478 100644 --- a/runner/tsconfig.json +++ b/runner/tsconfig.json @@ -8,19 +8,17 @@ "esModuleInterop": true, "paths": { "src/*": ["src/*"], - "server/*": ["src/server/*"], + "server/*": ["src/server/*"] }, "resolveJsonModule": true, "lib": [ "dom", + "ES2020.String", "ES2020.Promise", "ES2019.Object", "ES2019.Array" ], "skipLibCheck": true }, - "include": [ - "src", - "package.json" - ] + "include": ["src", "package.json"] }