@tryghost/mg-shortcodes 0.1.1

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2013-2022 Ghost Foundation
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 ADDED
@@ -0,0 +1,65 @@
1
+ # Shortcodes
2
+
3
+ This package wraps the excellent [universal-shortcodes](https://github.com/EvidentlyCube/universal-shortcodes), and adds utility functions to make adding support for shortcodes easier between different tools. It typecasts attribute values (string, int, float, bool) and handles encoded quotes (_pretty quotes_) that sometimes wrap attributes.
4
+
5
+ Unhandled shortcodes are returned without modification.
6
+
7
+ ## Install
8
+
9
+ `npm install @tryghost/mg-shortcodes --save`
10
+
11
+ or
12
+
13
+ `yarn add @tryghost/mg-shortcodes`
14
+
15
+
16
+ ## Usage
17
+
18
+ ```js
19
+ // Import the class
20
+ import Shortcodes from '@tryghost/mg-shortcodes';
21
+
22
+ // Create a new instance
23
+ const ShortcodeParser = new Shortcodes();
24
+
25
+ // Handle [link] shortcodes
26
+ shortcodes.add('link', ({attrs, content}) => {
27
+ return `<a href="${attrs.url}">${content}</a>`;
28
+ });
29
+
30
+ // Unwrap [block] shortcodes
31
+ shortcodes.unwrap('block');
32
+
33
+ // You can add & unwrap as many shortcodes as you like. The order is not important.
34
+
35
+ const content = `[block][link url="https://example.com"]Hello[/link][/block]`;
36
+
37
+ // Parse the content and return the updated content
38
+ const updatedContent = shortcodes.parse(content);
39
+ // <a href="https://example.com">Hello</a>
40
+ ```
41
+
42
+ ## Develop
43
+
44
+ This is a mono repository, managed with [lerna](https://lernajs.io/).
45
+
46
+ Follow the instructions for the top-level repo.
47
+ 1. `git clone` this repo & `cd` into it as usual
48
+ 2. Run `yarn` to install top-level dependencies.
49
+
50
+
51
+ ## Run
52
+
53
+ - `yarn dev`
54
+
55
+
56
+ ## Test
57
+
58
+ - `yarn lint` run just eslint
59
+ - `yarn test` run lint and tests
60
+ - `yarn benchmark` run benchmarks
61
+
62
+
63
+ # Copyright & License
64
+
65
+ Copyright (c) 2013-2022 Ghost Foundation - Released under the [MIT license](LICENSE).
package/index.js ADDED
@@ -0,0 +1,3 @@
1
+ import {Shortcodes} from './lib/Shortcodes.js';
2
+
3
+ export default Shortcodes;
@@ -0,0 +1,188 @@
1
+ class Shortcodes {
2
+ constructor() {
3
+ this.shortcodes = [];
4
+ this.html = '';
5
+ }
6
+
7
+ add(name, callback) {
8
+ this.shortcodes.push({name, callback});
9
+ }
10
+
11
+ unwrap(name) {
12
+ this.shortcodes.push({name, callback: ({content}) => {
13
+ return `${content} `;
14
+ }});
15
+ }
16
+
17
+ unwrapFromQuotes(string) {
18
+ const chars = ['’', '”', '“', '‘', '"'];
19
+ const quoteRegExp = new RegExp(`^(${chars.join('|')})|(${chars.join('|')})$`, 'gm');
20
+ return string.replace(quoteRegExp, '');
21
+ }
22
+
23
+ parseAttributes(attributesString) {
24
+ const tagAttrRegExp = new RegExp(`([\\w-]+)\\s*=\\s*"([^"]*)"(?:\\s|$)|([\\w-]+)\\s*=\\s*'([^']*)'(?:\\s|$)|([\\w-]+)\\s*=\\s*([^\\s'"]+)(?:\\s|$)|"([^"]*)"(?:\\s|$)|'([^']*)'(?:\\s|$)|(\\S+)(?:\\s|$)`, 'gmi');
25
+
26
+ const tagAttrMatches = [...RegExp.prototype[Symbol.matchAll].call(tagAttrRegExp, attributesString)];
27
+
28
+ let attributes = {};
29
+
30
+ tagAttrMatches.forEach((item) => {
31
+ let theKey;
32
+ let theValue;
33
+ if (item[1] && item[2]) {
34
+ // Quoted key="value" pairs
35
+ theKey = item[1];
36
+ theValue = this.typeCast(item[2]);
37
+ } else if (item[5] && item[6]) {
38
+ // Unquoted key=value pairs
39
+ theKey = item[5];
40
+ theValue = this.typeCast(item[6]);
41
+ } else if (item[9]) {
42
+ // Either a bool `someboolkey` of fallback `Study”="true"`
43
+ if (item[9].includes('=')) {
44
+ let parts = item[9].split('=');
45
+ theKey = parts[0];
46
+ theValue = parts[1];
47
+ } else {
48
+ theKey = item[9];
49
+ theValue = true;
50
+ }
51
+ }
52
+
53
+ theKey = this.unwrapFromQuotes(theKey);
54
+
55
+ if (typeof theValue === 'string') {
56
+ theValue = this.unwrapFromQuotes(theValue);
57
+ }
58
+
59
+ attributes[theKey] = this.typeCast(theValue);
60
+ });
61
+
62
+ return attributes;
63
+ }
64
+
65
+ typeCast(value) {
66
+ // Not supported type values
67
+ if (typeof value !== 'number' && typeof value !== 'boolean' && typeof value !== 'string') {
68
+ return value;
69
+ }
70
+
71
+ if (typeof value === 'string' && !value.trim()) {
72
+ return value;
73
+ }
74
+
75
+ if (typeof value === 'boolean') {
76
+ return value;
77
+ }
78
+
79
+ if (typeof value === 'string' && value.trim() === 'true') {
80
+ return true;
81
+ }
82
+
83
+ if (typeof value === 'string' && value.trim() === 'false') {
84
+ return false;
85
+ }
86
+
87
+ if (/^\d+$/.test(value)) {
88
+ // Is positive int
89
+ return parseInt(value, 10);
90
+ } else if (/^\d+\.\d+$/.test(value)) {
91
+ // Is positive float
92
+ return parseFloat(value);
93
+ } else if (/^(true|false)$/.test(value)) {
94
+ // Is bool?
95
+ return value === 'true';
96
+ } else if (/^-\d+$/.test(value)) {
97
+ // Is negative int
98
+ return parseFloat(value);
99
+ } else if (/^-\d+\.\d+$/.test(value)) {
100
+ // Is negative float
101
+ return parseFloat(value);
102
+ }
103
+
104
+ return value.toString();
105
+ }
106
+
107
+ hasKnownShortcode(text) {
108
+ if (!text) {
109
+ return false;
110
+ }
111
+
112
+ let result = false;
113
+
114
+ this.shortcodes.forEach((shortcode) => {
115
+ if (result && result.length) {
116
+ return result;
117
+ }
118
+
119
+ let shortcodeName = shortcode.name;
120
+
121
+ let shortcodeRegExp = new RegExp(`\\[${shortcodeName}(?<attrs>\\s[\\s\\S]*?)?\\](?:(?<content>(?!\\\\s*?(?:\\[${shortcodeName}|\\[\\/(?!${shortcodeName})))[\\s\\S]*?)(\\[\\/${shortcodeName}\\]))?`, 'm');
122
+
123
+ let match = text.match(shortcodeRegExp);
124
+
125
+ if (match && match.length) {
126
+ let sub = this.hasKnownShortcode(match.groups.content);
127
+
128
+ if (sub && sub.length) {
129
+ result = {
130
+ name: shortcodeName,
131
+ match: sub
132
+ };
133
+ } else {
134
+ result = {
135
+ name: shortcodeName,
136
+ match: match
137
+ };
138
+ }
139
+ }
140
+ });
141
+
142
+ return (result) ? result : false;
143
+ }
144
+
145
+ getCallback(name) {
146
+ if (!name) {
147
+ return false;
148
+ }
149
+
150
+ let thisThing = this.shortcodes.filter(n => n.name === name);
151
+
152
+ return thisThing[0].callback;
153
+ }
154
+
155
+ process() {
156
+ let text = this.html;
157
+
158
+ let knownShortcode = this.hasKnownShortcode(text);
159
+
160
+ if (knownShortcode) {
161
+ const theCall = this.getCallback(knownShortcode.name);
162
+ const attrs = this.parseAttributes(knownShortcode.match.groups.attrs);
163
+ const content = knownShortcode.match.groups.content;
164
+
165
+ if (theCall) {
166
+ text = text.replace(knownShortcode.match[0], theCall({attrs, content}));
167
+ this.html = text;
168
+ }
169
+ }
170
+
171
+ return this.html;
172
+ }
173
+
174
+ parse(html) {
175
+ this.html = html;
176
+
177
+ // Keep looping all the time a known shortcode is found in the content
178
+ while (this.hasKnownShortcode(this.html)) {
179
+ this.process();
180
+ }
181
+
182
+ return this.html;
183
+ }
184
+ }
185
+
186
+ export {
187
+ Shortcodes
188
+ };
package/package.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "@tryghost/mg-shortcodes",
3
+ "version": "0.1.1",
4
+ "repository": "https://github.com/TryGhost/migrate/tree/main/packages/mg-shortcodes",
5
+ "author": "Ghost Foundation",
6
+ "license": "MIT",
7
+ "main": "index.js",
8
+ "type": "module",
9
+ "scripts": {
10
+ "dev": "echo \"Implement me!\"",
11
+ "test": "node --experimental-vm-modules $(yarn bin jest)",
12
+ "lint": "eslint . --ext .js --cache",
13
+ "posttest": "yarn lint"
14
+ },
15
+ "files": [
16
+ "index.js",
17
+ "lib"
18
+ ],
19
+ "publishConfig": {
20
+ "access": "public"
21
+ },
22
+ "devDependencies": {
23
+ "eslint": "8.29.0",
24
+ "jest": "29.3.1",
25
+ "jest-extended": "3.2.0"
26
+ },
27
+ "gitHead": "f5a6a06ad2eb953bda77b11359ed135482d9dfc7"
28
+ }