markdown-up 1.5.1 → 1.7.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/lib/app.js CHANGED
@@ -4,16 +4,16 @@
4
4
  /** @module lib/app */
5
5
 
6
6
  import {ElementApplication, encodeHashID, getHashID} from 'element-app/lib/app.js';
7
+ import {MarkdownScriptRuntime, markdownScriptCodeBlock} from './script.js';
7
8
  import {decodeQueryString, encodeQueryString} from 'schema-markdown/lib/encode.js';
8
- import {getBaseURL, isRelativeURL, markdownElements} from 'markdown-model/lib/elements.js';
9
- import {UserTypeElements} from 'schema-markdown-doc/lib/userTypeElements.js';
10
- import {barChartCodeBlock} from 'markdown-charts/lib/barChart.js';
11
- import {chartModel} from 'markdown-charts/lib/model.js';
12
- import {dataTableCodeBlock} from 'markdown-charts/lib/dataTable.js';
13
- import {drawingCodeBlock} from 'markdown-charts/lib/drawing.js';
14
- import {getMarkdownTitle} from 'markdown-model/lib/markdownModel.js';
15
- import {lineChartCodeBlock} from 'markdown-charts/lib/lineChart.js';
16
- import {parseMarkdown} from 'markdown-model/lib/parser.js';
9
+ import {getBaseURL, isRelativeURL, markdownElementsAsync} from 'markdown-model/lib/elements.js';
10
+ import {getMarkdownTitle, parseMarkdown} from 'markdown-model/lib/parser.js';
11
+ import {barChartCodeBlock} from './barChart.js';
12
+ import {dataTableCodeBlock} from './dataTable.js';
13
+ import {evaluateExpression} from 'calc-script/lib/runtime.js';
14
+ import {lineChartCodeBlock} from './lineChart.js';
15
+ import {parseExpression} from 'calc-script/lib/parser.js';
16
+ import {schemaMarkdownDoc} from 'schema-markdown-doc/lib/schemaMarkdownDoc.js';
17
17
 
18
18
 
19
19
  // The application's hash parameter type model
@@ -44,8 +44,11 @@ struct MarkdownUp
44
44
  # The line height
45
45
  optional int(>= 1, <= 2) lineHeight
46
46
 
47
- # Variable collection
48
- optional FieldValue{len > 0} variables
47
+ # Variable expressions
48
+ optional string{} var
49
+
50
+ # If true, enable debug behavior
51
+ optional int(== 1) debug
49
52
 
50
53
 
51
54
  # Field value union
@@ -65,20 +68,24 @@ union FieldValue
65
68
  union Command
66
69
 
67
70
  # Display the application's hash parameter documentation
68
- HelpType help
71
+ int(== 1) help
69
72
 
70
73
  # Show the URL's Markdown text
71
74
  int(== 1) markdown
