@elvishscout/mdstory 0.1.2 → 0.1.3

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/README.md CHANGED
@@ -1,5 +1,295 @@
1
1
  # MdStory
2
2
 
3
- An interactive story format based on Markdown and Handlebars with JavaScript support.
3
+ An interactive fiction scripting format based on Markdown and Handlebars.
4
4
 
5
- Online demo available on <https://mdstory.elvish.cc>.
5
+ Online demo: <https://mdstory.elvish.cc>
6
+
7
+ ## Features
8
+
9
+ - Seamless intergration of Markdown, Handlebars and JavaScript.
10
+ - Ease-to-use API, for both Web and command line applications.
11
+
12
+ ## File Format
13
+
14
+ ### Metadata
15
+
16
+ The story file header may include YAML-formatted [Metadata](#type-metadata). Metadata defines the basic information and global configuration of the story.
17
+
18
+ ### Chapters
19
+
20
+ Story files are divided into chapters by level-one headings. The `id` attribute of the heading serves as the unique identifier (`id`) for the chapter. If omitted, the heading content is used as the chapter `id` instead.
21
+
22
+ Handlebars template language is supported in the chapter content. During rendering, properties in `globals` and `assets` are added to the context for direct access by the template.
23
+
24
+ ### Helpers
25
+
26
+ MdStory includes built-in Handlebars helpers for creating interactive components or various functionalities:
27
+
28
+ #### `{{input type name=default}}`
29
+
30
+ Creates an input of type `type` and assigns the input value (by default `default`) to a global variable named `name`. Supported input types include: `string`, `number`, `boolean`, and `object` (represented in a JSON string).
31
+
32
+ In HTML rendering mode, it generates a corresponding `<input>` element.
33
+
34
+ #### `{{set name=value}}`
35
+
36
+ Assigns the value `value` to a global variable named `name`.
37
+
38
+ #### `{{#nav target}}`
39
+
40
+ Creates an entry to navigate to another chapter identified by `target`.
41
+
42
+ In HTML rendering mode, it generates a corresponding `<button type="submit">` element.
43
+
44
+ #### `{{linebreak [n]}}`
45
+
46
+ Inserts `n` blank lines, where `n` defaults to `1`.
47
+
48
+ #### `{{asset name}}`
49
+
50
+ Retrieves the URL of a resource file named `name`. Basically it acts the same way as `{{name}}` except that it supports resource names with special characters.
51
+
52
+ #### `{{mime name}}`
53
+
54
+ Retrieves the MIME type of a resource file named `name`.
55
+
56
+ ### JavaScript Scripts
57
+
58
+ JavaScript may be included into the story file using the `<script>` tag. Scripts before any level-one headings are considered global scripts, while those within chapters are considered chapter scripts. Only one `<script>` tag is allowed at the beginning of the story and in each chapter.
59
+
60
+ Scripts are evaluated during runtime using the `Function()` constructor, therefore you may use top-level `return` statements to return objects of type [StoryHooks](#type-storyhooks) or [ChapterHooks](#type-chapterhooks).
61
+
62
+ ### Stylesheets
63
+
64
+ CSS stylesheets may be included using the `<style>` tag, they will be extracted and gathered into the `stylesheet` property of [StoryBody](#type-storybody) during parsing.
65
+
66
+ ## Examples
67
+
68
+ Here are some [examples](./examples/) of story files.
69
+
70
+ ## API
71
+
72
+ ### `type Value`
73
+
74
+ The type of variables in MdStory, basically all types allowed in JSON, including primitive values (`string`, `number`, `boolean`, `null`) and nested `array`s and `object`s. Functions and `undefined` are not supported.
75
+
76
+ ### `type Scope`
77
+
78
+ An object of variable values by their names, used to store global variables or input fields.
79
+
80
+ ### `type Asset`
81
+
82
+ A referenceable resource file.
83
+
84
+ #### Properties
85
+
86
+ - `url`: The URL of the resource.
87
+ - `mime (optional)`: The MIME type of the resource.
88
+
89
+ ### `type Metadata`
90
+
91
+ The Metadata of the story.
92
+
93
+ #### Properties
94
+
95
+ - `title (optional)`: The story title.
96
+ - `author (optional)`: The author's name.
97
+ - `email (optional)`: The author's email address.
98
+ - `globals (optional)`: An object of type [Scope](#type-scope) containing initial values of global variables.
99
+ - `assets (optional)`: An object of resource names and [Asset](#type-asset) objects, containing all assets used in the story.
100
+
101
+ ### `type ChapterBody`
102
+
103
+ The structured representation of chapter content.
104
+
105
+ #### Properties
106
+
107
+ - `title`: The chapter title.
108
+ - `template`: The Handlebars template for rendering.
109
+ - `script`: The JavaScript script for the chapter.
110
+
111
+ ### `type StoryBody`
112
+
113
+ The structured representation of story content.
114
+
115
+ #### Properties
116
+
117
+ - `metadata`: The story [Metadata](#type-metadata).
118
+ - `chapters`: An object of [ChapterBody](#type-chapterbody) objects by their `id`s.
119
+ - `entry`: The `id` of the entry chapter of the story, which may be `null`.
120
+ - `script`: The global JavaScript script of the story.
121
+ - `stylesheet`: The global stylesheet of the story.
122
+
123
+ ### `type StoryHooks`
124
+
125
+ Defines the global lifecycle hooks of the story.
126
+
127
+ #### Properties
128
+
129
+ - `onStart (optional)`: Called when the story starts.
130
+ - Parameters:
131
+ - `globals`: The initial values of global variables.
132
+ - Return value: Updated `globals` or `void`.
133
+
134
+ ### `type ChapterHooks`
135
+
136
+ Defines the lifecycle hooks of a chapter.
137
+
138
+ #### Properties
139
+
140
+ - `onEnter (optional)`: Called when entering a chapter.
141
+ - Parameters:
142
+ - `globals`: Current global variables.
143
+ - Return value: Updated `globals` or `void`, effective only during the lifecycle of current chapter.
144
+ - `onLeave (optional)`: Called when leaving a chapter.
145
+ - Parameters:
146
+ - `globals`: Current global variables.
147
+ - `fields`: Input fields from current chapter.
148
+ - Return value: Updated `globals` or `void`.
149
+ - `onNavigate (optional)`: Called during chapter navigation.
150
+ - Parameters:
151
+ - `target` : `id` of target chapter.
152
+ - `globals`: Current global variables.
153
+ - `fields`: Input fields from current chapter.
154
+ - Return value: Updated `target` or `void`.
155
+
156
+ ### `type Renderer`
157
+
158
+ Defines the renderer interface for generating outputs in different formats.
159
+
160
+ #### Methods
161
+
162
+ - `input({ name, type, value }) (optional)`: Generates the rendering result of an input field.
163
+
164
+ - Parameters:
165
+ - `name`: The name of the variable.
166
+ - `type`: The type of the variable.
167
+ - `value`: The default value of the variable.
168
+ - Return value: The rendered input field.
169
+
170
+ - `nav({ target, children }) (optional)`: Generates the rendering result of chapter navigation.
171
+ - Parameters:
172
+ - `target`: The `id` of the target chapter.
173
+ - `children`: The text content of the navigation button.
174
+ - Return value: The rendered navigation button.
175
+
176
+ ### `type RenderOptions`
177
+
178
+ Defines rendering options.
179
+
180
+ #### Properties
181
+
182
+ - `format`: The rendering format, which may be `"markdown"`, `"html"`, or a custom [Renderer](#type-renderer).
183
+ - `html (optional)`: Whether to parse Markdown into HTML, defaults to `false`.
184
+
185
+ ### `type RenderResult`
186
+
187
+ The rendering result, containing the rendered text and extracted fields.
188
+
189
+ #### Properties
190
+
191
+ - `text`: The rendered text content.
192
+ - `inputs`: An array of input fields, each containing:
193
+ - `name`: The name of the variable.
194
+ - `type`: The type of the variable.
195
+ - `value`: The default value of the variable.
196
+ - `sets`: An array of set fields, each containing:
197
+ - `name`: The name of the variable.
198
+ - `type`: The type of the variable.
199
+ - `value`: The value of the variable.
200
+ - `navs`: An array of navigation fields, each containing:
201
+ - `text`: The text content of the navigation button.
202
+ - `target`: The `id` of the target chapter.
203
+
204
+ ### `type ChapterOptions`
205
+
206
+ Defines the initialization options of a chapter.
207
+
208
+ #### Properties
209
+
210
+ - `id`: The unique identifier of the chapter.
211
+ - `title`: The title of the chapter.
212
+ - `template`: The Handlebars template for rendering.
213
+ - `hooks`: An object of type [ChapterHooks](#type-chapterhooks).
214
+
215
+ ### `class Chapter`
216
+
217
+ Defines a chapter.
218
+
219
+ #### Properties
220
+
221
+ - `id`: The unique identifier of the chapter.
222
+ - `title`: The title of the chapter.
223
+ - `template`: The Handlebars template for rendering.
224
+ - `hooks`: Chapter hooks of type [ChapterHooks](#type-chapterhooks).
225
+
226
+ #### Methods
227
+
228
+ - `constructor(options)`: Initializes the chapter instance.
229
+ - Parameters:
230
+ - `options`: The chapter options of type [ChapterOptions](#type-chapteroptions).
231
+ - `render(scope, assets, options)`: Renders the story content.
232
+ - Parameters:
233
+ - `scope`: The rendering context.
234
+ - `assets`: The story assets.
235
+ - `options`: The rendering options of type [RenderOptions](#type-renderoptions).
236
+ - Return value: The rendering result of type [RenderResult](#type-renderresult).
237
+
238
+ ### `type StoryPrompt`
239
+
240
+ Defines the prompt function of the story, used to handle user input.
241
+
242
+ #### Parameters
243
+
244
+ - `props`: An object containing the current chapter and rendering result.
245
+ - `chapter`: Current chapter.
246
+ - `text`: The rendered chapter content.
247
+ - `inputs`, `sets`, `navs`: Fields from the rendering result.
248
+
249
+ #### Return value
250
+
251
+ - A `Promise` resolving to one of the following forms:
252
+ - `{ target, updates }`: The `id` of the target chapter and updated global variables.
253
+ - `FormData`: Contains the form data of user input.
254
+
255
+ ### `class StoryBase`
256
+
257
+ Defines the base class of the story, containing the core logic of the story.
258
+
259
+ #### Properties
260
+
261
+ - `metadata`: Story [Metadata](#type-metadata).
262
+ - `globals`: Global variables.
263
+ - `chapters`: An object of chapters by their `id`s.
264
+ - `entry`: The entry chapter of the story.
265
+ - `hooks`: An object of type [StoryHooks](#type-storyhooks).
266
+ - `stylesheet`: The global stylesheet of the story.
267
+ - `assets`: An object of asset files by their alias names.
268
+
269
+ #### Methods
270
+
271
+ - `constructor({ metadata, chapters, entry, script, stylesheet })`: Initializes the story instance.
272
+ - `play(prompt, options)`: Starts playing the story.
273
+ - Parameters:
274
+ - `prompt`: A function of type [StoryPrompt](#type-storyprompt).
275
+ - `options`: An object of type [RenderOptions](#type-renderoptions).
276
+
277
+ ### `function parseStoryContent`
278
+
279
+ Parses the story content in Markdown format.
280
+
281
+ #### Parameters
282
+
283
+ - `content`: The story content in Markdown format.
284
+
285
+ #### Return value
286
+
287
+ - An object of type [StoryBody](#type-storybody).
288
+
289
+ ### `class Story`
290
+
291
+ Inherits from [StoryBase](#class-storybase), creating a story instance from the story content in Markdown format.
292
+
293
+ #### Methods
294
+
295
+ - `constructor(content: string)`: Initializes the story instance.
@@ -1,6 +1,7 @@
1
1
  import Handlebars from "handlebars";
2
2
  import MarkdownIt from "markdown-it";
3
3
  import pluginAttrs from "markdown-it-attrs";
4
+ const escapeHtml = (text) => text.replace(/[<>&'"]/g, (ch) => `&#${ch.charCodeAt(0)};`);
4
5
  const valueType = (value) => {
5
6
  if (typeof value === "string") {
6
7
  return "string";
@@ -13,7 +14,6 @@ const valueType = (value) => {
13
14
  }
14
15
  return "object";
15
16
  };
16
- const escapeHtml = (text) => text.replace(/[<>&'"]/g, (ch) => `&#${ch.charCodeAt(0)};`);
17
17
  const createElementHtml = (tag, attrs, children) => {
18
18
  // prettier-ignore
19
19
  const voidTags = [
@@ -21,61 +21,75 @@ const createElementHtml = (tag, attrs, children) => {
21
21
  "link", "meta", "param", "source", "track", "wbr",
22
22
  ];
23
23
  const attrText = Object.entries(attrs)
24
- .filter(([, value]) => value !== undefined)
25
24
  .map(([name, value]) => {
26
25
  if (typeof value === "boolean") {
27
26
  value = value ? "" : undefined;
28
27
  }
29
- const escapedValue = escapeHtml(value ?? "");
30
- return `${name}="${escapedValue}"`;
28
+ if (value === undefined) {
29
+ return null;
30
+ }
31
+ if (value) {
32
+ const escapedValue = escapeHtml(value ?? "");
33
+ return `${name}="${escapedValue}"`;
34
+ }
35
+ else {
36
+ return name;
37
+ }
31
38
  })
39
+ .filter((attr) => attr !== null)
32
40
  .join(" ");
33
41
  if (voidTags.includes(tag)) {
34
42
  return `<${tag} ${attrText}>`;
35
43
  }
36
44
  return `<${tag} ${attrText}>${children ?? ""}</${tag}>`;
37
45
  };
38
- const createInputHtml = ({ tagMap = {}, name, type, value, required, readonly, }) => {
39
- const tag = tagMap["input"] ?? "input";
46
+ const createInputHtml = ({ name, type, value }) => {
40
47
  const inputType = type === "boolean" ? "checkbox" : "text";
41
48
  const inputAttrs = {
42
49
  name,
43
50
  type: inputType,
44
51
  value: inputType !== "checkbox" ? (type === "object" ? JSON.stringify(value) : String(value)) : undefined,
45
52
  checked: inputType === "checkbox" && value ? "" : undefined,
46
- required,
47
- readonly,
48
53
  "aria-label": name,
49
54
  };
50
- return createElementHtml(tag, inputAttrs);
55
+ return createElementHtml("input", inputAttrs);
51
56
  };
52
- const createSubmitButtonHtml = ({ tagMap = {}, target, children, }) => {
53
- const tag = tagMap["button"] ?? "button";
57
+ const createSubmitButtonHtml = ({ target, children }) => {
54
58
  const buttonAttrs = {
55
59
  name: "@target",
56
60
  type: "submit",
57
61
  value: target,
58
62
  };
59
- return createElementHtml(tag, buttonAttrs, children);
63
+ return createElementHtml("button", buttonAttrs, children);
60
64
  };
61
- const useHelper = ({ inputs, sets, navs }, assets, options) => {
65
+ const markdownRenderer = {
66
+ input({ name, type }) {
67
+ if (type === "boolean") {
68
+ return `[? _${name}_]`;
69
+ }
70
+ else {
71
+ return `[> _${name}_]`;
72
+ }
73
+ },
74
+ nav({ children }) {
75
+ return `[@ __${children}__]`;
76
+ },
77
+ };
78
+ const htmlRenderer = {
79
+ input({ type, name, value }) {
80
+ return createInputHtml({ name, type, value });
81
+ },
82
+ nav({ target, children }) {
83
+ return createSubmitButtonHtml({ target: target ?? "", children });
84
+ },
85
+ };
86
+ const useHelper = ({ inputs, sets, navs }, assets, renderer) => {
62
87
  return {
63
88
  input(type, opt) {
64
89
  for (const name in opt.hash) {
65
- let result;
66
90
  const value = opt.hash[name];
67
91
  inputs.push({ name, type, value });
68
- if (options.format === "html") {
69
- result = createInputHtml({ name, type, value, ...options });
70
- }
71
- else {
72
- if (type === "boolean") {
73
- result = `[? _${name}_]`;
74
- }
75
- else {
76
- result = `[> _${name}_]`;
77
- }
78
- }
92
+ const result = renderer.input ? renderer.input({ name, type, value }) : "";
79
93
  return new Handlebars.SafeString(result);
80
94
  }
81
95
  return "";
@@ -89,15 +103,9 @@ const useHelper = ({ inputs, sets, navs }, assets, options) => {
89
103
  return "";
90
104
  },
91
105
  nav(target, opt) {
92
- let result;
93
106
  const text = opt.fn(this).trim();
94
107
  navs.push({ text, target });
95
- if (options.format === "html") {
96
- result = createSubmitButtonHtml({ target: target ?? "", children: text, ...options });
97
- }
98
- else {
99
- result = `[@ __${text}__]`;
100
- }
108
+ const result = renderer.nav ? renderer.nav({ target, children: text }) : "";
101
109
  return new Handlebars.SafeString(result);
102
110
  },
103
111
  asset(name) {
@@ -107,7 +115,7 @@ const useHelper = ({ inputs, sets, navs }, assets, options) => {
107
115
  return new Handlebars.SafeString(assets[name]?.mime ?? "");
108
116
  },
109
117
  linebreak(n) {
110
- return new Handlebars.SafeString("\n".repeat(n ?? 1));
118
+ return new Handlebars.SafeString("<br>".repeat(n ?? 1));
111
119
  },
112
120
  };
113
121
  };
@@ -118,19 +126,28 @@ export class Chapter {
118
126
  this.template = template;
119
127
  this.hooks = hooks;
120
128
  }
121
- render(scope, assets = {}, options) {
122
- const md = new MarkdownIt({ html: true }).use(pluginAttrs);
129
+ render(scope, assets = {}, { format, html }) {
130
+ let renderer;
131
+ if (format === "markdown") {
132
+ renderer = markdownRenderer;
133
+ }
134
+ else if (format === "html") {
135
+ renderer = htmlRenderer;
136
+ }
137
+ else {
138
+ renderer = format;
139
+ }
123
140
  const fields = {
124
141
  inputs: [],
125
142
  sets: [],
126
143
  navs: [],
127
144
  };
128
- const helpers = useHelper(fields, assets, options);
145
+ const helpers = useHelper(fields, assets, renderer);
129
146
  let text;
130
- if (options.format === "html") {
147
+ if (html) {
148
+ const md = new MarkdownIt({ html: true }).use(pluginAttrs);
131
149
  text = Handlebars.compile(this.template)(scope, { helpers });
132
150
  text = md.render(text);
133
- text = createElementHtml("input", { type: "submit", disabled: true, hidden: true }) + text;
134
151
  }
135
152
  else {
136
153
  text = Handlebars.compile(this.template, { noEscape: true })(scope, { helpers });
@@ -1,9 +1,10 @@
1
1
  import { z } from "zod";
2
2
  export const ValueSchema = z.any().transform((v) => v);
3
3
  export const ScopeSchema = z.record(ValueSchema);
4
+ const AssetObjectSchema = z.object({ url: z.string(), mime: z.string().optional() });
4
5
  export const AssetSchema = z.union([
5
- z.string().transform((url) => ({ url, mime: undefined })),
6
- z.object({ url: z.string(), mime: z.string().optional() }),
6
+ z.string().transform((url) => AssetObjectSchema.parse({ url, mime: undefined })),
7
+ AssetObjectSchema,
7
8
  ]);
8
9
  export const AssetsSchema = z.record(AssetSchema);
9
10
  export const MetadataSchema = z.object({
package/package.json CHANGED
@@ -1,7 +1,8 @@
1
1
  {
2
2
  "name": "@elvishscout/mdstory",
3
- "version": "0.1.2",
4
- "description": "An interactive story format based on Markdown and Handlebars with JavaScript support.",
3
+ "repository": "https://github.com/ElvishScout/mdstory.git",
4
+ "version": "0.1.3",
5
+ "description": "An interactive fiction scripting format based on Markdown and Handlebars.",
5
6
  "main": "./dist/index.js",
6
7
  "type": "module",
7
8
  "files": [
@@ -37,4 +38,4 @@
37
38
  ],
38
39
  "author": "Jiakai Jiang",
39
40
  "license": "ISC"
40
- }
41
+ }
@@ -1,13 +1,22 @@
1
1
  import { ValueType, Value, ChapterHooks, Scope, Asset } from "./definitions.js";
2
- type MarkdownOptions = {};
3
- type HtmlOptions = {
4
- tagMap?: Record<string, string>;
2
+ export type Renderer = {
3
+ input?: ({ name, type, value }: {
4
+ name: string;
5
+ type: ValueType;
6
+ value: string;
7
+ }) => string;
8
+ nav?: ({ target, children }: {
9
+ target: string | null;
10
+ children: string;
11
+ }) => string;
5
12
  };
6
- export type RenderOptions = ({
7
- format: "markdown";
8
- } & MarkdownOptions) | ({
9
- format: "html";
10
- } & HtmlOptions);
13
+ export type RenderOptions = {
14
+ format: "markdown" | "html" | Renderer;
15
+ html?: boolean;
16
+ };
17
+ export type RenderResult = {
18
+ text: string;
19
+ } & Fields;
11
20
  type Fields = {
12
21
  inputs: {
13
22
  name: string;
@@ -24,9 +33,6 @@ type Fields = {
24
33
  target: string | null;
25
34
  }[];
26
35
  };
27
- export type RenderResult = {
28
- text: string;
29
- } & Fields;
30
36
  export type ChapterOptions = {
31
37
  id: string;
32
38
  title: string;
@@ -39,6 +45,6 @@ export declare class Chapter {
39
45
  template: string;
40
46
  hooks: ChapterHooks;
41
47
  constructor({ id, title, template, hooks }: ChapterOptions);
42
- render(scope: Scope, assets: Record<string, Asset> | undefined, options: RenderOptions): RenderResult;
48
+ render(scope: Scope, assets: Record<string, Asset> | undefined, { format, html }: RenderOptions): RenderResult;
43
49
  }
44
50
  export {};
@@ -9,7 +9,7 @@ export declare const ValueSchema: z.ZodEffects<z.ZodAny, string | number | boole
9
9
  export declare const ScopeSchema: z.ZodRecord<z.ZodString, z.ZodEffects<z.ZodAny, string | number | boolean | JsonArray | JsonObject | null, any>>;
10
10
  export declare const AssetSchema: z.ZodUnion<[z.ZodEffects<z.ZodString, {
11
11
  url: string;
12
- mime: undefined;
12
+ mime?: string | undefined;
13
13
  }, string>, z.ZodObject<{
14
14
  url: z.ZodString;
15
15
  mime: z.ZodOptional<z.ZodString>;
@@ -22,7 +22,7 @@ export declare const AssetSchema: z.ZodUnion<[z.ZodEffects<z.ZodString, {
22
22
  }>]>;
23
23
  export declare const AssetsSchema: z.ZodRecord<z.ZodString, z.ZodUnion<[z.ZodEffects<z.ZodString, {
24
24
  url: string;
25
- mime: undefined;
25
+ mime?: string | undefined;
26
26
  }, string>, z.ZodObject<{
27
27
  url: z.ZodString;
28
28
  mime: z.ZodOptional<z.ZodString>;
@@ -40,7 +40,7 @@ export declare const MetadataSchema: z.ZodObject<{
40
40
  globals: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodEffects<z.ZodAny, string | number | boolean | JsonArray | JsonObject | null, any>>>;
41
41
  assets: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<[z.ZodEffects<z.ZodString, {
42
42
  url: string;
43
- mime: undefined;
43
+ mime?: string | undefined;
44
44
  }, string>, z.ZodObject<{
45
45
  url: z.ZodString;
46
46
  mime: z.ZodOptional<z.ZodString>;
@@ -57,9 +57,6 @@ export declare const MetadataSchema: z.ZodObject<{
57
57
  email?: string | undefined;
58
58
  globals?: Record<string, string | number | boolean | JsonArray | JsonObject | null> | undefined;
59
59
  assets?: Record<string, {
60
- url: string;
61
- mime: undefined;
62
- } | {
63
60
  url: string;
64
61
  mime?: string | undefined;
65
62
  }> | undefined;