-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
60 lines (57 loc) · 1.66 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
const label = (handle, display) => `<label for="${handle}">${display}</label>`;
const fields = {
input: ({ handle, display, value = "", type, required = false }) =>
`${label(
handle,
display
)}<input id="${handle}" name="${handle}" type="${type}" value="${value}" ${
required ? "required" : ""
} />`,
textarea: ({ handle, display, value = "", required = false }) =>
`${label(handle, display)}<textarea id="${handle}" name="${handle}" ${
required ? "required" : ""
}>${value}</textarea>`,
check: ({ handle, display, options, inline = false, type }) =>
`<fieldset><legend>${display}</legend>${Object.keys(options)
.map((key) => {
const display = options[key];
return `<input id="${key}" type="${type}" name="${handle}" />${label(
key,
display
)}`;
})
.join(inline ? "" : "<br/>")}</fieldset>`,
};
const renderField = ({ handle, field }) => {
const inputTypes = [
"text",
"email",
"telephone",
"time",
"week",
"url",
"range",
"password",
"number",
"month",
"hidden",
"file",
"date",
"color",
];
const checkTypes = ["checkbox", "radio"];
if (checkTypes.includes(field.type)) {
return fields["check"]({ handle, ...field });
}
if (inputTypes.includes(field.type)) {
return fields["input"]({ handle, ...field });
}
return fields["textarea"]({ handle, ...field });
};
module.exports = (eleventyConfig) => {
eleventyConfig.addShortcode("form", (fields, action) => {
return `<form action="${action ? action : ""}">${fields
.map((field) => renderField(field))
.join("")}</form>`;
});
};