-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.js
More file actions
888 lines (849 loc) · 31.7 KB
/
main.js
File metadata and controls
888 lines (849 loc) · 31.7 KB
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
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
/// stub sim
const basicSoloEventSpecs = [
//{eventType: "beginMajorWork", tags: ["artistic", "major"]},
{eventType: "createMinorWork", tags: ["release", "artistic", "positive"]},
{eventType: "createManifesto", tags: ["release", "artistic", "positive"]},
{eventType: "receivePoorReview", tags: ["reception", "artistic", "negative"]},
{eventType: "receiveGoodReview", tags: ["reception", "artistic", "positive"]},
{eventType: "receiveAward", tags: ["reception", "artistic", "positive", "major"]}
];
const basicDyadicEventSpecs = [
{eventType: "getCoffeeWith", tags: ["friendly"]},
{eventType: "receiveNegativeFeedbackFrom", tags: ["reception", "artistic", "negative"]},
{eventType: "receivePositiveFeedbackFrom", tags: ["reception", "artistic", "positive"]},
//{eventType: "physicallyAttack", tags: ["unfriendly", "harms", "major"]},
{eventType: "disparagePublicly", tags: ["unfriendly", "harms"]},
{eventType: "sendPostcard", tags: ["friendly"]},
{eventType: "insult", tags: ["unfriendly"]},
{eventType: "insultDismissively", tags: ["unfriendly", "highStatus"]},
{eventType: "rejectSuperiority", tags: ["unfriendly", "lowStatus"]},
{eventType: "flirtWith_accepted", tags: ["romantic", "positive"]},
{eventType: "flirtWith_rejected", tags: ["romantic", "negative", "awkward"]},
//{eventType: "askOut_accepted", tags: ["romantic", "positive", "major"]},
//{eventType: "askOut_rejected", tags: ["romantic", "negative", "awkward", "major"]},
//{eventType: "propose_accepted", tags: ["romantic", "positive", "major"]},
//{eventType: "propose_rejected", tags: ["romantic", "negative", "awkward", "major"]},
//{eventType: "breakUp", tags: ["romantic", "negative", "major"]},
{eventType: "buyLunchFor", tags: ["friendly"]},
{eventType: "inviteIntoGroup", tags: ["highStatus", "friendly", "helps"]},
{eventType: "shunFromGroup", tags: ["highStatus", "unfriendly", "harms"]},
{eventType: "apologizeTo", tags: ["friendly"]},
//{eventType: "begForFavor", tags: ["lowStatus"]},
//{eventType: "extortFavor", tags: ["highStatus"]},
//{eventType: "callInFavor", tags: ["highStatus"]},
//{eventType: "callInExtortionateFavor", tags: ["highStatus", "harms"]},
//{eventType: "playTheFool", tags: ["lowStatus", "friendly"]},
//{eventType: "playRoyalty", tags: ["highStatus", "friendly"]},
//{eventType: "neg", tags: ["highStatus", "romantic", "negative"]},
{eventType: "askForHelp", tags: ["lowStatus", "friendly"]},
//{eventType: "deferToExpertise", tags: ["career", "lowStatus"]},
//{eventType: "noticeMeSenpai", tags: ["lowStatus", "romantic"]},
//{eventType: "collab:phoneItIn", tags: ["career", "harms"]},
//{eventType: "collab:goAboveAndBeyond", tags: ["career", "helps"]},
];
const authorGoalTemplates = [
{
name: "establishFriendship",
pattern:
`(pattern establishFriendship
(event ?e1 where tag: friendly, actor: ?c1, target: ?c2)
(event ?e2 where tag: friendly, actor: ?c2, target: ?c1)
(event ?e3 where eventType: formFriendship, actor: ?c1, target: ?c2)
(unless-event where tag: unfriendly, actor: ?c1, target: ?c2)
(unless-event where tag: unfriendly, actor: ?c2, target: ?c1))`,
stages: [
"?c1 is friendly to ?c2",
"?c2 is friendly to ?c1",
"?c1 and ?c2 become friends"
]
},
{
name: "supportStrugglingFriend",
pattern:
`(pattern supportStrugglingFriend
(event ?e1 where eventType: formFriendship, actor: ?c1, target: ?c2)
(event ?e2 where tag: worry, actor: ?c2)
(event ?e3 where tag: friendly, actor: ?c1, target: ?c2)
(unless-event where tag: unfriendly, actor: ?c1, target: ?c2))`,
stages: [
"?c1 befriends ?c2",
"?c2 worries about something",
"?c1 supports ?c2"
]
},
{
name: "establishGrudge",
pattern:
`(pattern establishGrudge
(event ?e1 where tag: unfriendly, actor: ?c2, target: ?c1)
(event ?e2 where eventType: formGrudge, actor: ?c1, target: ?c2)
(unless-event where eventType: abandonGrudge, actor: ?c1, target: ?c2))`,
stages: [
"?c2 is unfriendly to ?c1",
"?c1 forms a grudge on ?c2"
]
},
{
name: "establishMutualGrudge",
pattern:
`(pattern establishMutualGrudge
(event ?e1 where eventType: formGrudge, actor: ?c1, target: ?c2)
(event ?e2 where eventType: formGrudge, actor: ?c2, target: ?c1)
(unless-event where eventType: abandonGrudge, actor: ?c1, target: ?c2))`,
stages: [
"?c1 forms a grudge on ?c2",
"?c2 forms a grudge on ?c1"
]
},
{
name: "grudgeFades",
pattern:
`(pattern grudgeFades
(event ?e1 where eventType: formGrudge, actor: ?c1, target: ?c2)
(event ?e2 where tag: friendly, actor: ?c2, target: ?c1)
(event ?e3 where eventType: abandonGrudge, actor: ?c1, target: ?c2)
(unless-event where eventType: formGrudge, actor: ?c2, target: ?c1))`,
stages: [
"?c1 forms a grudge on ?c2",
"?c2 is friendly to ?c1",
"?c1's grudge on ?c2 fades",
//"?c2 forms a grudge on ?c1"
]
},
{
name: "bondOverSharedDislike",
pattern:
`(pattern bondOverSharedDislike
(event ?e1 where eventType: formGrudge, actor: ?c1, target: ?c3)
(event ?e2 where eventType: formGrudge, actor: ?c2, target: ?c3)
(event ?e3 where tag: friendly, actor: ?c1, target: ?c2)
(event ?e4 where tag: friendly, actor: ?c2, target: ?c1)
(unless-event where eventType: abandonGrudge, actor: ?c1, target: ?c3)
(unless-event where eventType: abandonGrudge, actor: ?c2, target: ?c3))`,
stages: [
"?c1 forms a grudge on ?c3",
"?c2 also forms a grudge on ?c3",
"?c1 connects with ?c2 over disliking ?c3",
"?c2 keeps up the connection with ?c1"
]
},
{
name: "majorWork",
pattern:
`(pattern majorWork
(event ?e1 where eventType: beginMajorWork, actor: ?c1)
(event ?e2 where eventType: makeProgressOnMajorWork, actor: ?c1)
(event ?e3 where eventType: makeProgressOnMajorWork, actor: ?c1)
(event ?e4 where eventType: makeProgressOnMajorWork, actor: ?c1)
(event ?e5 where eventType: finishMajorWork, actor: ?c1))`,
stages: [
"?c1 begins a major work",
"?c1 makes progress on the work",
"?c1 makes more progress",
"?c1 makes even more progress",
"?c1 finishes the work"
]
},
{
name: "troubledMajorWork",
pattern:
`(pattern troubledMajorWork
(event ?e1 where eventType: beginMajorWork, actor: ?c1)
(event ?e2 where tag: artistic, tag: negative, actor: ?c1)
(event ?e3 where tag: artistic, tag: negative, actor: ?c1)
(event ?e4 where tag: artistic, tag: negative, actor: ?c1)
(unless-event where eventType: finishMajorWork, actor: ?c1))`,
stages: [
"?c1 begins a major work",
"?c1 suffers an artistic setback",
"?c1 suffers another setback",
"?c1 suffers yet another setback"
]
},
{
name: "onARoll",
pattern:
`(pattern onARoll
(event ?e1 where eventType: finishMajorWork, actor: ?c1)
(event ?e2 where eventType: finishMajorWork, actor: ?c1)
(unless-event ?e3 where eventType: finishMajorWork, actor: ?c2, (not= ?c1 ?c2)))`,
stages: [
"?c1 finishes a major work",
"?c1 finishes another major work"
//"?c2 finishes a major work first"
]
},
{
name: "quantityOverQuality",
pattern:
`(pattern quantityOverQuality
(event ?e1 where eventType: createMinorWork, actor: ?c1)
(event ?e2 where eventType: createMinorWork, actor: ?c1)
(event ?e3 where eventType: createMinorWork, actor: ?c1)
(event ?e4 where tag: reception, tag: positive, actor: ?c1)
(unless-event where eventType: finishMajorWork, actor: ?c1)
(unless-event between ?e3 ?e4 where tag: reception, tag: negative, actor: ?c1)
(unless-event between ?e3 ?e4 where
tag: reception, tag: positive, actor: ?c2, (not= ?c1 ?c2)))`,
stages: [
"?c1 creates a minor work",
"?c1 creates another minor work",
"?c1 creates yet another minor work",
"?c1 is rewarded with career success",
//"?c1 finishes a major work"
]
},
{
name: "slowAndSteady",
pattern:
`(pattern slowAndSteady
(event ?e1 where eventType: finishMajorWork, actor: ?c1)
(event ?e2 where tag: reception, tag: positive, actor: ?c1)
(unless-event where eventType: createMinorWork, actor: ?c1))`,
stages: [
"?c1 finishes a major work",
"?c1 is rewarded with career success",
//"?c2 creates a minor work"
]
},
{
name: "tryTryAgain",
pattern:
`(pattern tryTryAgain
(event ?e1 where tag: release, actor: ?c1)
(event ?e2 where tag: reception, tag: negative, actor: ?c1)
(event ?e3 where tag: release, actor: ?c1)
(event ?e4 where tag: reception, tag: negative, actor: ?c1)
(event ?e5 where tag: release, actor: ?c1)
(event ?e6 where tag: reception, tag: positive, actor: ?c1)
(unless-event between ?e1 ?e5 where tag: reception, tag: positive, actor: ?c1)
(unless-event between ?e5 ?e6 where tag: reception, tag: negative, actor: ?c1))`,
stages: [
"?c1 releases an artwork",
"?c1's work is received poorly",
"?c1 releases another artwork",
"?c1's work is received poorly again",
"?c1 releases a third artwork",
"?c1's work is finally received well",
//"?c1's work is received well",
//"?c1's work is received poorly",
]
},
];
function getAllCharIDs(db) {
return datascript.q(`[:find ?c :where [?c "type" "char"]]`, db).map(res => res[0]);
}
function getAllCharIDPairs(db) {
return datascript.q(`[:find ?c1 ?c2
:where [?c1 "type" "char"] [?c2 "type" "char"] [(not= ?c1 ?c2)]]`, db);
}
function getCharName(db, id) {
return datascript.q(`[:find ?n . :where [${id} "type" "char"] [${id} "name" ?n]]`, db);
}
function generatePossibleActions(goal) {
if (goal.pattern.name === "majorWork") {
if (!goal.bindings["?e1"]) {
const enabledActions = [];
const possibleActors = goal.bindings["?c1"]
? [goal.bindings["?c1"]]
: getAllCharIDs(appState.db);
for (const charID of possibleActors) {
enabledActions.push({
eventType: "beginMajorWork",
actor: charID,
tags: ["artistic", "major"]
});
}
return enabledActions;
}
else if (goal.abandoned && !goal.bindings["?e5"]) {
return [{
eventType: "resumeMajorWork",
actor: goal.bindings["?c1"],
tags: ["artistic", "positive", "minor"]
}];
}
else if (!goal.bindings["?e5"]) {
const enabledActions = [
/*{
eventType: "abandonMajorWork",
actor: goal.bindings["?c1"],
tags: ["artistic", "negative", "major"]
},*/
{
eventType: "makeProgressOnMajorWork",
actor: goal.bindings["?c1"],
tags: ["artistic", "positive", "minor"]
},
{
eventType: "worryAboutMajorWork",
actor: goal.bindings["?c1"],
tags: ["worry", "artistic", "negative", "minor"]
},
{
eventType: "complainAboutMajorWork",
actor: goal.bindings["?c1"],
tags: ["complain", "artistic", "negative", "minor"]
}
];
if (goal.bindings["?e4"]) {
enabledActions.push({
eventType: "finishMajorWork",
actor: goal.bindings["?c1"],
tags: ["release", "artistic", "positive", "major"]
});
}
return enabledActions;
}
else {
return [];
}
}
else if (goal.pattern.name === "establishGrudge" && goal.lastStep !== "die") {
if (goal.bindings["?e1"] && !goal.bindings["?e2"]) {
return [{
eventType: "formGrudge",
actor: goal.bindings["?c1"],
target: goal.bindings["?c2"],
tags: ["negative", "major"]
}];
}
else if (goal.bindings["?e2"]) {
const enabledActions = [
{
eventType: "sabotageLatestWork",
tags: ["artistic", "unfriendly", "harms", "major"]
},
{eventType: "complainAboutGrudge", tags: ["complain", "negative", "minor"]},
{eventType: "worryAboutGrudge", tags: ["worry", "negative", "minor"]},
{eventType: "createDissWork", tags: ["release", "artistic", "unfriendly", "positive"]}
];
enabledActions.forEach(template => {
template.actor = goal.bindings["?c1"];
template.target = goal.bindings["?c2"];
});
return enabledActions;
}
else {
return [];
}
}
else if (goal.pattern.name === "grudgeFades") {
if (goal.bindings["?e2"] && !goal.bindings["?e3"]) {
return [{
eventType: "abandonGrudge",
actor: goal.bindings["?c1"],
target: goal.bindings["?c2"],
tags: ["positive", "major"]
}];
}
else {
return [];
}
}
else if (goal.pattern.name === "establishFriendship" && goal.lastStep !== "die") {
if (goal.bindings["?e1"] && goal.bindings["?e2"] && !goal.bindings["?e3"]) {
return [{
eventType: "formFriendship",
actor: goal.bindings["?c1"],
target: goal.bindings["?c2"],
tags: ["positive", "friendly", "major"]
}];
}
else {
return [];
}
}
else {
return [];
}
}
function getAllPossibleActions(appState) {
const allPossibleActions = [];
const charIDs = getAllCharIDs(appState.db);
const charIDPairs = getAllCharIDPairs(appState.db);
for (const eventSpec of basicSoloEventSpecs) {
for (const c of charIDs) {
allPossibleActions.push({
type: "event",
eventType: eventSpec.eventType,
tags: eventSpec.tags,
actor: c
});
}
}
for (const eventSpec of basicDyadicEventSpecs) {
for (const [c1, c2] of charIDPairs) {
allPossibleActions.push({
type: "event",
eventType: eventSpec.eventType,
tags: eventSpec.tags,
actor: c1,
target: c2
});
}
}
for (const goal of appState.goals) {
for (const actionTemplate of generatePossibleActions(goal)) {
actionTemplate.type = "event";
actionTemplate.goal = goal.id;
allPossibleActions.push(actionTemplate);
}
}
return allPossibleActions;
}
// Add an event to the DB and return an updated DB.
function addEvent(db, event) {
const transaction = [[":db/add", -1, "type", "event"]];
for (let attr of Object.keys(event)) {
if (attr === "tags") continue;
transaction.push([":db/add", -1, attr, event[attr]]);
}
for (let tag of event.tags || []) {
transaction.push([":db/add", -1, "tag", tag]);
}
return datascript.db_with(db, transaction);
}
const schema = {
tag: {":db/cardinality": ":db.cardinality/many"}
};
const allCharNames = [
"Aidan", "Bella", "Cam", "Devin", "Emily",
// spare names if we need extra
"Adam", "Alex", "Alice", "Ann",
"Ben", "Beth",
"Cathy", "Colin",
"Emma", "Erin",
"Fred",
"Gavin", "Gillian",
"Izzy",
"Jacob", "James", "Janey", "Jason", "Jordan",
"Kevin", "Kurt",
"Liz",
"Matt", "Melissa",
"Nathan", "Nicole", "Nora",
"Quinn",
"Robin",
"Sarah",
"Victor", "Vincent"
];
function initializeDB() {
let db = datascript.empty_db(schema);
for (let i = 0; i < 5; i++) {
const charName = allCharNames[i];
const transaction = [
[":db/add", -1, "type", "char"],
[":db/add", -1, "name", charName],
];
db = datascript.db_with(db, transaction);
}
return db;
}
/// UI state management
const firstFiveChars = allCharNames.slice(0, 5);
const allValues = ["cuteness", "humor", "minimalism", "radicalism", "seriousness", "sincerity"];
let appState = {
db: initializeDB(),
initialCharSituations: firstFiveChars.map(char => {
const doesValue = randNth(allValues);
const doesntValue = randNth(allValues.filter(v => v !== doesValue));
//const likeTarget = randNth(firstFiveChars.filter(tc => tc !== char));
//const dislikeTarget = randNth(firstFiveChars.filter(tc => tc !== char && tc !== likeTarget));
return {
name: char,
situations: [
randNth(["microcelebrity", "firebrand", "slacker", "sycophant", "worrier"]),
"appreciates " + doesValue,
"despises " + doesntValue
//"likes " + likeTarget,
//"dislikes " + dislikeTarget
]
};
}),
goals: [],
nextAuthorGoalID: 0,
backgroundPartialMatches: [],
suggestions: [],
suggestionsCursor: 0,
transcriptEntries: [],
};
function initAppState() {
for (const goalName of ["establishGrudge", "majorWork"]) {
addAuthorGoal(appState, goalName);
}
for (const goalTemplate of authorGoalTemplates) {
const compiledPattern = compilePattern(parse(goalTemplate.pattern)[0]);
appState.backgroundPartialMatches.push({pattern: compiledPattern, bindings: {}});
}
}
initAppState();
function refreshSuggestions() {
const allSuggestions = shuffle(getAllPossibleActions(appState));
for (const suggestion of allSuggestions) {
const nextDB = addEvent(appState.db, suggestion);
suggestion.db = nextDB;
// figure out how this suggestion would update author goals if accepted
// (TODO unify this logic with the logic used below in the pickSuggestion UI effect handler)
suggestion.goalUpdates = [];
const latestEventID = newestEID(suggestion.db);
for (const goal of appState.goals) {
const possibleGoalUpdates = tryAdvance(goal, suggestion.db, "", latestEventID);
suggestion.goalUpdates = suggestion.goalUpdates.concat(possibleGoalUpdates);
}
}
// Sort by whether/how each suggestion advances active goals,
// and secondarily by whether each suggestion is enabled by an active goal
// (even if it doesn't advance any goals). FIXME Improve this.
allSuggestions.sort((a, b) => {
const randomOffset = Math.random();
const bScore = b.goalUpdates.length + (b.goal ? 0.5 : 0) + randomOffset;
const aScore = a.goalUpdates.length + (a.goal ? 0.5 : 0);
return bScore - aScore;
});
appState.suggestions = allSuggestions;
appState.suggestionsCursor = 0;
}
function getAuthorGoal(appState, goalID) {
return appState.goals.find(goal => goal.id === goalID);
}
function addAuthorGoal(appState, goalName) {
const goalTemplate = authorGoalTemplates.find(agt => agt.name === goalName);
const compiledPattern = compilePattern(parse(goalTemplate.pattern)[0]);
appState.goals.push({id: appState.nextAuthorGoalID, pattern: compiledPattern, bindings: {}});
appState.nextAuthorGoalID += 1;
}
function removeAuthorGoal(appState, goalID) {
appState.goals = appState.goals.filter(goal => goal.id !== goalID);
}
function summarizeAuthorGoal(goal) {
const nonEventKeys = Object.keys(goal.bindings).filter(k => !k.startsWith("?e")); // FIXME hacky
const nonEventVals = nonEventKeys.map(k => goal.bindings[k]);
return goal.pattern.name + "|" + nonEventVals.join("|");
}
function applyUIEffect(effect, params) {
// transcript UI effects
if (effect === "updateTranscriptEntryText") {
appState.transcriptEntries[params.entry].text = params.newText;
}
// suggestion UI effects
else if (effect === "pickSuggestion") {
// identify which suggestion we're trying to perform
const suggestion = appState.suggestions[params.suggestion];
// perform it, updating the DB with the resulting effects and new event
appState.db = suggestion.db;
// add a new transcript entry for the new event
const latestEventID = newestEID(appState.db);
const latestEvent = getEntity(appState.db, latestEventID);
const actorName = getCharName(appState.db, suggestion.actor);
const targetName = suggestion.target ? getCharName(appState.db, suggestion.target) : "";
appState.transcriptEntries.push({
title: `${actorName} ${latestEvent.eventType} ${targetName}`.trim(),
text: ""
});
// update any goals that this suggestion advances/completes/cuts off
for (let i = 0; i < appState.goals.length; i++) {
const goal = appState.goals[i];
const possibleGoalUpdates = tryAdvance(goal, appState.db, "", latestEventID);
console.log("possibleGoalUpdates", possibleGoalUpdates);
const meaningfulUpdates = possibleGoalUpdates.filter(g => g.lastStep !== "pass");
if (meaningfulUpdates.length > 0) {
const prevGoalID = appState.goals[i].id;
const prevStatus = appState.goals[i].status;
appState.goals[i] = meaningfulUpdates[0];
appState.goals[i].id = prevGoalID;
if (prevStatus) {
appState.goals[i].status = prevStatus;
}
}
}
// update background partial matches too
appState.backgroundPartialMatches = mapcat(
appState.backgroundPartialMatches,
function(partialMatch) {
let possibleMatchUpdates = tryAdvance(partialMatch, appState.db, "", latestEventID);
// greedily replace bpms with advanced versions of themselves,
// except for the baseline empty bpms we keep around to capture later match opportunities
if (possibleMatchUpdates[0].lastStep === "pass"
&& possibleMatchUpdates.length > 1
&& Object.keys(possibleMatchUpdates[0].bindings).length > 0) {
possibleMatchUpdates = possibleMatchUpdates.slice(1);
}
return possibleMatchUpdates.filter(pmu => pmu.lastStep !== "die");
// FIXME also filter out complete matches?
}
);
// copy over background partial matches to player-visible goals if it makes sense to do so
const goalSummaries = appState.goals.map(summarizeAuthorGoal);
for (const bpm of appState.backgroundPartialMatches) {
// skip to next background partial match if this bpm wasn't just advanced
// (FIXME does lastStep have to be literally "accept", or is any non-"pass" lastStep ok?)
if (bpm.lastStep !== "accept") continue;
// skip to next background partial match if this bpm is already a goal
const bpmSummary = summarizeAuthorGoal(bpm);
if (goalSummaries.includes(bpmSummary)) continue;
// skip to next background partial match if this bpm is already a *prefix to* a goal
const relevantGoals = goalSummaries.filter(gs => gs.split("|")[0] === bpm.pattern.name);
const bpmBindingsSummary = bpmSummary.split("|").slice(1).join("|");
const furtherAdvancedGoal = relevantGoals.find(rg => {
const rgBindingsSummary = rg.split("|").slice(1).join("|");
return rgBindingsSummary.startsWith(bpmBindingsSummary);
});
if (furtherAdvancedGoal) continue;
// skip to next background partial match if not enough progress on this one yet
const numClauses = bpm.pattern.eventClauses.length;
let numClausesBound = 0;
for (const clause of bpm.pattern.eventClauses) {
if (!hasBinding(bpm, clause.eventLvar)) break;
numClausesBound += 1;
}
const completionProgress = numClausesBound / numClauses;
if (completionProgress < 0.33) continue;
// add this background partial match directly to goals
bpm.status = "suggested";
bpm.id = appState.nextAuthorGoalID;
appState.nextAuthorGoalID += 1;
appState.goals.push(bpm);
}
// remove bpms that were suggested as goals from the bpm pool
appState.backgroundPartialMatches = appState.backgroundPartialMatches.filter(bpm => {
return bpm.status !== "suggested";
});
// refresh suggestions based on new DB state
refreshSuggestions();
}
else if (effect === "hoverSuggestion") {
// identify which suggestion we're trying to perform
const suggestion = appState.suggestions[params.suggestion];
// visually update any goals that would be advanced/completed/cut off by it
for (const goalUpdate of suggestion.goalUpdates) {
if (goalUpdate.lastStep !== "pass") {
const goal = appState.goals.find(g => g.id === goalUpdate.parent.id);
goal.updateIfSuggestionAccepted = goalUpdate;
}
}
}
else if (effect === "unhoverSuggestion") {
// visually update any goals that are currently impacted by suggestion hover
appState.goals.forEach(goal => {
delete goal.updateIfSuggestionAccepted;
});
}
else if (effect === "showMoreSuggestions") {
// advance the suggestions cursor, wrapping around if we reach the end
let nextCursor = appState.suggestionsCursor + 3;
if (!appState.suggestions[nextCursor]) nextCursor = 0;
appState.suggestionsCursor = nextCursor;
}
else if (effect === "showTopSuggestions") {
// reset the suggestions cursor back to the start of the list
appState.suggestionsCursor = 0;
}
// goal UI effects
else if (effect === "openGoalComposer") {
appState.goalComposerActive = true;
}
else if (effect === "closeGoalComposer") {
appState.goalComposerActive = false;
}
else if (effect === "acceptSuggestedAuthorGoal") {
delete appState.goals.find(goal => goal.id === params.id).status;
// FIXME suggestions shouldn't change when a goal goes from suggested to accepted, right?
}
else if (effect === "addAuthorGoal") {
addAuthorGoal(appState, params.name);
refreshSuggestions();
}
else if (effect === "removeAuthorGoal") {
removeAuthorGoal(appState, params.id);
refreshSuggestions();
}
// fallback: catch any attempts to invoke nonexistent UI effect types
else {
console.warn("Bad UI effect type", effect);
}
// at the end, rerender everything to reflect the updated app state
rerenderUI(appState);
}
/// rendering
const e = React.createElement;
function rerenderUI(state) {
// render transcript
const transcriptEntriesDiv = document.getElementById("transcript-entries");
ReactDOM.render(
state.transcriptEntries.map((entry, entryID) => {
return e("div", {className: "entry", key: entryID},
e("div", {className: "system-text"}, entry.title),
e("textarea", {
className: "user-text",
onChange: ev => applyUIEffect(
"updateTranscriptEntryText",
{entry: entryID, newText: ev.target.value}
),
placeholder: "Details here...",
value: entry.text
})
);
}),
transcriptEntriesDiv
);
// ...and scroll most recent entry into view if there are any entries
if (transcriptEntriesDiv.lastChild) {
transcriptEntriesDiv.lastChild.scrollIntoView();
}
// render suggested actions
const cursor = state.suggestionsCursor;
const suggestions = state.suggestions.slice(cursor, cursor + 3);
ReactDOM.render(
suggestions.map((suggestion, suggestionIdx) => {
const absoluteSuggestionIdx = cursor + suggestionIdx;
const actorName = getCharName(state.db, suggestion.actor);
const targetName = suggestion.target ? getCharName(state.db, suggestion.target) : "";
return e("div", {
className: "suggestion",
key: suggestionIdx,
onClick: ev => applyUIEffect("pickSuggestion", {suggestion: absoluteSuggestionIdx}),
onMouseEnter: ev => applyUIEffect("hoverSuggestion", {suggestion: absoluteSuggestionIdx}),
onMouseLeave: ev => applyUIEffect("unhoverSuggestion", {})
},
`${actorName} ${suggestion.eventType} ${targetName}`.trim()
);
}),
document.getElementById("suggestions")
);
// render goals
const goalElems = state.goals.map(goal => {
const firstIncompleteClauseIdx = goal.pattern.eventClauses.findIndex(
ec => !hasBinding(goal, ec.eventLvar)
);
const goalTpl = authorGoalTemplates.find(agt => agt.name === goal.pattern.name);
const friendlyBindings = {};
for (const lvar of Object.keys(goal.bindings)) {
const val = goal.bindings[lvar];
if (Number.isInteger(val)) {
const ent = getEntity(appState.db, val);
friendlyBindings[lvar] = ent.name;
} else {
friendlyBindings[lvar] = val;
}
}
const nextStep = goal.updateIfSuggestionAccepted?.lastStep;
const clauseElems = [];
for (let clauseIdx = 0; clauseIdx < goal.pattern.eventClauses.length; clauseIdx++) {
const clause = goal.pattern.eventClauses[clauseIdx];
const complete = goal.lastStep === "complete" || clauseIdx < firstIncompleteClauseIdx;
const firstIncompleteClause = clauseIdx === firstIncompleteClauseIdx;
const highlight = firstIncompleteClause && ["accept","complete"].includes(nextStep);
const stageDescTpl = goalTpl.stages[clauseIdx];
let stageDesc = stageDescTpl;
for (const lvar of Object.keys(friendlyBindings)) {
stageDesc = stageDesc.replaceAll(lvar, friendlyBindings[lvar]);
}
if (firstIncompleteClause && (goal.lastStep === "die" || nextStep === "die")) {
//const constraint = goal.updateIfSuggestionAccepted.deathDetails.constraint;
// TODO better description based on constraint
clauseElems.push(e("div", {
className: "goal-part die",
key: "unless-event" + clauseIdx
},
"Pattern cut off"));
}
clauseElems.push(e("div", {
className: `goal-part${complete ? " complete" : ""}${highlight ? " selected" : ""}`,
key: clauseIdx
},
stageDesc));
}
const goalDivAttrs = {
className: `goal${goal.status === "suggested" ? " suggested" : ""}`
};
if (goal.status === "suggested") {
goalDivAttrs.onClick = (ev => applyUIEffect("acceptSuggestedAuthorGoal", {id: goal.id}));
}
return e("div", goalDivAttrs,
e("div", {className: "goal-title", key: -1},
e("span", {
className: "delete-goal-button",
onClick: ev => {
ev.stopPropagation();
applyUIEffect("removeAuthorGoal", {id: goal.id});
}
}, "❌"),
goal.pattern.name
),
clauseElems
);
});
goalElems.push(e("div", {
className: "add-goal",
onClick: ev => applyUIEffect("openGoalComposer", {})
}, "+"));
// divide goalElems into two columns to approximate a masonry layout
const evenGoalElems = [];
const oddGoalElems = [];
for (let i = 0; i < goalElems.length; i++) {
const targetColumn = i % 2 === 0 ? evenGoalElems : oddGoalElems;
targetColumn.push(goalElems[i]);
}
ReactDOM.render(
e("div", {className: "goals"},
e("div", {className: "goals-column"}, evenGoalElems),
e("div", {className: "goals-column"}, oddGoalElems)
),
document.getElementById("goals")
);
// render goal composer if active
let goalComposer = null;
if (state.goalComposerActive) {
goalComposer = e("div", {
className: "goal-composer-modal",
onClick: ev => applyUIEffect("closeGoalComposer", {})
},
e("div", {className: "goal-composer"},
e("h3", {}, "Add new author goal"),
e("div", {className: "goal-template-picker"},
authorGoalTemplates.map(agt => {
return e("div", {
className: "goal-template",
onClick: ev => applyUIEffect("addAuthorGoal", {name: agt.name})
},
agt.name);
})
)
)
),
document.getElementById("goal-composer-modal");
}
ReactDOM.render(goalComposer, document.getElementById("goal-composer-modal"));
}
function initiallyRenderUI(state) {
// render the see-more-suggestions button
ReactDOM.render(
e("div", {},
e("span", {
onClick: ev => applyUIEffect("showMoreSuggestions", {})
}, "see more suggestions"),
e("span", {}, " • "),
e("span", {
onClick: ev => applyUIEffect("showTopSuggestions", {})
}, "back to top suggestions")
),
document.getElementById("suggestions-more")
);
// get the initial set of suggestions
refreshSuggestions();
// render the dramatis personae / initial character situations
ReactDOM.render(
state.initialCharSituations.map(char => {
return e("span", {className: "char-situation"},
e("span", {className: "char-name"}, char.name),
", ",
char.situations.join(", "),
e("br")
);
}),
document.getElementById("dramatis-personae")
);
// do a first render pass on all the dynamic UI bits too
rerenderUI(state);
}
initiallyRenderUI(appState);