Skip to content

Commit

Permalink
feat: Added templating to html components and titles
Browse files Browse the repository at this point in the history
  • Loading branch information
ziggy-cyb authored Nov 27, 2023
1 parent 12785a7 commit d443ec2
Show file tree
Hide file tree
Showing 26 changed files with 328 additions and 27 deletions.
36 changes: 35 additions & 1 deletion designer/client/field-edit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -188,6 +193,35 @@ export function FieldEdit({ isContentField = false }: Props) {
</span>
</div>
</div>
<div
className="govuk-checkboxes govuk-form-group"
data-test-id="field-options.exposeToContext-wrapper"
>
<div className="govuk-checkboxes__item">
<input
className="govuk-checkboxes__input"
id="field-options-exposeToContext"
name="options.exposeToContext"
type="checkbox"
checked={exposeToContext}
onChange={(e) =>
dispatch({
type: Actions.EDIT_OPTIONS_EXPOSE_TO_CONTEXT,
payload: e.target.checked,
})
}
/>
<label
className="govuk-label govuk-checkboxes__label"
htmlFor="field-options-exposeToContext"
>
{i18n("common.exposeToContextOption.title")}
</label>
<span className="govuk-hint govuk-checkboxes__hint">
{i18n("common.exposeToContextOption.helpText")}
</span>
</div>
</div>
</div>
</div>
);
Expand Down
4 changes: 4 additions & 0 deletions designer/client/i18n/translations/en.translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -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)"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 },
},
};
}
}
1 change: 1 addition & 0 deletions designer/client/reducers/component/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down
1 change: 1 addition & 0 deletions docker-compose.smoke.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ services:
- sandbox=true
- PREVIEW_MODE=true
- NODE_ENV=test
- ALLOW_USER_TEMPLATES=true
command: yarn runner start
depends_on:
- redis
Expand Down
27 changes: 27 additions & 0 deletions docs/runner/templating.md
Original file line number Diff line number Diff line change
@@ -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).
17 changes: 17 additions & 0 deletions e2e/cypress/e2e/runner/htmlTemplating.feature
Original file line number Diff line number Diff line change
@@ -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"
63 changes: 63 additions & 0 deletions e2e/cypress/fixtures/html-templating-example.json
Original file line number Diff line number Diff line change
@@ -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": "<p class=\"govuk-body\">This page demonstrates how templating works.</p>\n<p class=\"govuk-body\">Depending on the answer you chose for the first question, you should see different content displayed below.</p>\n<p class=\"govuk-body\">You chosen the option: {{contentToDisplay}}</p>\n{{additionalContexts.example[contentToDisplay].additionalInfo | safe}}\n<p class=\"govuk-body\">The following list will have different items</p>\n<ul class=\"govuk-list govuk-list--bullet\">\n{{additionalContexts.example[contentToDisplay].listItems | safe }}\n</ul>",
"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 }
}
5 changes: 5 additions & 0 deletions model/src/components/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ interface TextFieldBase {
classes?: string;
allow?: string;
autocomplete?: string;
exposeToContext?: boolean;
};
schema: {
max?: number;
Expand All @@ -99,6 +100,7 @@ interface NumberFieldBase {
options: {
prefix?: string;
suffix?: string;
exposeToContext?: boolean;
};
schema: {
min?: number;
Expand All @@ -119,6 +121,7 @@ interface ListFieldBase {
optionalText?: boolean;
classes?: string;
bold?: boolean;
exposeToContext?: boolean;
};
list: string;
schema: {};
Expand Down Expand Up @@ -146,6 +149,7 @@ interface DateFieldBase {
optionalText?: boolean;
maxDaysInFuture?: number;
maxDaysInPast?: number;
exposeToContext?: boolean;
};
schema: {};
}
Expand Down Expand Up @@ -212,6 +216,7 @@ export interface FileUploadFieldComponent {
hideTitle?: boolean;
multiple?: boolean;
classes?: string;
exposeToContext?: boolean;
};
schema: {};
}
Expand Down
3 changes: 2 additions & 1 deletion runner/config/custom-environment-variables.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
2 changes: 2 additions & 0 deletions runner/config/default.js
Original file line number Diff line number Diff line change
Expand Up @@ -135,4 +135,6 @@ module.exports = {
enableQueueService: false,
// queueDatabaseUrl: "mysql://root:root@localhost:3306/queue"
queueServicePollingInterval: "500",

allowUserTemplates: false,
};
63 changes: 63 additions & 0 deletions runner/src/server/forms/html-templating-example.json
Original file line number Diff line number Diff line change
@@ -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": "<p class=\"govuk-body\">This page demonstrates how templating works.</p>\n<p class=\"govuk-body\">Depending on the answer you chose for the first question, you should see different content displayed below.</p>\n<p class=\"govuk-body\">You chosen the option: {{contentToDisplay}}</p>\n{{additionalContexts.example[contentToDisplay].additionalInfo | safe}}\n<p class=\"govuk-body\">The following list will have different items</p>\n<ul class=\"govuk-list govuk-list--bullet\">\n{{additionalContexts.example[contentToDisplay].listItems | safe }}\n</ul>",
"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 }
}
1 change: 0 additions & 1 deletion runner/src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,6 @@ async function createServer(routeConfig: RouteConfig) {
WebhookService,
AddressService,
]);

if (config.enableQueueService) {
server.registerService([
QueueService,
Expand Down
8 changes: 7 additions & 1 deletion runner/src/server/plugins/engine/components/Html.ts
Original file line number Diff line number Diff line change
@@ -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) {
Expand Down
4 changes: 1 addition & 3 deletions runner/src/server/plugins/engine/components/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import joi from "joi";
import Joi from "joi";
import { add, startOfToday, sub } from "date-fns";

/**
Expand Down Expand Up @@ -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) {
Expand Down
Loading

0 comments on commit d443ec2

Please sign in to comment.