72
-
73
- # Help type enum
74
- enum HelpType
75
- Help
76
- Bar
77
- Line
78
- Table
79
75
  `;
80
76
 
81
77
 
78
+ /**
79
+ * A markdown-up application options object
80
+ *
81
+ * @typedef {Object} MarkdownUpOptions
82
+ * @param {number} [options.fontSize = 12] - The font size, in points
83
+ * @param {number} [options.lineHeight = 1.2] - The line height, in em
84
+ * @param {boolean} [options.menu = true] - If true, show the menu
85
+ * @param {string} [options.url = 'README.md'] - The resource URL
86
+ */
87
+
88
+
82
89
  /**
83
90
  * MarkdownUp, a web application for viewing Markdown files
84
91
  *
@@ -89,31 +96,40 @@ enum HelpType
89
96
  * @extends ElementApplication
90
97
  * @property {number} fontSize - The font size, in points
91
98
  * @property {number} lineHeight - The line height, in em
99
+ * @property {string} markdownText - The markdown text
92
100
  * @property {boolean} menu - If true, show the menu
93
101
  * @property {string} url - The resource URL
102
+ * @property {number} [setNavigateTimeoutId = null] - The navigate timeout ID
94
103
  */
95
104
  export class MarkdownUp extends ElementApplication {
96
105
  /**
97
106
  * Create an application instance
98
107
  *
99
108
  * @param {Object} window - The web browser window object
100
- * @param {Object} [options] - The application options
101
- * @param {number} [options.fontSize = 12] - The font size, in points
102
- * @param {number} [options.lineHeight = 1.2] - The line height, in em
103
- * @param {boolean} [options.menu = true] - If true, show the menu
104
- * @param {string} [options.url = 'README.md'] - The resource URL
109
+ * @property {module:lib/app~MarkdownUpOptions} [options] - The markdown-up application options
105
110
  */
106
- constructor(window, {
107
- fontSize = 12,
108
- lineHeight = 1.2,
109
- menu = true,
110
- url = 'README.md'
111
- } = {}) {
112
- super(window, 'markdown-up', 'MarkdownUp', markdownUpHashTypes);
111
+ constructor(window, {fontSize = 12, lineHeight = 1.2, markdownText = null, menu = true, url = 'README.md'} = {}) {
112
+ super(window, null, 'MarkdownUp', markdownUpHashTypes);
113
113
  this.fontSize = fontSize;
114
114
  this.lineHeight = lineHeight;
115
+ this.markdownText = markdownText;
115
116
  this.menu = menu;
116
117
  this.url = url;
118
+ this.setNavigateTimeoutId = null;
119
+ }
120
+
121
+ /**
122
+ * ElementApplication.render override to clear the navigate timeout
123
+ */
124
+ async render() {
125
+ // Clear the navigate timeout ID, if one is set
126
+ if (this.setNavigateTimeoutId !== null) {
127
+ this.window.clearTimeout(this.setNavigateTimeoutId);
128
+ this.setNavigateTimeoutId = null;
129
+ }
130
+
131
+ // Call the base class implementation
132
+ await super.render();
117
133
  }
118
134
 
119
135
  /**
@@ -143,17 +159,21 @@ export class MarkdownUp extends ElementApplication {
143
159
  async main() {
144
160
  // Load the text resource
145
161
  const url = 'url' in this.params ? this.params.url : this.url;
146
- let text = null;
162
+ let markdownText = null;
147
163
  let markdownModel = null;
148
164
  let markdownTitle = null;
149
165
  if (!('cmd' in this.params) || 'markdown' in this.params.cmd) {
150
- const response = await this.window.fetch(url);
151
- if (!response.ok) {
152
- const status = response.statusText;
153
- throw new Error(`Could not fetch "${url}"${status === '' ? '' : `, ${JSON.stringify(status)}`}`);
166
+ if (this.markdownText !== null && !('url' in this.params)) {
167
+ ({markdownText} = this);
168
+ } else {
169
+ const response = await this.window.fetch(url);
170
+ if (!response.ok) {
171
+ const status = response.statusText;
172
+ throw new Error(`Could not fetch "${url}"${status === '' ? '' : `, ${JSON.stringify(status)}`}`);
173
+ }
174
+ markdownText = await response.text();
154
175
  }
155
- text = await response.text();
156
- markdownModel = parseMarkdown(text);
176
+ markdownModel = parseMarkdown(markdownText);
157
177
  markdownTitle = getMarkdownTitle(markdownModel);
158
178
  }
159
179
 
@@ -162,17 +182,11 @@ export class MarkdownUp extends ElementApplication {
162
182
  if ('cmd' in this.params) {
163
183
  // Display markdown?
164
184
  if ('markdown' in this.params.cmd) {
165
- cmdElements = {'html': 'div', 'attr': {'class': 'markdown'}, 'elem': {'text': text}};
185
+ cmdElements = {'html': 'div', 'attr': {'class': 'markdown'}, 'elem': {'text': markdownText}};
166
186
 
167
187
  // Help
168
- } else if (this.params.cmd.help === 'Bar') {
169
- cmdElements = new UserTypeElements(this.params).getElements(chartModel.types, `BarChart`);
170
- } else if (this.params.cmd.help === 'Line') {
171
- cmdElements = new UserTypeElements(this.params).getElements(chartModel.types, `LineChart`);
172
- } else if (this.params.cmd.help === 'Table') {
173
- cmdElements = new UserTypeElements(this.params).getElements(chartModel.types, `DataTable`);
174
188
  } else {
175
- cmdElements = new UserTypeElements(this.params).getElements(this.hashTypes, this.hashType);
189
+ cmdElements = schemaMarkdownDoc(this.hashTypes, this.hashType, {'params': encodeQueryString(this.params)});
176
190
  }
177
191
  }
178
192
 
@@ -213,14 +227,69 @@ export class MarkdownUp extends ElementApplication {
213
227
  return `#${encodeQueryString(params)}`;
214
228
  };
215
229
 
