markdown-up 1.5.0 → 1.7.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/lib/app.js CHANGED
@@ -4,13 +4,16 @@
4
4
  /** @module lib/app */
5
5
 
6
6
  import {ElementApplication, encodeHashID, getHashID} from 'element-app/lib/app.js';
7
- import {barChartCodeBlock, dataTableCodeBlock, lineChartCodeBlock} from 'markdown-charts/lib/codeBlock.js';
7
+ import {MarkdownScriptRuntime, markdownScriptCodeBlock} from './script.js';
8
8
  import {decodeQueryString, encodeQueryString} from 'schema-markdown/lib/encode.js';
9
- import {getBaseURL, isRelativeURL, markdownElements} from 'markdown-model/lib/elements.js';
9
+ import {getBaseURL, isRelativeURL, markdownElementsAsync} from 'markdown-model/lib/elements.js';
10
+ import {getMarkdownTitle, parseMarkdown} from 'markdown-model/lib/parser.js';
10
11
  import {UserTypeElements} from 'schema-markdown-doc/lib/userTypeElements.js';
11
- import {chartModel} from 'markdown-charts/lib/model.js';
12
- import {getMarkdownTitle} from 'markdown-model/lib/markdownModel.js';
13
- import {parseMarkdown} from 'markdown-model/lib/parser.js';
12
+ import {barChartCodeBlock} from './barChart.js';
13
+ import {dataTableCodeBlock} from './dataTable.js';
14
+ import {evaluateExpression} from 'calc-script/lib/runtime.js';
15
+ import {lineChartCodeBlock} from './lineChart.js';
16
+ import {parseExpression} from 'calc-script/lib/parser.js';
14
17
 
15
18
 
16
19
  // The application's hash parameter type model
@@ -41,8 +44,11 @@ struct MarkdownUp
41
44
  # The line height
42
45
  optional int(>= 1, <= 2) lineHeight
43
46
 
44
- # Variable collection
45
- optional FieldValue{len > 0} variables
47
+ # Variable expressions
48
+ optional string{} var
49
+
50
+ # If true, enable debug behavior
51
+ optional int(== 1) debug
46
52
 
47
53
 
48
54
  # Field value union
@@ -62,20 +68,24 @@ union FieldValue
62
68
  union Command
63
69
 
64
70
  # Display the application's hash parameter documentation
65
- HelpType help
71
+ int(== 1) help
66
72
 
67
73
  # Show the URL's Markdown text
68
74
  int(== 1) markdown
69
-
70
- # Help type enum
71
- enum HelpType
72
- Help
73
- Bar
74
- Line
75
- Table
76
75
  `;
77
76
 
78
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
+
79
89
  /**
80
90
  * MarkdownUp, a web application for viewing Markdown files
81
91
  *
@@ -86,31 +96,40 @@ enum HelpType
86
96
  * @extends ElementApplication
87
97
  * @property {number} fontSize - The font size, in points
88
98
  * @property {number} lineHeight - The line height, in em
99
+ * @property {string} markdownText - The markdown text
89
100
  * @property {boolean} menu - If true, show the menu
90
101
  * @property {string} url - The resource URL
102
+ * @property {number} [setNavigateTimeoutId = null] - The navigate timeout ID
91
103
  */
92
104
  export class MarkdownUp extends ElementApplication {
93
105
  /**
94
106
  * Create an application instance
95
107
  *
96
108
  * @param {Object} window - The web browser window object
97
- * @param {Object} [options] - The application options
98
- * @param {number} [options.fontSize = 12] - The font size, in points
99
- * @param {number} [options.lineHeight = 1.2] - The line height, in em
100
- * @param {boolean} [options.menu = true] - If true, show the menu
101
- * @param {string} [options.url = 'README.md'] - The resource URL
109
+ * @property {module:lib/app~MarkdownUpOptions} [options] - The markdown-up application options
102
110
  */
103
- constructor(window, {
104
- fontSize = 12,
105
- lineHeight = 1.2,
106
- menu = true,
107
- url = 'README.md'
108
- } = {}) {
109
- 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);
110
113
  this.fontSize = fontSize;
111
114
  this.lineHeight = lineHeight;
115
+ this.markdownText = markdownText;
112
116
  this.menu = menu;
113
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();
114
133
  }
115
134
 
116
135
  /**
@@ -140,17 +159,21 @@ export class MarkdownUp extends ElementApplication {
140
159
  async main() {
141
160
  // Load the text resource
142
161
  const url = 'url' in this.params ? this.params.url : this.url;
143
- let text = null;
162
+ let markdownText = null;
144
163
  let markdownModel = null;
145
164
  let markdownTitle = null;
146
165
  if (!('cmd' in this.params) || 'markdown' in this.params.cmd) {
147
- const response = await this.window.fetch(url);
148
- if (!response.ok) {
149
- const status = response.statusText;
150
- 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();
151
175
  }
152
- text = await response.text();
153
- markdownModel = parseMarkdown(text);
176
+ markdownModel = parseMarkdown(markdownText);
154
177
  markdownTitle = getMarkdownTitle(markdownModel);
155
178
  }
156
179
 
@@ -159,15 +182,9 @@ export class MarkdownUp extends ElementApplication {
159
182
  if ('cmd' in this.params) {
160
183
  // Display markdown?
161
184
  if ('markdown' in this.params.cmd) {
162
- cmdElements = {'html': 'div', 'attr': {'class': 'markdown'}, 'elem': {'text': text}};
185
+ cmdElements = {'html': 'div', 'attr': {'class': 'markdown'}, 'elem': {'text': markdownText}};
163
186
 
164
187
  // Help
165
- } else if (this.params.cmd.help === 'Bar') {
166
- cmdElements = new UserTypeElements(this.params).getElements(chartModel.types, `BarChart`);
167
- } else if (this.params.cmd.help === 'Line') {
168
- cmdElements = new UserTypeElements(this.params).getElements(chartModel.types, `LineChart`);
169
- } else if (this.params.cmd.help === 'Table') {
170
- cmdElements = new UserTypeElements(this.params).getElements(chartModel.types, `DataTable`);
171
188
  } else {
172
189
  cmdElements = new UserTypeElements(this.params).getElements(this.hashTypes, this.hashType);
173
190
  }
@@ -210,14 +227,69 @@ export class MarkdownUp extends ElementApplication {
210
227
  return `#${encodeQueryString(params)}`;
