Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add selectFieldTag helper #118

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions src/plugins/default-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ export default function defaultHelpersPlugin(app: MojoApp): void {
app.addHelper('tags.linkTo', linkTo);
app.addHelper('tags.passwordField', passwordFieldTag);
app.addHelper('tags.script', scriptTag);
app.addHelper('tags.selectField', selectFieldTag);
app.addHelper('tags.style', styleTag);
app.addHelper('tags.submitButton', submitButtonTag);

Expand All @@ -98,6 +99,7 @@ export default function defaultHelpersPlugin(app: MojoApp): void {
app.addHelper('linkTo', linkTo);
app.addHelper('passwordFieldTag', passwordFieldTag);
app.addHelper('scriptTag', scriptTag);
app.addHelper('selectFieldTag', scriptTag);
app.addHelper('styleTag', styleTag);
app.addHelper('submitButtonTag', submitButtonTag);

Expand Down Expand Up @@ -301,6 +303,61 @@ function scriptTag(ctx: MojoContext, target: string, attrs: TagAttrs = {}): Prom
return ctx.tag('script', {src: ctx.urlForFile(target), ...attrs});
}

async function selectFieldTag(ctx: MojoContext, name: string, optionItems: any[], attrs: TagAttrs = {}) {
attrs.name ??= name;
const params = await ctx.params();
const selected: Record<string, boolean> = {};
for (const [n, v] of params.entries()) {
if (n !== name) continue;
selected[v] = true;
}
const considerSelectedParams = Object.keys(selected).length > 0;
const output: string[] = [];
let groupOutput: string[] = [];
let groupMode = false;
let groupAttrs: TagAttrs = {};
const stack = optionItems;
const optiongrpEnd = Symbol('option end');

while (stack.length > 0) {
const item = stack.shift();
const itemAttrs = typeof stack[0] === 'object' && !Array.isArray(stack[0]) ? stack.shift() : {};
if (item === optiongrpEnd) {
output.push(ctx.tag('optgroup', groupAttrs, new SafeString(groupOutput.join(''))));
groupOutput = [];
groupAttrs = {};
groupMode = false;
} else if (typeof item === 'string') {
itemAttrs.value ??= item;
if (considerSelectedParams) {
if (selected[itemAttrs.value]) {
itemAttrs.selected = true;
} else {
delete itemAttrs.selected;
}
}
(groupMode ? groupOutput : output).push(ctx.tag('option', itemAttrs, item));
} else if (Array.isArray(item)) {
groupAttrs = itemAttrs;
const label = item.shift();
if (typeof label === 'string' && label.length > 0) {
groupAttrs.label = label;
}
groupMode = true;
stack.unshift(optiongrpEnd);
for (const option of item.reverse()) {
if (Array.isArray(option)) {
throw new Error('Nested option groups are not allowed.');
}
stack.unshift(option);
}
} else {
throw new Error(`Unsupported data type ${ctx.inspect(item, {})}`);
}
}
return ctx.tag('select', attrs, new SafeString(output.join('')));
}

function styleTag(ctx: MojoContext, target: string, attrs: TagAttrs = {}): Promise<SafeString> {
return ctx.tag('link', {rel: 'stylesheet', href: ctx.urlForFile(target), ...attrs});
}
Expand Down
159 changes: 159 additions & 0 deletions test/plugin-app.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ t.test('Plugin app', async t => {

app.get('/tag_helpers', ctx => ctx.render({inline: tagHelperPlugin}));
app.get('/form_helpers', ctx => ctx.render({inline: formTagHelpers}));
app.put('/selection', ctx => ctx.render({inline: selectTagHelper}));

app.get('/helper', ctx => ctx.render({text: ctx.testHelper('test')}));
app.get('/nested/helper', ctx => ctx.render({text: ctx.nested.testHelper('test')}));
Expand Down Expand Up @@ -111,6 +112,151 @@ t.test('Plugin app', async t => {
fiftyfour: 'Fiftyfour'
};
(await ua.getOk('/form_helpers', {form})).statusIs(200).bodyIs(formTagHelpersFilledResult);

// Empty selection
(await ua.putOk('/selection'))
.statusIs(200)
.bodyIs(
'\n<form method="POST" action="/selection?_method=PUT">\n' +
'<select name="a">' +
'<option value="b">b</option>' +
'<optgroup label="c">' +
'<option value="&lt;d">&lt;d</option>' +
'<option value="e">E</option>' +
'<option value="f">f</option>' +
'</optgroup>' +
'<option value="g">g</option>' +
'</select>\n' +
'<select multiple="multiple" name="foo">' +
'<option value="bar">bar</option>' +
'<option value="baz">baz</option>' +
'</select>\n' +
'<select name="bar">' +
'<option value="d" disabled>D</option>' +
'<option value="baz">baz</option>' +
'</select>\n' +
'<select name="yada">' +
'<optgroup class="x" label="test">' +
'<option value="a">a</option>' +
'<option value="b">b</option>' +
'</optgroup>' +
'</select>\n' +
'<select name="h">' +
'<option value="i" selected>I</option>' +
'<option value="j">J</option>' +
'</select>\n' +
'<input value="Ok" type="submit">' +
'\n</form>\n'
);

// Selection with values
(await ua.putOk('/selection?a=e&foo=bar&bar=baz&yada=b&h=j'))
.statusIs(200)
.bodyIs(
'\n<form method="POST" action="/selection?_method=PUT">\n' +
'<select name="a">' +
'<option value="b">b</option>' +
'<optgroup label="c">' +
'<option value="&lt;d">&lt;d</option>' +
'<option value="e" selected>E</option>' +
'<option value="f">f</option>' +
'</optgroup>' +
'<option value="g">g</option>' +
'</select>\n' +
'<select multiple="multiple" name="foo">' +
'<option value="bar" selected>bar</option>' +
'<option value="baz">baz</option>' +
'</select>\n' +
'<select name="bar">' +
'<option value="d" disabled>D</option>' +
'<option value="baz" selected>baz</option>' +
'</select>\n' +
'<select name="yada">' +
'<optgroup class="x" label="test">' +
'<option value="a">a</option>' +
'<option value="b" selected>b</option>' +
'</optgroup>' +
'</select>\n' +
'<select name="h">' +
'<option value="i">I</option>' +
'<option value="j" selected>J</option>' +
'</select>\n' +
'<input value="Ok" type="submit">' +
'\n</form>\n'
);

// Selection with multiple values
(await ua.putOk('/selection?foo=bar&a=e&foo=baz&bar=d&yada=a&yada=b&h=i&h=j'))
.statusIs(200)
.bodyIs(
'\n<form method="POST" action="/selection?_method=PUT">\n' +
'<select name="a">' +
'<option value="b">b</option>' +
'<optgroup label="c">' +
'<option value="&lt;d">&lt;d</option>' +
'<option value="e" selected>E</option>' +
'<option value="f">f</option>' +
'</optgroup>' +
'<option value="g">g</option>' +
'</select>\n' +
'<select multiple="multiple" name="foo">' +
'<option value="bar" selected>bar</option>' +
'<option value="baz" selected>baz</option>' +
'</select>\n' +
'<select name="bar">' +
'<option value="d" disabled selected>D</option>' +
'<option value="baz">baz</option>' +
'</select>\n' +
'<select name="yada">' +
'<optgroup class="x" label="test">' +
'<option value="a" selected>a</option>' +
'<option value="b" selected>b</option>' +
'</optgroup>' +
'</select>\n' +
'<select name="h">' +
'<option value="i" selected>I</option>' +
'<option value="j" selected>J</option>' +
'</select>\n' +
'<input value="Ok" type="submit">' +
'\n</form>\n'
);

// Selection with multiple values preselected
// (await ua.putOk('/selection?preselect=1&undef=1'))
(await ua.putOk('/selection?a=b&a=g'))
.statusIs(200)
.bodyIs(
'\n<form method="POST" action="/selection?_method=PUT">\n' +
'<select name="a">' +
'<option value="b" selected>b</option>' +
'<optgroup label="c">' +
'<option value="&lt;d">&lt;d</option>' +
'<option value="e">E</option>' +
'<option value="f">f</option>' +
'</optgroup>' +
'<option value="g" selected>g</option>' +
'</select>\n' +
'<select multiple="multiple" name="foo">' +
'<option value="bar">bar</option>' +
'<option value="baz">baz</option>' +
'</select>\n' +
'<select name="bar">' +
'<option value="d" disabled>D</option>' +
'<option value="baz">baz</option>' +
'</select>\n' +
'<select name="yada">' +
'<optgroup class="x" label="test">' +
'<option value="a">a</option>' +
'<option value="b">b</option>' +
'</optgroup>' +
'</select>\n' +
'<select name="h">' +
'<option value="i" selected>I</option>' +
'<option value="j">J</option>' +
'</select>\n' +
'<input value="Ok" type="submit">' +
'\n</form>\n'
);
});

await t.test('Helper', async () => {
Expand Down Expand Up @@ -436,6 +582,19 @@ Button2: <form method="POST" action="/form/bar"><input value="Test2" type="submi
`;
}

const selectTagHelper = `
<{formBlock}>

%= await tags.selectField ("a", ["b", ["c", "<d", "E", {value: "e"}, "f"], "g"])
%= await tags.selectField ("foo", ["bar", "baz"], {multiple: "multiple"})
%= await tags.selectField ("bar", ['D', {value: 'd', disabled: true}, 'baz'])
%= await tags.selectField ("yada", [["test", "a", "b"], {class: 'x'}])
%= await tags.selectField ("h", ['I', {value: 'i', selected: true}, 'J', {value: 'j'}])
%= await tags.submitButton()
<{/formBlock}>
<%= await ctx.tags.formFor('selection', {}, formBlock()) %>
`;

function mixedPlugin(app) {
app.config.test = 'works';

Expand Down
Loading