230
+ // The URL modifier function
231
+ const urlFn = (rawURL) => {
232
+ // Hash URL?
233
+ if (rawURL.startsWith('#')) {
234
+ // Fixup the "url" param if its relative
235
+ const hashParams = decodeQueryString(rawURL.slice(1));
236
+ if ('url' in hashParams && isRelativeURL(hashParams.url)) {
237
+ hashParams.url = `${getBaseURL(url)}${hashParams.url}`;
238
+ }
239
+
240
+ // Return the combined hash URL
241
+ return encodeHashID({...this.params, ...hashParams}, getHashID(rawURL));
242
+ }
243
+
244
+ // Relative URL?
245
+ if (isRelativeURL(rawURL)) {
246
+ return `${getBaseURL(url)}${rawURL}`;
247
+ }
248
+
249
+ return rawURL;
250
+ };
251
+
252
+ // The log function
253
+ const logFn = (text) => {
254
+ if ('debug' in this.params) {
255
+ this.window.console.log(text);
256
+ }
257
+ };
258
+
259
+ // The fetch function
260
+ // eslint-disable-next-line require-await
261
+ const fetchFn = async (fetchURL, init) => this.window.fetch(urlFn(fetchURL), init);
262
+
263
+ // The navigate timeout function
264
+ const navigateTimeoutFn = (navigateURL, delay) => {
265
+ const timeoutCallback = () => {
266
+ this.window.location.href = urlFn(navigateURL);
267
+ };
268
+ this.setNavigateTimeoutId = this.window.setTimeout(timeoutCallback, delay);
269
+ };
270
+ // eslint-disable-next-line lines-around-comment
271
+
216
272
  // Render the text as Markdown
