@schreibtischhelden/showdown-forms 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +122 -2
- package/index.d.ts +33 -0
- package/index.mjs +4 -0
- package/package.json +45 -5
- package/showdown-forms.js +290 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Tobias Fichtner
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,123 @@
|
|
|
1
|
-
#
|
|
1
|
+
# showdown-forms
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://github.com/schreibtischhelden/showdown-forms/actions/workflows/ci.yml)
|
|
4
|
+
|
|
5
|
+
A [Showdown](https://github.com/showdownjs/showdown) 2.x extension that turns simple `:::form` blocks in Markdown into HTML forms.
|
|
6
|
+
|
|
7
|
+
```text
|
|
8
|
+
:::form action="https://example.com/submit" method="post"
|
|
9
|
+
Name* = ___
|
|
10
|
+
E-Mail* = ___:email
|
|
11
|
+
Message = [___]:5
|
|
12
|
+
Contact via = (x) e-mail () phone
|
|
13
|
+
Topics = [x] Support [] Sales [] Other
|
|
14
|
+
Country = {Germany, (Austria), ch -> Switzerland}
|
|
15
|
+
[[ Send ]]
|
|
16
|
+
:::
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
The syntax is inspired by the original [showdown-forms](https://github.com/runvnc/showdown-forms) (based on [wmd](https://github.com/maleldil/wmd)). This package is a rewrite: it does not bundle its own Markdown parser, only touches `:::form` blocks, and escapes everything it outputs.
|
|
20
|
+
|
|
21
|
+
## Installation
|
|
22
|
+
|
|
23
|
+
```sh
|
|
24
|
+
npm install showdown @schreibtischhelden/showdown-forms
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Or in the browser, after Showdown (registers the extension as `forms` and the global `showdownForms`):
|
|
28
|
+
|
|
29
|
+
```html
|
|
30
|
+
<script src="https://cdn.jsdelivr.net/npm/showdown@2.1.0/dist/showdown.min.js"></script>
|
|
31
|
+
<script src="https://cdn.jsdelivr.net/npm/@schreibtischhelden/showdown-forms@1/showdown-forms.js"></script>
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Usage
|
|
35
|
+
|
|
36
|
+
```javascript
|
|
37
|
+
import showdown from 'showdown';
|
|
38
|
+
import showdownForms from '@schreibtischhelden/showdown-forms';
|
|
39
|
+
|
|
40
|
+
const converter = new showdown.Converter({ extensions: [showdownForms()] });
|
|
41
|
+
const html = converter.makeHtml(markdown);
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
CommonJS works as well: `const showdownForms = require('@schreibtischhelden/showdown-forms');`.
|
|
45
|
+
In the browser: `new showdown.Converter({ extensions: ['forms'] })`.
|
|
46
|
+
|
|
47
|
+
## Syntax
|
|
48
|
+
|
|
49
|
+
| Line | Field |
|
|
50
|
+
| :--- | :--- |
|
|
51
|
+
| `Label = ___` | Text input |
|
|
52
|
+
| `Label = ___:email` | Input with type `email`, `tel`, `number`, `date`, `time`, `url` or `password` |
|
|
53
|
+
| `Label = [___]` / `[___]:5` | Textarea (optional number of rows, default 4) |
|
|
54
|
+
| `Label = (x) a () b` | Radio buttons, `(x)` is preselected |
|
|
55
|
+
| `Label = [x] a [] b` | Checkboxes, `[x]` is checked |
|
|
56
|
+
| `Label = {a, (b), v -> Label}` | Select, `(b)` is preselected, `v -> Label` sets a different value |
|
|
57
|
+
| `Label* = ...` | Required field (for checkboxes only the label is marked) |
|
|
58
|
+
| `[[ Send ]]` | Submit button |
|
|
59
|
+
|
|
60
|
+
- The block starts with `:::form` on its own line and ends with `:::`. Fenced code blocks are left alone.
|
|
61
|
+
- The field `name` is the label in lowercase with `_` instead of spaces, limited to letters, digits, `_` and `-` (`E-Mail` → `e-mail`, `Contact via` → `contact_via`).
|
|
62
|
+
- Ids are `<idPrefix>-<n>` for the form and `<idPrefix>-<n>-<line>` for fields, so several forms and option groups never collide.
|
|
63
|
+
- Lines that are not a field are shown as escaped text. Markdown is not processed inside the block.
|
|
64
|
+
- `action` may be a relative URL, `http(s):` or `mailto:`; other schemes (`javascript:`, `data:` …) and protocol-relative URLs are dropped. `method` is `get` or `post` (default `post`).
|
|
65
|
+
|
|
66
|
+
## Options
|
|
67
|
+
|
|
68
|
+
```javascript
|
|
69
|
+
showdownForms({ idPrefix: 'contact', dataPrefix: 'mdp' });
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
| Option | Default | Description |
|
|
73
|
+
| :--- | :--- | :--- |
|
|
74
|
+
| `idPrefix` | `sdf-form` | Prefix of the generated ids |
|
|
75
|
+
| `dataPrefix` | `sdf` | Prefix of the data attributes (`data-sdf-form`, `data-sdf-name`) and of the submit event (`sdf:form-submit`) |
|
|
76
|
+
|
|
77
|
+
## Forms without `action`
|
|
78
|
+
|
|
79
|
+
A form without `action` gets `data-sdf-form="local"`. With `listen()` such forms never navigate away; submitting dispatches a bubbling `sdf:form-submit` event instead:
|
|
80
|
+
|
|
81
|
+
```javascript
|
|
82
|
+
import { listen } from '@schreibtischhelden/showdown-forms';
|
|
83
|
+
|
|
84
|
+
const stop = listen(document); // returns a function that removes the listener
|
|
85
|
+
document.addEventListener('sdf:form-submit', (event) => {
|
|
86
|
+
console.log(event.target.id, Object.fromEntries(event.detail.data));
|
|
87
|
+
});
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
## Using a sanitizer
|
|
91
|
+
|
|
92
|
+
The extension escapes all labels and values, but Showdown still passes through raw HTML written in the rest of the Markdown. If the Markdown is not fully trusted, sanitize the output, e.g. with [DOMPurify](https://github.com/cure53/DOMPurify).
|
|
93
|
+
|
|
94
|
+
DOMPurify removes `name` attributes that equal a document or form property (e.g. `name="name"`) to prevent DOM clobbering. Every generated field carries its name in `data-sdf-name` as well; `restoreNames()` puts it back after the HTML has been inserted (only names made of letters, digits, `_` and `-`):
|
|
95
|
+
|
|
96
|
+
```javascript
|
|
97
|
+
import { restoreNames } from '@schreibtischhelden/showdown-forms';
|
|
98
|
+
|
|
99
|
+
container.innerHTML = DOMPurify.sanitize(converter.makeHtml(markdown));
|
|
100
|
+
restoreNames(container);
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
## Other helpers
|
|
104
|
+
|
|
105
|
+
- `render(body, { attributes, id, idPrefix, dataPrefix })` renders the lines of a single block to HTML.
|
|
106
|
+
- `escapeHtml(value)` is the escaping function used everywhere.
|
|
107
|
+
|
|
108
|
+
## Development
|
|
109
|
+
|
|
110
|
+
```sh
|
|
111
|
+
npm install
|
|
112
|
+
npm test
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
## Releasing
|
|
116
|
+
|
|
117
|
+
1. Set the new version in `package.json` and add it to `CHANGELOG.md`.
|
|
118
|
+
2. Commit, then tag and push: `git tag v1.2.3 && git push origin v1.2.3`.
|
|
119
|
+
3. The [Release workflow](.github/workflows/release.yml) runs the tests and publishes to npm with provenance (npm Trusted Publishing; the secret `NPM_TOKEN` is only a fallback).
|
|
120
|
+
|
|
121
|
+
## License
|
|
122
|
+
|
|
123
|
+
[MIT](LICENSE)
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export interface ShowdownFormsOptions {
|
|
2
|
+
/** Prefix of the generated form ids, default "sdf-form". */
|
|
3
|
+
idPrefix?: string;
|
|
4
|
+
/** Prefix of the data attributes and the submit event, default "sdf". */
|
|
5
|
+
dataPrefix?: string;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface RenderOptions extends ShowdownFormsOptions {
|
|
9
|
+
/** Attributes as written after ":::form", e.g. 'action="/send" method="get"'. */
|
|
10
|
+
attributes?: string;
|
|
11
|
+
/** Id of the form element. */
|
|
12
|
+
id?: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface ShowdownLangExtension {
|
|
16
|
+
type: 'lang';
|
|
17
|
+
filter: (text: string) => string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
declare function showdownForms(options?: ShowdownFormsOptions): ShowdownLangExtension[];
|
|
21
|
+
|
|
22
|
+
declare namespace showdownForms {
|
|
23
|
+
function render(body: string, options?: RenderOptions): string;
|
|
24
|
+
function restoreNames(root: ParentNode, options?: Pick<ShowdownFormsOptions, 'dataPrefix'>): void;
|
|
25
|
+
function listen(target: EventTarget, options?: Pick<ShowdownFormsOptions, 'dataPrefix'>): () => void;
|
|
26
|
+
function escapeHtml(value: unknown): string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export default showdownForms;
|
|
30
|
+
export declare const render: typeof showdownForms.render;
|
|
31
|
+
export declare const restoreNames: typeof showdownForms.restoreNames;
|
|
32
|
+
export declare const listen: typeof showdownForms.listen;
|
|
33
|
+
export declare const escapeHtml: typeof showdownForms.escapeHtml;
|
package/index.mjs
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,46 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@schreibtischhelden/showdown-forms",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Showdown extension: HTML forms from simple :::form blocks in Markdown, with escaping and safe defaults.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"showdown",
|
|
7
|
+
"showdown-extension",
|
|
8
|
+
"markdown",
|
|
9
|
+
"forms"
|
|
10
|
+
],
|
|
11
|
+
"homepage": "https://github.com/schreibtischhelden/showdown-forms#readme",
|
|
12
|
+
"bugs": "https://github.com/schreibtischhelden/showdown-forms/issues",
|
|
13
|
+
"repository": {
|
|
14
|
+
"type": "git",
|
|
15
|
+
"url": "git+https://github.com/schreibtischhelden/showdown-forms.git"
|
|
16
|
+
},
|
|
17
|
+
"license": "MIT",
|
|
18
|
+
"author": "Tobias Fichtner",
|
|
19
|
+
"main": "./showdown-forms.js",
|
|
20
|
+
"types": "./index.d.ts",
|
|
21
|
+
"exports": {
|
|
22
|
+
".": {
|
|
23
|
+
"types": "./index.d.ts",
|
|
24
|
+
"import": "./index.mjs",
|
|
25
|
+
"require": "./showdown-forms.js"
|
|
26
|
+
},
|
|
27
|
+
"./package.json": "./package.json"
|
|
28
|
+
},
|
|
29
|
+
"files": [
|
|
30
|
+
"showdown-forms.js",
|
|
31
|
+
"index.mjs",
|
|
32
|
+
"index.d.ts"
|
|
33
|
+
],
|
|
34
|
+
"engines": {
|
|
35
|
+
"node": ">=20"
|
|
36
|
+
},
|
|
37
|
+
"scripts": {
|
|
38
|
+
"test": "node --test"
|
|
39
|
+
},
|
|
40
|
+
"peerDependencies": {
|
|
41
|
+
"showdown": "^2.0.0"
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"showdown": "^2.1.0"
|
|
45
|
+
}
|
|
46
|
+
}
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
* showdown-forms - Markdown form blocks for Showdown 2.x
|
|
3
|
+
* https://github.com/schreibtischhelden/showdown-forms
|
|
4
|
+
* MIT License
|
|
5
|
+
*/
|
|
6
|
+
(function (root, factory) {
|
|
7
|
+
if (typeof module === 'object' && module.exports) {
|
|
8
|
+
module.exports = factory();
|
|
9
|
+
} else if (typeof define === 'function' && define.amd) {
|
|
10
|
+
define([], factory);
|
|
11
|
+
} else {
|
|
12
|
+
root.showdownForms = factory();
|
|
13
|
+
if (root.showdown && typeof root.showdown.extension === 'function') {
|
|
14
|
+
root.showdown.extension('forms', root.showdownForms);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
})(typeof self !== 'undefined' ? self : this, function () {
|
|
18
|
+
'use strict';
|
|
19
|
+
|
|
20
|
+
// :::form action="https://example.com/submit" method="post"
|
|
21
|
+
// Name* = ___
|
|
22
|
+
// E-Mail* = ___:email
|
|
23
|
+
// Message = [___]:5
|
|
24
|
+
// Contact via = (x) e-mail () phone
|
|
25
|
+
// Topics = [x] Support [] Sales
|
|
26
|
+
// Country = {Germany, (Austria), ch -> Switzerland}
|
|
27
|
+
// [[ Send ]]
|
|
28
|
+
// :::
|
|
29
|
+
//
|
|
30
|
+
// Every label and value ends up in an attribute or text node and is
|
|
31
|
+
// HTML-escaped. Without "action" the form is not sent anywhere.
|
|
32
|
+
|
|
33
|
+
var INPUT_TYPES = ['text', 'email', 'tel', 'number', 'date', 'time', 'url', 'password'];
|
|
34
|
+
// fenced code blocks are matched too, so that they can be skipped
|
|
35
|
+
var FORM_BLOCK = /(^|\n)(```|~~~)[^\n]*\n[\s\S]*?\n\2[ \t]*(?=\n|$)|(^|\n):::form([^\n]*)\n([\s\S]*?)\n:::[ \t]*(?=\n|$)/g;
|
|
36
|
+
var SAFE_ACTION = /^(https?:|mailto:|[^:]*$)/i; // http(s), mailto, or no scheme at all
|
|
37
|
+
var SAFE_NAME = /^[\p{L}\p{N}_-]+$/u;
|
|
38
|
+
|
|
39
|
+
var DEFAULTS = {
|
|
40
|
+
// prefix of the generated form ids: <idPrefix>-<n>, fields <idPrefix>-<n>-<line>
|
|
41
|
+
idPrefix: 'sdf-form',
|
|
42
|
+
// prefix of the data attributes (data-<dataPrefix>-form, data-<dataPrefix>-name)
|
|
43
|
+
// and of the submit event (<dataPrefix>:form-submit)
|
|
44
|
+
dataPrefix: 'sdf',
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
function resolveOptions(options) {
|
|
48
|
+
var result = {};
|
|
49
|
+
Object.keys(DEFAULTS).forEach(function (key) {
|
|
50
|
+
var value = options && options[key];
|
|
51
|
+
result[key] = typeof value === 'string' && /^[a-z][a-z0-9-]*$/i.test(value) ? value : DEFAULTS[key];
|
|
52
|
+
});
|
|
53
|
+
return result;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function escapeHtml(value) {
|
|
57
|
+
return String(value)
|
|
58
|
+
.replace(/&/g, '&')
|
|
59
|
+
.replace(/</g, '<')
|
|
60
|
+
.replace(/>/g, '>')
|
|
61
|
+
.replace(/"/g, '"')
|
|
62
|
+
.replace(/'/g, ''');
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function fieldName(label) {
|
|
66
|
+
return label.trim().toLowerCase().replace(/\s+/g, '_').replace(/[^\p{L}\p{N}_-]/gu, '') || 'field';
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function parseFormAttributes(text) {
|
|
70
|
+
var attrs = {};
|
|
71
|
+
// fixed keywords and at most one space around "=" keep this linear (no ReDoS)
|
|
72
|
+
text.replace(/\b(action|method)\s?=\s?"([^"]*)"/gi, function (match, key, value) {
|
|
73
|
+
attrs[key.toLowerCase()] = value.trim();
|
|
74
|
+
return match;
|
|
75
|
+
});
|
|
76
|
+
var result = {};
|
|
77
|
+
var action = attrs.action;
|
|
78
|
+
// eslint-disable-next-line no-control-regex
|
|
79
|
+
if (action && !/^\/\//.test(action) && !/[\u0000-\u001f\u007f]/.test(action) && SAFE_ACTION.test(action)) {
|
|
80
|
+
result.action = action;
|
|
81
|
+
}
|
|
82
|
+
result.method = /^(get|post)$/i.test(attrs.method || '') ? attrs.method.toLowerCase() : 'post';
|
|
83
|
+
return result;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function nameAttrs(name, opts) {
|
|
87
|
+
var escaped = escapeHtml(name);
|
|
88
|
+
return ' name="' + escaped + '" data-' + opts.dataPrefix + '-name="' + escaped + '"';
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function renderChoices(type, pattern, value, labelText, name, id, req, opts) {
|
|
92
|
+
var html = '<fieldset><legend>' + labelText + '</legend>';
|
|
93
|
+
var i = 0;
|
|
94
|
+
value.replace(pattern, function (match, checked, text) {
|
|
95
|
+
var optionId = id + '-' + (i++);
|
|
96
|
+
var optionText = text.trim();
|
|
97
|
+
html += '<label for="' + optionId + '">'
|
|
98
|
+
+ '<input type="' + type + '" id="' + optionId + '"' + nameAttrs(name, opts)
|
|
99
|
+
+ ' value="' + escapeHtml(optionText) + '"' + (checked ? ' checked' : '') + req + '> '
|
|
100
|
+
+ escapeHtml(optionText) + '</label>';
|
|
101
|
+
return match;
|
|
102
|
+
});
|
|
103
|
+
return html + '</fieldset>';
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function renderField(rawLabel, required, value, id, opts) {
|
|
107
|
+
var label = rawLabel.trim();
|
|
108
|
+
var name = fieldName(label);
|
|
109
|
+
var req = required ? ' required' : '';
|
|
110
|
+
var labelText = escapeHtml(label) + (required ? ' <span aria-hidden="true">*</span>' : '');
|
|
111
|
+
var match;
|
|
112
|
+
|
|
113
|
+
// text input: ___ or ___:email
|
|
114
|
+
if ((match = /^___(?::([a-z]+))?$/.exec(value))) {
|
|
115
|
+
var type = INPUT_TYPES.indexOf(match[1]) >= 0 ? match[1] : 'text';
|
|
116
|
+
return '<label for="' + id + '">' + labelText + '</label>'
|
|
117
|
+
+ '<input type="' + type + '" id="' + id + '"' + nameAttrs(name, opts) + req + '>';
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// textarea: [___] or [___]:5
|
|
121
|
+
if ((match = /^\[___\](?::(\d{1,2}))?$/.exec(value))) {
|
|
122
|
+
var rows = match[1] ? Math.max(1, parseInt(match[1], 10)) : 4;
|
|
123
|
+
return '<label for="' + id + '">' + labelText + '</label>'
|
|
124
|
+
+ '<textarea id="' + id + '"' + nameAttrs(name, opts) + ' rows="' + rows + '"' + req + '></textarea>';
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// radio buttons: (x) one () two
|
|
128
|
+
if (/^\(x?\)/.test(value)) {
|
|
129
|
+
return renderChoices('radio', /\((x?)\)\s*([^()]+)/g, value, labelText, name, id, req, opts);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// checkboxes: [x] one [] two
|
|
133
|
+
if (/^\[x?\]/.test(value)) {
|
|
134
|
+
// "required" on every checkbox would force all of them - only the label is marked
|
|
135
|
+
return renderChoices('checkbox', /\[(x?)\]\s*([^[\]]+)/g, value, labelText, name, id, '', opts);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// select: {a, (b), value -> Label}
|
|
139
|
+
if ((match = /^\{(.+)\}$/.exec(value))) {
|
|
140
|
+
var options = match[1].split(',').map(function (option) {
|
|
141
|
+
option = option.trim();
|
|
142
|
+
var selected = /^\(.*\)$/.test(option);
|
|
143
|
+
if (selected) {
|
|
144
|
+
option = option.slice(1, -1).trim();
|
|
145
|
+
}
|
|
146
|
+
var parts = option.split('->');
|
|
147
|
+
var optValue = parts[0].trim();
|
|
148
|
+
var optLabel = (parts.length > 1 ? parts.slice(1).join('->') : parts[0]).trim();
|
|
149
|
+
return '<option value="' + escapeHtml(optValue) + '"' + (selected ? ' selected' : '') + '>'
|
|
150
|
+
+ escapeHtml(optLabel) + '</option>';
|
|
151
|
+
}).join('');
|
|
152
|
+
return '<label for="' + id + '">' + labelText + '</label>'
|
|
153
|
+
+ '<select id="' + id + '"' + nameAttrs(name, opts) + req + '>' + options + '</select>';
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
return null;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function renderForm(attrText, body, formId, opts) {
|
|
160
|
+
var attrs = parseFormAttributes(attrText || '');
|
|
161
|
+
var html = '<form id="' + formId + '" method="' + attrs.method + '"'
|
|
162
|
+
+ (attrs.action ? ' action="' + escapeHtml(attrs.action) + '"' : ' data-' + opts.dataPrefix + '-form="local"') + '>';
|
|
163
|
+
String(body || '').split('\n').forEach(function (line, index) {
|
|
164
|
+
line = line.trim();
|
|
165
|
+
if (!line) {
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
// line parsing uses string operations instead of regexes (no ReDoS on long lines)
|
|
169
|
+
if (line.length > 4 && line.slice(0, 2) === '[[' && line.slice(-2) === ']]') {
|
|
170
|
+
var buttonText = line.slice(2, -2).trim();
|
|
171
|
+
if (buttonText) {
|
|
172
|
+
html += '<button type="submit">' + escapeHtml(buttonText) + '</button>';
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
var rendered = null;
|
|
177
|
+
var eq = line.indexOf('=');
|
|
178
|
+
if (eq > 0) {
|
|
179
|
+
var label = line.slice(0, eq).trim();
|
|
180
|
+
var required = label.slice(-1) === '*';
|
|
181
|
+
if (required) {
|
|
182
|
+
label = label.slice(0, -1).trim();
|
|
183
|
+
}
|
|
184
|
+
var value = line.slice(eq + 1).trim();
|
|
185
|
+
if (label && value) {
|
|
186
|
+
rendered = renderField(label, required, value, formId + '-' + index, opts);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
// anything else is shown as plain (escaped) text
|
|
190
|
+
html += rendered !== null ? rendered : '<p>' + escapeHtml(line) + '</p>';
|
|
191
|
+
});
|
|
192
|
+
return html + '</form>';
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Creates the Showdown extension.
|
|
197
|
+
*
|
|
198
|
+
* const converter = new showdown.Converter({ extensions: [showdownForms()] });
|
|
199
|
+
*
|
|
200
|
+
* @param {{idPrefix?: string, dataPrefix?: string}} [options]
|
|
201
|
+
* @returns {Array<{type: 'lang', filter: function(string): string}>}
|
|
202
|
+
*/
|
|
203
|
+
function showdownForms(options) {
|
|
204
|
+
var opts = resolveOptions(options);
|
|
205
|
+
var counter = 0;
|
|
206
|
+
return [{
|
|
207
|
+
type: 'lang',
|
|
208
|
+
filter: function (text) {
|
|
209
|
+
return text.replace(/\r\n?/g, '\n').replace(FORM_BLOCK, function (match, pre1, fence, pre2, attrs, body) {
|
|
210
|
+
if (fence) {
|
|
211
|
+
return match; // leave fenced code blocks untouched
|
|
212
|
+
}
|
|
213
|
+
var formId = opts.idPrefix + '-' + (++counter);
|
|
214
|
+
return (pre2 || '') + '\n' + renderForm(attrs, body, formId, opts) + '\n\n';
|
|
215
|
+
});
|
|
216
|
+
},
|
|
217
|
+
}];
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Renders the body of a single form block (the lines between ":::form" and ":::").
|
|
222
|
+
*
|
|
223
|
+
* @param {string} body
|
|
224
|
+
* @param {{attributes?: string, id?: string, idPrefix?: string, dataPrefix?: string}} [options]
|
|
225
|
+
* @returns {string} HTML
|
|
226
|
+
*/
|
|
227
|
+
function render(body, options) {
|
|
228
|
+
var opts = resolveOptions(options);
|
|
229
|
+
var formId = options && typeof options.id === 'string' && /^[a-z][\w-]*$/i.test(options.id) ? options.id : opts.idPrefix + '-1';
|
|
230
|
+
return renderForm(options && options.attributes, body, formId, opts);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Sanitizers such as DOMPurify drop name attributes that equal a document
|
|
235
|
+
* or form property (e.g. name="name") to prevent DOM clobbering. The name of
|
|
236
|
+
* a generated field is derived from its label and only contains letters,
|
|
237
|
+
* digits, "_" and "-", so it is restored from data-<dataPrefix>-name.
|
|
238
|
+
* Call this after inserting sanitized HTML into the page.
|
|
239
|
+
*
|
|
240
|
+
* @param {ParentNode} root
|
|
241
|
+
* @param {{dataPrefix?: string}} [options]
|
|
242
|
+
*/
|
|
243
|
+
function restoreNames(root, options) {
|
|
244
|
+
var attr = 'data-' + resolveOptions(options).dataPrefix + '-name';
|
|
245
|
+
var selector = ['input', 'textarea', 'select'].map(function (tag) {
|
|
246
|
+
return 'form ' + tag + '[' + attr + ']';
|
|
247
|
+
}).join(', ');
|
|
248
|
+
Array.prototype.forEach.call(root.querySelectorAll(selector), function (field) {
|
|
249
|
+
var name = field.getAttribute(attr);
|
|
250
|
+
if (SAFE_NAME.test(name)) {
|
|
251
|
+
field.setAttribute('name', name);
|
|
252
|
+
}
|
|
253
|
+
field.removeAttribute(attr);
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Forms without "action" never navigate away: submitting them dispatches a
|
|
259
|
+
* bubbling "<dataPrefix>:form-submit" event with detail { data: FormData }.
|
|
260
|
+
*
|
|
261
|
+
* @param {Document|Element} target where the submit listener is attached
|
|
262
|
+
* @param {{dataPrefix?: string}} [options]
|
|
263
|
+
* @returns {function(): void} removes the listener again
|
|
264
|
+
*/
|
|
265
|
+
function listen(target, options) {
|
|
266
|
+
var prefix = resolveOptions(options).dataPrefix;
|
|
267
|
+
var handler = function (event) {
|
|
268
|
+
var form = event.target;
|
|
269
|
+
if (form && form.getAttribute && form.getAttribute('data-' + prefix + '-form') === 'local') {
|
|
270
|
+
event.preventDefault();
|
|
271
|
+
form.dispatchEvent(new CustomEvent(prefix + ':form-submit', {
|
|
272
|
+
bubbles: true,
|
|
273
|
+
detail: { data: new FormData(form) },
|
|
274
|
+
}));
|
|
275
|
+
}
|
|
276
|
+
};
|
|
277
|
+
target.addEventListener('submit', handler);
|
|
278
|
+
return function () {
|
|
279
|
+
target.removeEventListener('submit', handler);
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
showdownForms.render = render;
|
|
284
|
+
showdownForms.restoreNames = restoreNames;
|
|
285
|
+
showdownForms.listen = listen;
|
|
286
|
+
showdownForms.escapeHtml = escapeHtml;
|
|
287
|
+
showdownForms.default = showdownForms;
|
|
288
|
+
|
|
289
|
+
return showdownForms;
|
|
290
|
+
});
|