-
Notifications
You must be signed in to change notification settings - Fork 2
/
inklewriter-convert.ts
765 lines (610 loc) · 25.1 KB
/
inklewriter-convert.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
// --------------------------------------
// Types for the data directly coming from JSON
// --------------------------------------
// Top level interface for the JSON
interface InklewriterJSON {
title : string,
data : InklewriterData, // main data blob (see interface below)
created_at: string, // date
url_key: string,
updated_at: string // date
}
interface InklewriterData {
allowCheckpoints : boolean,
optionMirroring : boolean,
initial : string,
stitches : {
[name:string]: StitchData
},
editorData: {
playPoint: string,
textSize: number,
authorName: string,
libraryVisible: boolean
}
}
interface StitchData {
content: ContentData[]
}
type ContentData = TextData | ChoiceData | NotIfConditionData | IfConditionData | DivertData | RunOnData | FlagData | PageNumData | PageLabelData | ImageData;
type TextData = string;
interface ChoiceData {
linkPath: string | null,
ifConditions: IfConditionData[] | null,
option: string,
notIfConditions: NotIfConditionData[] | null
}
interface NotIfConditionData {
notIfCondition: string
}
interface IfConditionData {
ifCondition: string
}
interface DivertData {
divert: string
}
// Equivalent to ink glue
interface RunOnData {
runOn: true
}
interface PageNumData {
pageNum: number
}
interface PageLabelData {
pageLabel: string
}
// In inklewriter the field was called "flagName" but in fact
// the feature was expanded so that they could include expressions
// such as "myFlag + 1" or "myFlag = 9". For the converter we
// parse these on load.
interface FlagData {
flagName: string
}
interface ImageData {
image: string // image URL
}
// --------------------------------------
// Classes for parsed / loaded story data
// --------------------------------------
class Condition {
constructor(condition : string, isNot : boolean) {
this.condition = condition;
this.isNot = isNot;
}
condition : string
isNot : boolean
}
class Choice {
text : string
linkPath : string | null
conditions : Condition[]
constructor(data : ChoiceData) {
this.text = data.option;
this.linkPath = data.linkPath;
this.conditions = [];
if( data.ifConditions ) {
for(let ifC of data.ifConditions) {
this.conditions.push(new Condition(ifC.ifCondition, false));
}
}
if( data.notIfConditions ) {
for(let notIfC of data.notIfConditions) {
this.conditions.push(new Condition(notIfC.notIfCondition, true));
}
}
}
}
class Flag {
flagName : string;
assignedExpression : string;
defaultValue : 0 | false;
constructor(flagText : string) {
var assignPos = flagText.indexOf("=");
var mathOpPos = flagText.search(/(\+|-|\*|\/)/);
// Explicit assignment
// e.g. "myFlag = 5"
if( assignPos !== -1) {
this.flagName = flagText.substr(0, assignPos).trim();
this.assignedExpression = flagText.substr(assignPos+1).trim();
if( this.assignedExpression === "true" || this.assignedExpression === "false" )
this.defaultValue = false;
else
this.defaultValue = 0;
}
// Mathematical expression. Assume flag name comes first.
// e.g. "myFlag + 1"
else if( mathOpPos !== -1 ) {
this.flagName = flagText.substr(0, mathOpPos).trim();
this.assignedExpression = flagText.trim();
this.defaultValue = 0;
}
// Simple flag set to true expression
// e.g. "myFlag"
else {
this.flagName = flagText.trim();
this.assignedExpression = "true";
this.defaultValue = false;
}
}
}
class Stitch {
constructor(name : string, data : StitchData, owner : Story) {
this.name = name;
this.textContent = [];
this.choices = [];
this.conditions = [];
this.divert = null;
this.runOn = false;
this.flags = [];
this.image = null;
this.pageNum = -1;
this.originalPageNum = -1;
this.pageLabel = null;
this.distanceFromHeader = -1;
this.header = null;
this.divertBackLinks = [];
this.choiceBackLinks = [];
this.owner = owner;
for(var c of data.content) {
// Text content
if( typeof(c) == "string" ) {
this.textContent.push(c);
}
// Choice
else if( (c as ChoiceData).option !== undefined ) {
this.choices.push(new Choice(c as ChoiceData));
}
// Page num
else if( (c as PageNumData).pageNum !== undefined ) {
this.pageNum = this.originalPageNum = (c as PageNumData).pageNum;
}
// Page label
else if( (c as PageLabelData).pageLabel !== undefined ) {
this.pageLabel = (c as PageLabelData).pageLabel;
}
// ifCondition
else if( (c as IfConditionData).ifCondition !== undefined ) {
this.conditions.push(new Condition((c as IfConditionData).ifCondition, false));
}
// notIfCondition
else if( (c as NotIfConditionData).notIfCondition !== undefined ) {
this.conditions.push(new Condition((c as NotIfConditionData).notIfCondition, true));
}
// divert
else if( (c as DivertData).divert !== undefined ) {
this.divert = (c as DivertData).divert;
}
// runOn
else if( (c as RunOnData).runOn !== undefined ) {
this.runOn = true;
}
// flag
else if( (c as FlagData).flagName !== undefined ) {
this.flags.push(new Flag((c as FlagData).flagName));
}
// image
else if( (c as ImageData).image !== undefined ) {
this.image = (c as ImageData).image;
}
}
}
eachLinkedStitch(func : (s : Stitch) => void) {
if( this.divert !== null ) {
let divertTarget = this.owner.stitchesByName[this.divert];
func(divertTarget);
}
for(let c of this.choices) {
if( c.linkPath === null ) continue;
var choiceTarget = this.owner.stitchesByName[c.linkPath];
func(choiceTarget);
}
}
get isHeader() : boolean {
return this.distanceFromHeader === 0;
}
get divertTarget() : Stitch | null {
if( this.divert )
return this.owner.stitchesByName[this.divert];
else
return null;
}
name : string;
textContent : string[]
choices : Choice[]
pageNum : number
originalPageNum : number
header : Stitch | null
pageLabel : string | null
distanceFromHeader : number
conditions : Condition[]
divert : string | null
runOn : boolean
flags : Flag[]
image : string | null
divertBackLinks : Stitch[]
choiceBackLinks : Stitch[]
owner : Story
}
class Story {
title : string
author : string
optionMirroring : boolean
initialStitchName : string
stitchesByName : { [name: string]: Stitch }
orderedStitches : Stitch[];
constructor(json : InklewriterJSON) {
let data = json.data as InklewriterData;
this.title = json.title;
this.author = data.editorData.authorName;
this.optionMirroring = data.optionMirroring;
this.initialStitchName = data.initial;
this.stitchesByName = {};
this.orderedStitches = [];
for(let stitchName in data.stitches) {
let stitchData = data.stitches[stitchName];
let stitch = new Stitch(stitchName, stitchData, this);
this.stitchesByName[stitchName] = stitch;
this.orderedStitches.push(stitch);
}
this.calculateSectionsAndOrdering();
}
get firstStitch() : Stitch {
return this.stitchesByName[this.initialStitchName];
}
// We use the section labelling in inklewriter to construct
// ink-style knots. So the first thing is to find a sensible
// ordering. inklewriter itself does something very similar
// in order to order the index sidebar.
private calculateSectionsAndOrdering() {
let originalHeaders : Stitch[] = [];
function searchLinksForSortIndices(stitch : Stitch, originalHeader : Stitch, currentDepth : number) {
// Explicitly numbered headers get treated specially in the main loop
if( stitch.originalPageNum >= 0 )
return;
// Labelled pages are also headers, but we don't know their overall ordering ahead of time
else if( stitch.pageLabel != null) {
currentDepth = 0;
}
if( stitch.distanceFromHeader === -1 || currentDepth < stitch.distanceFromHeader ) {
stitch.distanceFromHeader = currentDepth;
// If this is a stitch with a valid pageLabel then strictly speaking it
// shouldn't have the same page number as the originalHeader, but
stitch.pageNum = originalHeader.originalPageNum;
// Recurse
stitch.eachLinkedStitch(subStitch => searchLinksForSortIndices(subStitch, originalHeader, currentDepth + 1));
}
}
// First stitch is implicitly a header stitch
let first = this.firstStitch;
originalHeaders = this.orderedStitches.filter(s => s.originalPageNum >= 0 || s === first);
for(let originalHeader of originalHeaders) {
originalHeader.distanceFromHeader = 0;
originalHeader.eachLinkedStitch(subStitch => searchLinksForSortIndices(subStitch, originalHeader, 1));
}
let unreachedStitches : Stitch[] = [];
// Drop unreached stitches down to the bottom
for(let stitch of this.orderedStitches) {
if( stitch.pageNum === -1 ) {
stitch.pageNum = 1000000;
unreachedStitches.push(stitch);
}
}
if( unreachedStitches.length > 0 && !unreachedStitches[0].pageLabel ) {
unreachedStitches[0].pageLabel = "##Unused##";
}
// Find the overall linear ordering of the stitches
this.orderedStitches.sort((s1, s2) => {
if( s1.pageNum != s2.pageNum )
return s1.pageNum - s2.pageNum;
else
return s1.distanceFromHeader - s2.distanceFromHeader;
});
// Extract final ordered sections, and renumber
let header : Stitch | null = null;
let pageNum = 0;
for(let stitch of this.orderedStitches) {
// Either it's an original header or it's a labelled header
// that needs its own page number now.
// Or it's the unused page we may have created above
if( stitch.distanceFromHeader === 0 || stitch.pageLabel === "##Unused##" ) {
header = stitch;
pageNum++;
}
stitch.header = header;
stitch.pageNum = pageNum;
}
// Set up backlinks so that we can look both backwards
// and forwards to see whether stitches are directly
// linked together and therefore and simply be laid
// out consecutively in ink.
for(let stitch of this.orderedStitches) {
var target = stitch.divertTarget;
if( target )
target.divertBackLinks.push(stitch);
for(let choice of stitch.choices) {
if( choice.linkPath === null ) continue;
let choiceTarget = this.stitchesByName[choice.linkPath];
if( choiceTarget )
choiceTarget.choiceBackLinks.push(stitch);
}
}
}
}
// Create an ink-compatible name for a stitch/knot/variable name (identifier) from
// an inklewriter stitch / section / flag name, taking in a dictionary of the names
// that have already been taken so that we can prevent collisions using numbering.
function createIdentifierFromString(str : string, collisionDictionary : {[existingName:string]:any}) : string {
let id = "";
for(let c of str) {
// Allow a-z etc
if( c >= '0' && c <= '9' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c == '_' ) {
id += c;
}
// Convert whitespace to single '_'
else if( c == ' ' || c == '\t' ) {
if( id.length > 0 && id[id.length-1] != "_" )
id += "_";
}
// skip everything else
}
if( id.length > 0 && id[id.length-1] == "_" ) {
id = id.substr(0, id.length-1);
}
// Avoid naming collisions
let originalId = id;
let count = 2;
while(collisionDictionary[id]) {
id = `${originalId}_${count}`;
count++;
}
return id;
}
// Main conversion function.
export function convert(sourceJSON : InklewriterJSON, terminateAllLooseEnds : boolean) : string {
// Parse Story from the JSON
var story = new Story(sourceJSON);
// Final output
let inkLines : string[] = [];
// Create ink-specific stitch/knot name mappings out of the inklewriter content
let inklewriterStitchToInkNames : { [inklewriterName:string]: string} = {};
let inkNamesUsage : { [inkName:string]: true } = {};
for(let stitch of story.orderedStitches) {
let inkName = stitch.name;
if( stitch.isHeader && stitch.pageLabel )
inkName = createIdentifierFromString(stitch.pageLabel, inkNamesUsage);
inkNamesUsage[inkName] = true;
inklewriterStitchToInkNames[stitch.name] = inkName;
}
let initialKnotName = inklewriterStitchToInkNames[story.initialStitchName];
inkLines.push(`// ---- ${sourceJSON.title} ----`);
inkLines.push(`// Converted from original inklewriter URL:`);
inkLines.push(`# title: ${story.title}`);
inkLines.push(`# author: ${story.author}`);
inkLines.push(`// -----------------------------`);
inkLines.push(``);
// Convert flag names to VAR names:
// Flag names can have spaces, so we need to cover them all to proper identifiers
let flagNamesToVarNames : { [flagName:string]: string } = {};
let varNamesToFlagNames : { [varName:string]: string } = {};
let orderedVarNames : string[] = [];
let defaultValuesByVarName : { [varName:string]: any } = {};
for(let s of story.orderedStitches) {
for(let flag of s.flags) {
let varName = flagNamesToVarNames[flag.flagName];
if( !varName ) {
varName = createIdentifierFromString(flag.flagName, varNamesToFlagNames);
flagNamesToVarNames[flag.flagName] = varName;
varNamesToFlagNames[varName] = flag.flagName;
orderedVarNames.push(varName);
}
// Infer the data types of the variables
if( defaultValuesByVarName[varName] === undefined )
defaultValuesByVarName[varName] = flag.defaultValue;
}
}
// VAR declarations
for(let varName of orderedVarNames) {
let assumedDefault = defaultValuesByVarName[varName];
if( assumedDefault === undefined ) assumedDefault = false;
inkLines.push(`VAR ${varName} = ${assumedDefault}`);
}
// Anywhere we have logic (e.g. conditionals, inline logic in main text)
// Do some fixing up to make it valid ink logic.
function replaceFlagNamesAndUpdateLogic(logicStr : string) : string {
if( logicStr != null && logicStr.length > 0 ) {
// Replace flag names with VAR names
for(let flagName in flagNamesToVarNames) {
let varName = flagNamesToVarNames[flagName];
logicStr = logicStr.split(flagName).join(varName);
}
// Replace single "=" with double "=="
// (but not >= or <=!)
logicStr = logicStr.replace(/([^><])(=)/g, "$1==");
}
return logicStr;
}
// Divert into first knot
inkLines.push(``);
inkLines.push(`-> ${initialKnotName}`);
inkLines.push(``);
// We mostly process stitches consecutively, but when there are
// directly linked stitches we allow them to be "inlined" so that
// you don't need to use explicit stitch names for them all. Keep
// track of which ones have already been processed here.
let processedStitchNames : { [name:string]: true } = {};
// Main conversion function for a single Stitch.
function processStitch(stitch : Stitch, stitchIdx : number) {
// Has this stitch already been processed?
if( processedStitchNames[stitch.name] )
return;
processedStitchNames[stitch.name] = true;
// Header is always explicitly named as a knot
// (Header is a stitch that begins a new inklewriter section)
if( stitch.isHeader ) {
var knotName = inklewriterStitchToInkNames[stitch.name];
inkLines.push(`\n==== ${knotName} ====`);
}
// Do we need to label this stitch?
else {
// Directly following on to this stitch?
if( stitch.divertBackLinks.length === 1 && stitch.divertBackLinks[0].header === stitch.header && stitch.choiceBackLinks.length === 0 && !stitch.isHeader ) {
// no need to print stitch title
}
// Otherwise, name this stitch for full linking
else {
inkLines.push(`\n= ${inklewriterStitchToInkNames[stitch.name]}`);
}
}
// Content is conditional?
let isConditional = stitch.conditions.length > 0;
if( isConditional ) {
let conditionsTexts = stitch.conditions.map(cond => {
let condTxt = cond.condition;
condTxt = replaceFlagNamesAndUpdateLogic(condTxt);
if( cond.isNot )
condTxt = "not "+condTxt;
return condTxt;
});
let conditionsStr = conditionsTexts.join(" and ");
inkLines.push(`{ ${conditionsStr}:`);
}
// Image
if( stitch.image ) {
// New-inky-specific template tag, but could be usable in other environments
inkLines.push(`# IMAGE: ${stitch.image}`);
}
// Main text content for stitch
// Think there's actually only ever one line...?
for(let lineIdx=0; lineIdx<stitch.textContent.length; lineIdx++) {
let line = stitch.textContent[lineIdx];
// Update any inline logic
// - Flag names to VAR names
// - logic tweaks - e.g. "=" to "=="
let nextSearchPos = 0;
do {
let logicPos = line.indexOf("{", nextSearchPos);
if( logicPos > -1 ) {
let logicEndPos = line.indexOf(":", logicPos);
// Might be a sequence rather than normal conditional logic
if( logicEndPos === -1 )
logicEndPos = line.indexOf("}", logicPos)
let logicTxt = line.substr(logicPos, logicEndPos-logicPos);
// Replace flag names with VAR names
let updatedLogicTxt = replaceFlagNamesAndUpdateLogic(logicTxt);
let txtBefore = line.substr(0, logicPos);
let txtAfter = line.substr(logicEndPos);
line = txtBefore + updatedLogicTxt + txtAfter;
nextSearchPos = txtBefore.length + updatedLogicTxt.length;
// Was that the end of the line?
if( txtAfter.length <= 0 )
nextSearchPos = -1;
}
// No logic left
else {
nextSearchPos = -1;
}
} while(nextSearchPos !== -1);
// Italics
line = line.split("/=").join("<em>");
line = line.split("=/").join("</em>");
// Bold
line = line.split("*-").join("<strong>");
line = line.split("-*").join("</strong>");
// Inline value evaluation
// In inklewriter it looks like this:
// [value:varName]
// In ink it looks like this:
// {varName}
line = line.replace(/\[value:([^\]]+)\]/g, "{$1}");
// runOn (inklewriter elipsis) == ink-style glue
let isLastLine = lineIdx === stitch.textContent.length-1;
if( isLastLine && stitch.runOn )
line += " <>";
// old style runOn that has't be upgraded
line = line.split("[...]").join("<>");
if( isConditional )
line = " " + line;
inkLines.push(line);
}
// Flags
// (Evaluation of flags comes AFTER the main content.)
for(let flag of stitch.flags) {
let exprWithVars = replaceFlagNamesAndUpdateLogic(flag.assignedExpression);
let conditionalIndent = isConditional ? " " : " ";
inkLines.push(`${conditionalIndent} ~ ${flagNamesToVarNames[flag.flagName]} = ${exprWithVars}`);
}
if( isConditional )
inkLines.push("}");
// Find the ink-specific target path given the original inklewriter stitch name.
// Resolve so it's either a simple name or a dot.separated name depending on whether
// we need to jump between ink knots (inklewriter sections).
function resolveDivertTargetStr(stitchName : string, relativeStitch : Stitch) : string {
let targetStitch = story.stitchesByName[stitchName];
let targetName = inklewriterStitchToInkNames[targetStitch.name];
if( !targetStitch.isHeader && targetStitch.header !== relativeStitch.header ) {
let targetHeaderName = inklewriterStitchToInkNames[targetStitch.header!.name];
targetName = `${targetHeaderName}.${targetName}`;
}
return targetName;
}
if( stitch.choices.length > 0 && stitch.divert )
throw new Error("Got both choices AND a divert? Shouldn't be possible?");
// Link up choices
for(let choice of stitch.choices) {
let conditionsTexts = choice.conditions.map(cond => {
let condTxt = cond.condition;
condTxt = replaceFlagNamesAndUpdateLogic(condTxt);
if( cond.isNot )
condTxt = "not "+condTxt;
return `{${condTxt}} `;
});
let conditionsStr = conditionsTexts.join("");
let targetName : string | null = null;
if( choice.linkPath ) {
targetName = resolveDivertTargetStr(choice.linkPath, stitch);
}
let choiceLine = "";
if( story.optionMirroring )
choiceLine = ` + ${conditionsStr}${choice.text}`;
else
choiceLine = ` + ${conditionsStr}[${choice.text}]`;
if( targetName ) {
// When options are mirrored it has to be a bit uglier to enforce the newline after the mirrored text
// When options aren't mirrored we can include the divert on the same line.
if( story.optionMirroring ) choiceLine += `\n `;
choiceLine += ` -> ${targetName} `;
} else {
choiceLine += `\n TODO: This choice is a loose end.`;
}
inkLines.push(choiceLine);
}
// Divert (mutually exclusive v.s. choices)
let nextStitch : Stitch | null = null;
let divertTargetFollowsOnDirectly = false;
if( stitch.divert ) {
nextStitch = stitch.divertTarget;// stitchIdx < story.orderedStitches.length-1 ? story.orderedStitches[stitchIdx+1] : null;
divertTargetFollowsOnDirectly = (nextStitch !== null && nextStitch.divertBackLinks.length === 1 && nextStitch.choiceBackLinks.length == 0 && !nextStitch.isHeader && nextStitch.header === stitch.header) ? true : false;
if( !divertTargetFollowsOnDirectly ) {
let targetName = resolveDivertTargetStr(stitch.divert, stitch);
inkLines.push(` -> ${targetName}`);
}
}
// Immediately recurse if we're following straight on to more content
// within this current ink stitch/knot
if( divertTargetFollowsOnDirectly && nextStitch !== null ) {
let nextStitchIdx = story.orderedStitches.indexOf(nextStitch);
processStitch(nextStitch, nextStitchIdx);
}
// Assume all loose ends are complete, or not?
if( !stitch.divert && stitch.choices.length === 0 && terminateAllLooseEnds ) {
inkLines.push(` -> END`);
}
}
// Convert all stitches to ink
for(let stitchIdx = 0; stitchIdx < story.orderedStitches.length; stitchIdx++) {
let stitch = story.orderedStitches[stitchIdx];
processStitch(stitch, stitchIdx);
}
// Final ink
return inkLines.join("\n");
}