217
- const chartOptions = {
218
- 'fontSize': 0.9 * (this.params !== null && 'fontSize' in this.params ? this.params.fontSize : this.fontSize),
219
- url,
220
- 'variables': 'variables' in this.params ? this.params.variables : {},
221
- 'window': this.window
273
+ const fontSize = 0.9 * (this.params !== null && 'fontSize' in this.params ? this.params.fontSize : this.fontSize);
274
+ const scriptOptions = {
275
+ fetchFn,
276
+ fontSize,
277
+ 'localStorage': this.window.localStorage,
278
+ logFn,
279
+ navigateTimeoutFn,
280
+ 'params': this.params,
281
+ 'sessionStorage': this.window.sessionStorage,
282
+ urlFn
222
283
  };
223
- return {
284
+ if ('var' in this.params) {
285
+ scriptOptions.variables = {};
286
+ for (const varName of Object.keys(this.params.var)) {
287
+ const varExpr = parseExpression(this.params.var[varName]);
288
+ scriptOptions.variables[varName] = evaluateExpression(varExpr, scriptOptions.variables);
289
+ }
290
+ }
291
+ scriptOptions.runtime = new MarkdownScriptRuntime(scriptOptions);
292
+ const result = {
224
293
  'title': markdownTitle,
225
294
  'elements': [
226
295
  // Command?
@@ -231,27 +300,15 @@ export class MarkdownUp extends ElementApplication {
231
300
  ? null : {'html': 'div', 'attr': {'id': encodeQueryString(this.params), 'style': 'display=none'}},
232
301
 
233
302
  // Render the markdown
234
- cmdElements !== null ? null : markdownElements(markdownModel, {
303
+ cmdElements !== null ? null : await markdownElementsAsync(markdownModel, {
235
304
  'codeBlocks': {
236
- 'bar-chart': (language, lines) => barChartCodeBlock(language, lines, chartOptions),
237
- 'data-table': (language, lines) => dataTableCodeBlock(language, lines, chartOptions),
238
- 'drawing': (language, lines) => drawingCodeBlock(language, lines, chartOptions),
239
- 'line-chart': (language, lines) => lineChartCodeBlock(language, lines, chartOptions)
305
+ 'bar-chart': (language, lines) => barChartCodeBlock(language, lines, scriptOptions),
306
+ 'data-table': (language, lines) => dataTableCodeBlock(language, lines, scriptOptions),
307
+ 'line-chart': (language, lines) => lineChartCodeBlock(language, lines, scriptOptions),
308
+ 'markdown-script': (language, lines) => markdownScriptCodeBlock(language, lines, scriptOptions)
240
309
  },
241
- 'hashFn': (hashURL) => {
242
- // Decode the hash params
243
- const hashParams = decodeQueryString(hashURL.slice(1));
244
-
245
- // Fixup the "url" param if its relative
246
- if ('url' in hashParams && isRelativeURL(hashParams.url)) {
247
- hashParams.url = `${getBaseURL(url)}${hashParams.url}`;
248
- }
249
-
250
- // Return the combined hash URL
251
- return encodeHashID({...this.params, ...hashParams}, getHashID(hashURL));
252
- },
253
- 'headerIds': true,
254
- url
310
+ urlFn,
311
+ 'headerIds': true
255
312
  }),
256
313
 
257
314
  // Popup menu burger
@@ -274,7 +331,7 @@ export class MarkdownUp extends ElementApplication {
274
331
  'elem': [
275
332
  {
276
333
  'html': 'a',
277
- 'attr': {'href': linkCommandToggle('markdown', 1), 'aria-label': 'Show Markdown'},
334
+ 'attr': {'href': linkCommandToggle('markdown', '1'), 'aria-label': 'Show Markdown'},
278
335
  'elem': markdownSVGElements
279
336
  },
280
337
  {
@@ -289,13 +346,20 @@ export class MarkdownUp extends ElementApplication {
289
346
  },
290
347
  {
291
348
  'html': 'a',
292
- 'attr': {'href': linkCommandToggle('help', 'Help'), 'aria-label': 'Help'},
349
+ 'attr': {'href': linkCommandToggle('help', '1'), 'aria-label': 'Help'},
293
350
  'elem': helpSVGElements
294
351
  }
295
352
  ]
296
353
  }
297
354
  ]
298
355
  };
356
+
357
+ // Set document title?
358
+ if (scriptOptions.runtime.documentTitle !== null) {
359
+ result.title = scriptOptions.runtime.documentTitle;
360
+ }
361
+
362
+ return result;
299
363
  }
300
364
  }
301
365
 
@@ -0,0 +1,34 @@
1
+ // Licensed under the MIT License
2
+ // https://github.com/craigahobbs/markdown-up/blob/main/LICENSE
3
+
4
+ /** @module lib/barChart */
5
+
6
+ import {chartCodeBlock} from './util.js';
7
+ import {loadChartData} from './data.js';
8
+ import {validateBarChart} from './model.js';
9
+
10
+
11
+ /**
12
+ * Bar chart code block function
13
+ *
14
+ * @param {string} language - The code block language
15
+ * @param {string[]} lines - The code block's text lines
16
+ * @param {module:lib/util~MarkdownScriptOptions} [options=null] - Markdown script options
17
+ * @returns {Object} The bar chart element model
18
+ */
19
+ export function barChartCodeBlock(language, lines, options = null) {
20
+ return chartCodeBlock(language, lines, options, validateBarChart, barChartElements);
21
+ }
22
+
23
+
24
+ /**
25
+ * Render a bar chart
26
+ *
27
+ * @param {Object} barChart - The bar chart model
28
+ * @param {module:lib/util~MarkdownScriptOptions} [options=null] - Markdown script options
29
+ * @returns {Object} The bar chart element model
30
+ */
31
+ export async function barChartElements(barChart, options = null) {
32
+ const {data} = await loadChartData(barChart, options);
33
+ return {'html': 'pre', 'elem': {'text': JSON.stringify(data, null, 4)}};
34
+ }
package/lib/csv.js ADDED
@@ -0,0 +1,59 @@
1
+ // Licensed under the MIT License
2
+ // https://github.com/craigahobbs/markdown-up/blob/main/LICENSE
3
+
4
+ /** @module lib/csv */
5
+
6
+
7
+ /**
8
+ * Parse CSV text to a JSON data array
9
+ *
10
+ * @param {string} text - The CSV text
11
+ * @returns {Object[]}
12
+ */
13
+ export function parseCSV(text) {
14
+ const data = [];
15
+ const splitLines = text.split(rCSVLineSplit).map((line) => line.replace(rCSVLineScrub, '$1').split(rCSVFieldSplit));
16
+ const [fields] = splitLines;
17
+ for (let ixLine = 1; ixLine < splitLines.length; ixLine += 1) {
18
+ const splitLine = splitLines[ixLine];
19
+ if (splitLine.length > 1 || splitLine[0] !== '') {
20
+ data.push(Object.fromEntries(fields.map(
21
+ (field, ixField) => [field, ixField < splitLine.length ? splitLine[ixField] : 'null']
22
+ )));
23
+ }
24
+ }
25
+ return data;
26
+ }
27
+
28
+ const rCSVLineSplit = /\r?\n/;
29
+ const rCSVLineScrub = /^"?(.*?)"?$/;
30
+ const rCSVFieldSplit = /"?,"?/;
31
+
32
+
33
+ /**
34
+ * Parse a CSV number
35
+ */
36
+ export function parseCSVNumber(text) {
37
+ const value = Number.parseFloat(text);
38
+ if (Number.isNaN(value) || !Number.isFinite(value)) {
39
+ return null;
40
+ }
41
+ return value;
42
+ }
43
+
44
+
45
+ /**
46
+ * Parse a CSV datetime
47
+ */
48
+ export function parseCSVDatetime(text) {
49
+ if (rCSVDate.test(text)) {
50
+ const localDate = new Date(text);
51
+ return new Date(localDate.getUTCFullYear(), localDate.getUTCMonth(), localDate.getUTCDate());
52
+ } else if (rCSVDatetime.test(text)) {
53
+ return new Date(text);
54
+ }
55
+ return null;
56
+ }
57
+
58
+ const rCSVDate = /^\d{4}-\d{2}-\d{2}$/;
59
+ const rCSVDatetime = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?(?:Z|[+-]\d{2}:\d{2})$/;