211
228
  };
212
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
+
213
272
  // Render the text as Markdown
273
+ const fontSize = 0.9 * (this.params !== null && 'fontSize' in this.params ? this.params.fontSize : this.fontSize);
214
274
  const chartOptions = {
215
- 'fontSize': 0.9 * (this.params !== null && 'fontSize' in this.params ? this.params.fontSize : this.fontSize),
216
- url,
217
- 'variables': 'variables' in this.params ? this.params.variables : {},
218
- 'window': this.window
275
+ fetchFn,
276
+ fontSize,
277
+ 'localStorage': this.window.localStorage,
278
+ logFn,
279
+ navigateTimeoutFn,
280
+ 'params': this.params,
281
+ 'sessionStorage': this.window.sessionStorage,
282
+ urlFn
219
283
  };
220
- return {
284
+ if ('var' in this.params) {
285
+ chartOptions.variables = {};
286
+ for (const varName of Object.keys(this.params.var)) {
287
+ const varExpr = parseExpression(this.params.var[varName]);
288
+ chartOptions.variables[varName] = evaluateExpression(varExpr, chartOptions.variables);
289
+ }
290
+ }
291
+ chartOptions.runtime = new MarkdownScriptRuntime(chartOptions);
292
+ const result = {
221
293
  'title': markdownTitle,
222
294
  'elements': [
223
295
  // Command?
@@ -228,26 +300,15 @@ export class MarkdownUp extends ElementApplication {
228
300
  ? null : {'html': 'div', 'attr': {'id': encodeQueryString(this.params), 'style': 'display=none'}},
229
301
 
230
302
  // Render the markdown
231
- cmdElements !== null ? null : markdownElements(markdownModel, {
303
+ cmdElements !== null ? null : await markdownElementsAsync(markdownModel, {
232
304
  'codeBlocks': {
233
305
  'bar-chart': (language, lines) => barChartCodeBlock(language, lines, chartOptions),
234
306
  'data-table': (language, lines) => dataTableCodeBlock(language, lines, chartOptions),
235
- 'line-chart': (language, lines) => lineChartCodeBlock(language, lines, chartOptions)
236
- },
237
- 'hashFn': (hashURL) => {
238
- // Decode the hash params
239
- const hashParams = decodeQueryString(hashURL.slice(1));
240
-
241
- // Fixup the "url" param if its relative
242
- if ('url' in hashParams && isRelativeURL(hashParams.url)) {
243
- hashParams.url = `${getBaseURL(url)}${hashParams.url}`;
244
- }
245
-
246
- // Return the combined hash URL
247
- return encodeHashID({...this.params, ...hashParams}, getHashID(hashURL));
307
+ 'line-chart': (language, lines) => lineChartCodeBlock(language, lines, chartOptions),
308
+ 'markdown-script': (language, lines) => markdownScriptCodeBlock(language, lines, chartOptions)
248
309
  },
249
- 'headerIds': true,
250
- url
310
+ urlFn,
311
+ 'headerIds': true
251
312
  }),
252
313
 
253
314
  // Popup menu burger
@@ -268,6 +329,11 @@ export class MarkdownUp extends ElementApplication {
268
329
  'html': 'div',
269
330
  'attr': {'class': 'menu'},
270
331
  'elem': [
332
+ {
333
+ 'html': 'a',
334
+ 'attr': {'href': linkCommandToggle('markdown', '1'), 'aria-label': 'Show Markdown'},
335
+ 'elem': markdownSVGElements
336
+ },
271
337
  {
272
338
  'html': 'a',
273
339
  'attr': {'href': linkCycle('fontSize', this.fontSize, 2), 'aria-label': 'Font size'},
@@ -280,18 +346,15 @@ export class MarkdownUp extends ElementApplication {
280
346
  },
281
347
  {
282
348
  'html': 'a',
283
- 'attr': {'href': linkCommandToggle('markdown', 1), 'aria-label': 'Show Markdown'},
284
- 'elem': markdownSVGElements
285
- },
286
- {
287
- 'html': 'a',
288
- 'attr': {'href': linkCommandToggle('help', 'Help'), 'aria-label': 'Help'},
349
+ 'attr': {'href': linkCommandToggle('help', '1'), 'aria-label': 'Help'},
289
350
  'elem': helpSVGElements
290
351
  }
291
352
  ]
292
353
  }
293
354
  ]
294
355
  };
356
+
357
+ return result;
295
358
  }
296
359
  }
297
360
 
@@ -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})$/;