/
scripts.txt
835 lines (830 loc) · 31.1 KB
/
scripts.txt
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
./scripts/main.js
```javascript
import './module/settings.js';
import './module/prosemirrorPlugin.js';
import './module/api.js';
import './module/uiHelpers.js';
import './module/journalManager.js';
import './module/utils.js';
import './module/aiJournalSheet.js';
function initializeModule() {
log({message: "Ready hook triggered."});
}
Hooks.once('ready', initializeModule);```
./scripts/module/settings.js
```javascript
export const MAX_TOKENS = 4096;
export const BASE_URL = 'https://api.openai.com/v1/chat/completions';
export function registerSettings() {
game.settings.register('legend-lore', 'openaiApiKey', {
name: "OpenAI API Key",
hint: "Enter your OpenAI API key here.",
scope: 'world',
config: true,
type: String,
default: ""
});
game.settings.register('legend-lore', 'models', {
name: "Models",
hint: "Enter models you wish to have available in a space-separated list. Only models with JSON mode are supported. For model information, see [OpenAI Models]. For pricing information, see [OpenAI Pricing Link].",
scope: 'world',
config: true,
type: String,
default: "gpt-3.5-turbo-1106 gpt-4-1106-preview"
});
game.settings.register('legend-lore', 'temperature', {
name: "Temperature",
hint: "Enter a desired temperature (higher is more creative, lower is more consistent).",
scope: 'world',
config: true,
type: Number,
default: "0.3"
});
game.settings.registerMenu("legend-lore", "templateSettingMenu", {
name: "Journal Entry Templates",
label: "Select Templates",
hint: "Select journal entry templates for your module.",
icon: "fas fa-bars",
type: JournalEntrySelectionApplication,
restricted: true
});
game.settings.register('legend-lore', 'globalContext', {
scope: 'world',
label: "Global Context",
hint: "Context that will be considered when generating content.",
config: true,
type: String,
default: ''
});
game.settings.register('legend-lore', 'journalEntryTemplates', {
scope: 'world',
config: false,
type: Object,
default: ["journal-entry-templates"]
});
logInfo({message: "Game settings registered successfully."});
}
class JournalEntrySelectionApplication extends FormApplication {
constructor(...args) {
super(...args);
this.journalEntries = this._getJournalEntryCompendiums();
}
static get defaultOptions() {
return mergeObject(super.defaultOptions, {
id: "journal-entry-selection",
classes: ["legend-lore"],
title: "Select Journal Entries",
template: "modules/legend-lore/templates/journal-entry-selection.html",
width: 640,
height: "auto",
resizable: true
});
}
getData() {
const selectedIds = new Set(game.settings.get('legend-lore', 'journalEntryTemplates'));
return {
entries: this.journalEntries.map(entry => ({
...entry,
isSelected: selectedIds.has(entry.id)
}))
};
}
async _updateObject(event, formData) {
const selectedEntries = Object.entries(formData)
.filter(([key, value]) => value)
.map(([key]) => key);
await game.settings.set('legend-lore', 'journalEntryTemplates', selectedEntries);
}
activateListeners(html) {
super.activateListeners(html);
const filterInput = html.find("#filter-input");
const entryContainer = html.find("#journal-entries-container");
filterInput.on("keyup", event => {
const searchTerm = event.target.value.toLowerCase();
entryContainer.find(".checkbox").each(function() {
const label = $(this).find("label").text().toLowerCase();
const isMatch = label.includes(searchTerm);
$(this).toggle(isMatch);
});
});
}
_getJournalEntryCompendiums() {
const packs = Array.from(game.packs);
return packs
.filter(pack => pack.metadata.type === "JournalEntry")
.map(pack => ({
id: pack.metadata.id,
name: pack.metadata.name,
label: `${pack.metadata.label} `,
group: `${pack.metadata.id.split('.')[0]}`
}));
}
}
Hooks.on('renderPackageConfiguration', (app, html, data) => {
let apiKeyInput = $('[name="legend-lore.openaiApiKey"]')[0];
if (apiKeyInput) {
apiKeyInput.type = 'password';
apiKeyInput.autocomplete = 'one-time-code';
}
});
Hooks.once('ready', () => {
registerSettings();
});```
./scripts/module/utils.js
```javascript
/**
* Logs messages with standard module formatting.
* @param {string} message - The message to log.
*/
export function log(options = {
message,
display: ["console"], type: ["info"], error
}) {
const console_message = `Legend Lore | ${message}`
const ui_message = `${message}`
if (options.type.contains("console")) {
if (options.type.contains("info")) {
console.info(console_message);
}
if (options.type.contains("warn")) {
console.warn(console_message);
}
if (options.type.contains("error")) {
if(options.error){
console.error(console_message, options.error);
}
else {
console.error(console_message, options.error);
}
}
}
if (options.type.contains("ui")) {
if (options.type.contains("info")) {
ui.notifications.info(ui_message);
}
if (options.type.contains("warn")) {
ui.notifications.warn(ui_message);
}
if (options.type.contains("error")) {
if(options.error){
ui.notifications.error(ui_message);
}
else {
ui.notifications.error(ui_message + " [See web console for more information]");
}
}
}
}
```
./scripts/module/elementTransformer.js
```javascript
export class ElementHandler {
/**
* Converts an HTML element to its JSON representation.
* @param {Element} element - The HTML element to convert.
* @return {Object} JSON representation of the element.
*/
static htmlToJson(element) {
try {
if (!(element instanceof Element)) {
throw new Error("Invalid input: Expected HTML Element.");
}
let json = {
tagName: element.tagName.toLowerCase()
};
let children = [];
for (let node of element.childNodes) {
if (node.nodeType === Node.TEXT_NODE && node.nodeValue.trim().length > 0) {
children.push({ type: 'text', content: node.nodeValue.trim() });
} else if (node.nodeType === Node.ELEMENT_NODE) {
children.push(ElementHandler.htmlToJson(node));
}
}
if (children.length > 0) {
json.children = children;
}
return json;
}
catch (error) {
log({
message: 'Error in HTML to JSON processing.',
error: error,
display: ["ui", "console"],
type: ["error"]
});
}
}
/**
* Converts a JSON object back into an HTML element.
* @param {Object} jsonObject - The JSON object to convert.
* @return {Element} The resulting HTML element.
*/
static jsonToHtml(jsonObject) {
try {
if (typeof jsonObject !== 'object' || jsonObject === null) {
throw new Error("Invalid input: Expected JSON object.");
}
const element = document.createElement(jsonObject.tagName);
if (jsonObject.children) {
for (let childJson of jsonObject.children) {
if (childJson.type === 'text') {
let textNode = document.createTextNode(childJson.content);
element.appendChild(textNode);
} else {
let childElement = ElementHandler.jsonToHtml(childJson);
element.appendChild(childElement);
}
}
}
return element;
}
catch (error) {
log({
message: 'Error in JSON to HTML processing.',
error: error,
display: ["ui", "console"],
type: ["error"]
});
}
}
static getElementAttributes(element) {
let attributes = {};
for (let attr of element.attributes) {
attributes[attr.name] = attr.value;
}
return attributes;
}
static setElementAttributes(element, attributes) {
for (let attrName in attributes) {
element.setAttribute(attrName, attributes[attrName]);
}
}
}
```
./scripts/module/api.js
```javascript
import { BASE_URL, MAX_TOKENS } from './settings.js';
import { createNewJournalEntryPage } from './journalManager.js'
async function callOpenAI(preprompt, contextPrompt, model) {
const fullPrompt = `${preprompt}\n\n${contextPrompt}`;
const apiKey = game.settings.get('legend-lore', 'openaiApiKey');
if (!apiKey) {
log({
message: "OpenAI API key is not set in the Legend Lore module settings.",
display: ["ui", "console"],
type: ["error"]});
return null;
}
const requestOptions = {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: model,
messages: [
{
role: "system",
content: preprompt
},
{
role: "user",
content: contextPrompt
}
],
temperature: game.settings.get('legend-lore', 'temperature'),
MAX_TOKENS: MAX_TOKENS,
response_format: { type: "json_object" },
}),
};
try {
const response = await fetch(`${BASE_URL}`, requestOptions);
if (!response.ok) {
throw new Error(response.statusText);
return null;
}
const data = await response.json();
return data;
} catch (error) {
log({
message: 'Error in OpenAI API request.',
error: error,
display: ["ui", "console"],
type: ["error"]
});
return null;
}
}
export async function processGPTRequest(options = {
type,
subject,
journalEntryName,
originalTitle,
context,
additionalContext,
journalEntryId,
templateContent,
globalContext,
model
}) {
const preprompt = `You are a TTRPG content generator.`
(options);
(JSON.stringify(options.templateContent));
let prompt = `Generate a fully-detailed and RICH TTRPG entry for "${options.journalEntryName}" from within "${options.originalTitle}" on the following subject: "${options.subject}". Expand on "${options.journalEntryName}" in granular detail and introduce new subjects within the context of "${options.originalTitle}". `
if(options.context) {
prompt = prompt + `Here is more context on "${options.subject}" below:
CONTEXT
---
${JSON.stringify(options.context)}
---
`
}
if ( options.additionalContext || options.globalContext) {
prompt = prompt + `
ADDITIONAL CONSIDERATIONS:`
if (options.additionalContext) prompt = prompt + `
${options.additionalContext}
---`
if (options.globalContext) prompt = prompt + `
${options.globalContext}
---`
}
prompt = prompt + `
ADHERE TO THE FOLLOWING JSON TEMPLATE:
'{
"precedent_subjects": "<Comprehensive Comma-Separated List of Existing Subjects with Precedent EXCLUSIVELY related to ${options.subject}>",
"new_subjects": "<Comprehensive Comma-Separated List of Newly Generated, UNPRECEDENTED DISTINCT Subjects EXCLUSIVELY related to ${options.subject}, using PROPER NOUNS>",
"subject_expansion": "array detailing each identified precedent_subject and new_subject, ONLY IF RELATED TO ${options.subject}, in an effort to provide RICH content.",
"output": ${JSON.stringify(options.templateContent)
}"
}'
Emulate and adhere to the formatting and writing style of the CONTEXT provided. All new content must be DIRECTLY related to "${options.subject}."`;
(prompt);
const apiResponseContent = await callOpenAI(preprompt, prompt, options.model);
if (!apiResponseContent) {
ui.notifications.error('Failed to get a response from OpenAI.');
return;
}
(apiResponseContent);
return {
journalEntryId: options.journalEntryId,
subject: options.subject,
originalContent: options.context,
apiResponseContent: apiResponseContent
};
}
```
./scripts/module/prosemirrorPlugin.js
```javascript
import { openDialog } from './uiHelpers.js';
Hooks.once('ready', () => {
const originalBuild = window.ProseMirror.ProseMirrorHighlightMatchesPlugin.build;
window.ProseMirror.ProseMirrorHighlightMatchesPlugin.build = function (schema, options = {}) {
const originalPlugin = originalBuild.call(window.ProseMirror.ProseMirrorHighlightMatchesPlugin, schema, options);
const originalView = originalPlugin.spec.view;
if (typeof originalView === 'function') {
originalPlugin.spec.view = (editorView) => {
const tooltipInstance = originalView(editorView);
if (typeof tooltipInstance.update === 'function') {
const originalUpdate = tooltipInstance.update.bind(tooltipInstance);
tooltipInstance.update = async function(view, lastState) {
const state = view.state;
const { from } = state.selection;
const start = view.coordsAtPos(from);
const left = (start.left + 3) + "px";
const bottom = (window.innerHeight - start.bottom + 25) + "px";
const position = { bottom, left };
await originalUpdate(view, lastState);
if (view.state.selection.content().size > 0){
const { from, to } = view.state.selection;
const highlightedText = view.state.doc.textBetween(from, to);
const safeHighlightedText = highlightedText.replace(/'/g, "\\'");
const closestJournalEntryElement = editorView.dom.closest('[id*=JournalEntry]');
let journalEntryId = null;
if (closestJournalEntryElement && closestJournalEntryElement.id) {
const idParts = closestJournalEntryElement.id.split('-');
const journalEntryIdIndex = idParts.findIndex(part => part === 'JournalEntry') + 1;
journalEntryId = idParts[journalEntryIdIndex];
}
const gptGenerateButtonContent = `
<section style="background-color:gold;">
<h4 style="color:black;">Legend Lore</h4>
<a class="generate-entry-link content-link" onclick="generateEntryForText('${safeHighlightedText}', '${journalEntryId}'); return false;">
<i class="fas fa-wand-sparkles"></i>Generate Entry for ${highlightedText}
</a>
</section>
`;
window.generateEntryForText = function(highlightedText, journalEntryId) {
let originalContent = new DOMParser().parseFromString(editorView.dom.outerHTML.replace(/<([a-z][a-z0-9]*)[^>]*?(\/?)>/gi, '<$1$2>'), 'text/xml');
let originalTitle = $(editorView.dom).closest('.editable.flexcol').find('[name="name"').value;
openDialog({
type: "context",
highlightedText: highlightedText,
journalEntryId: journalEntryId,
originalTitle: originalTitle,
originalContent: originalContent
});
};
if (this.tooltip) {
this.tooltip.innerHTML += gptGenerateButtonContent;
} else {
this._createTooltip(position, gptGenerateButtonContent, {cssClass: "link-matches"});
}
}
};
}
return tooltipInstance;
};
}
return originalPlugin;
};
});
```
./scripts/module/journalManager.js
```javascript
export async function createNewJournalEntryPage(options = {
type,
journalEntryId,
pageName,
highlightedText,
originalContent,
pageContent
}) {
const type = options.type;
const journalEntryId = options.journalEntryId;
const pageName = options.pageName;
const highlightedText = options.highlightedText;
const originalContent = options.originalContent;
const pageContent = options.pageContent;
let journalEntry = game.journal.get(journalEntryId);
if (!journalEntry) {
log({
message: `Could not find JournalEntry with ID: ${journalEntryId}`,
display: ["console", "ui"],
type: ["error"]
});
return;
}
let sortValue;
if (typeof journalEntry.getNextSortOrder === "function") {
sortValue = journalEntry.getNextSortOrder();
} else {
const pages = journalEntry.pages.contents;
sortValue = pages.length ? (pages[pages.length - 1].sort + CONST.SORT_INTEGER_DENSITY) : 0;
}
let data = {
name: pageName || "New Page",
text: { content: pageContent || "" },
sort: sortValue,
parent: journalEntry.id
};
('Data object for new JournalEntryPage:', data);
if (!game.user.can("JOURNAL_CREATE")) {
log({
message: `You do not have permission to create new journal pages.`,
display: ["console", "ui"],
type: ["warn"]
});
return;
}
try {
let createdPage = await JournalEntryPage.create(data, {parent: journalEntry});
log(`New page created with ID: ${createdPage.id}`);
let updatedContent = replaceHighlightedTextInContent(highlightedText, createdPage.id, originalContent);
updateEditorContent(updatedContent);
return createdPage;
} catch (error) {
log({
message: `Error creating new JournalEntryPage.`,
error: error,
display: ["console", "ui"],
type: ["error"]
});
return null;
}
}
function replaceHighlightedTextInContent(originalText, pageUUID, content) {
let replacementText = `@UUID[.${pageUUID}]{${originalText}}`;
return content.split(originalText).join(replacementText);
}
function updateEditorContent(updatedContent) {
let editorContentDiv = document.querySelector('.editor-content.journal-page-content.ProseMirror');
if(editorContentDiv) {
editorContentDiv.innerHTML = updatedContent;
} else {
log({
message: `Editor content div not found`,
display: ["console", "ui"],
type: ["error"]
});
}
}
function saveEditorChanges() {
let saveButton = document.querySelector('button[data-action="save"]');
if(saveButton) {
saveButton.click();
} else {
log({
message: `Save button not found`,
display: ["console", "ui"],
type: ["error"]
});
}
}
```
./scripts/module/uiHelpers.js
```javascript
import { processGPTRequest } from "./api.js";
import { createNewJournalEntryPage } from "./journalManager.js";
import { ElementHandler } from './elementTransformer.js';
export async function openDialog(options = {
type,
highlightedText,
journalEntryId,
originalTitle,
originalContent
}) {
const type = options.type;
const journalEntryId = options.journalEntryId;
const journalEntry = game.journal.get(journalEntryId);
let journalEntryName;
if (journalEntry) {
journalEntryName = journalEntry.name;
}
let dialogTitle, dialogTemplate, highlightedText, originalTitle, originalContent, contextName, contextPlaceholder;
if (type === "context") {
highlightedText = options.highlightedText;
originalTitle = options.originalTitle;
originalContent = options.originalContent;
contextName = "Additional Context";
contextPlaceholder = "OPTIONAL: Add any additional information or instruction for the AI model to consider.";
dialogTitle = `Additional Context for "${highlightedText}"`;
} else if (type === "generate") {
dialogTitle = `Generate New Journal Entry Page`;
contextName = "Generation Context";
contextPlaceholder = "REQUIRED: Add information or instruction for the AI model to use as inspiration for generating this entry.";
}
dialogTemplate = await renderTemplate('modules/legend-lore/templates/dialog.html', {
contextName: contextName,
contextPlaceholder: contextPlaceholder
});
let d = new Dialog({
title: dialogTitle,
content: dialogTemplate,
buttons: {
accept: {
icon: '<i class="fas fa-check"></i>',
label: "Accept",
disabled: true,
callback: (html) => {
let selectedJournalId = html.find('.journal-entry-dropdown').val();
createNewJournalEntryPage({
type: type,
journalEntryId: selectedJournalId,
pageName: html.find(".legend-lore.entry-title")[0].value,
highlightedText: highlightedText,
originalContent: originalContent,
pageContent: html.find(".legend-lore.generation-preview").html()
});
}
},
cancel: {
icon: '<i class="fas fa-times"></i>',
label: "Cancel"
}
},
default: "cancel",
render: async (html) => dialogHelper({
html: html,
type: type,
highlightedText: highlightedText,
journalEntryName: journalEntryName,
originalTitle: originalTitle,
originalContent: originalContent,
journalEntryId: journalEntryId
})
}).render(true, {
width: 800
});
}
async function dialogHelper(options = {
html,
type,
highlightedText,
pageName,
journalEntryName,
originalTitle,
originalContent,
journalEntryId
}) {
await populateJournalDropdown(options.journalEntryId);
$(options.html[2]).prepend('<button class="dialog-button generate"><i class="fas fa-wand-sparkles"></i> Generate</button>');
const generateButton = options.html.find(".dialog-button.generate");
const acceptButton = options.html.find(".dialog-button.accept");
const contextField = options.html.find(".context");
const titleField = options.html.find(".entry-title");
titleField.on("input", () => {
generateButton.prop("disabled",(!(contextField.val() && titleField.val())));
});
if(options.type === "generate") {
generateButton.prop("disabled",true);
contextField.on("input", () => {
generateButton.prop("disabled",(!(contextField.val() && titleField.val())));
});
}
const contentPreview = options.html.find(".generation-preview");
contentPreview.on("change", () => {
if ( contentPreview.innerHTML != "Pending Generation") {
}
});
options.html.find(".legend-lore.entry-title").val(options.highlightedText);
generateButton.click(function() {
handleGenerate(options = {
html: options.html,
type: options.type,
highlightedText: options.highlightedText,
journalEntryName: options.journalEntryName,
originalTitle: options.originalTitle,
globalContext: (options.html.find('.global-context')[0].value) ? game.settings.get('legend-lore','globalContext') : '',
originalContent: (options.html.find('.originating-content')[0].value) ? options.originalContent : '',
journalEntryId: options.journalEntryId
});
});
$(options.html).find('#entry-template').on('change', function() {
if (this.value === "null" ) {
resetPreviewStyle("template-preview");
}
else {
updateTemplatePreview(this.value);
}
});
populateJournalEntryTemplates();
populateModels();
}
function resetPreviewStyle(previewName) {
$(`.legend-lore.${previewName}`).empty();
$(`.legend-lore.${previewName}`).html(`
<p>[Provide, with context to the original content, a brief introduction to the subject, including its basic definition, nature, and overall significance or relevance in the context it is being addressed.]</p>
<h2>General Description</h2>
<p>[Offer, with context to the original content, a general description of the subject, focusing on its key characteristics, features, or aspects. This section should lay the foundation for understanding the subject's uniqueness and importance.]</p>
`);
}
function updatePreviewStyle(previewName) {
$(`.legend-lore.${previewName}`).removeAttr( 'style' );
$(`.legend-lore.${previewName}`).css ('height', '184px');
$(`.legend-lore.${previewName}`).css ('padding-left', '8px');
$(`.legend-lore.${previewName}`).css ('padding-right', '8px');
}
async function updateTemplatePreview(journalDataString) {
updatePreviewStyle("template-preview");
const journalData = JSON.parse(journalDataString);
const templateContent = await getJournalEntryPages(journalData.pack, journalData.journalEntryName, journalData.journalEntryPageName);
$('.legend-lore.template-preview').html(templateContent.text.content);
}
function populateModels() {
const dropdown = document.getElementById("gpt-model");
const models= game.settings.get('legend-lore','models').split(' ');
for (const model of models) {
const option = document.createElement("option");
option.value = model;
option.text = model;
dropdown.add(option);
}
}
async function populateJournalEntryTemplates() {
const compendiumNames = game.settings.get('legend-lore', 'journalEntryTemplates');
const dropdown = document.getElementById("entry-template");
clearDropdownOptions(dropdown);
for (const compendiumName of compendiumNames) {
const journalEntries = await getJournalEntriesFromCompendium(compendiumName);
for (const journalEntry of journalEntries) {
const pages = await getJournalEntryPages(compendiumName, journalEntry.name);
if (pages && pages.size > 0) {
addPagesToDropdown(pages, journalEntry, dropdown);
}
}
}
}
function clearDropdownOptions(dropdown) {
while (dropdown.options.length > 0) {
dropdown.remove(0);
}
let option = document.createElement("option");
option.value = "null";
option.text = `None`;
dropdown.add(option);
}
function addPagesToDropdown(pages, journalEntry, dropdown) {
for (const page of pages) {
const option = document.createElement("option");
option.value = JSON.stringify({
pack: page.pack,
journalEntryName: journalEntry.name,
journalEntryPageName: page.name
});
option.text = `${journalEntry.name}: ${page.name}`;
dropdown.add(option);
}
}
async function getJournalEntriesFromCompendium(compendiumName) {
const compendium = game.packs.get(compendiumName);
if (!compendium) {
log({
message: `Compendium not found: ${compendiumName}.`,
display: ["console", "ui"],
type: ["error"]
})
return [];
}
await compendium.getIndex();
const journalEntries = [];
for (const indexEntry of compendium.index) {
const entry = await compendium.getDocument(indexEntry._id);
journalEntries.push(entry);
}
return journalEntries;
}
async function getJournalEntryPages(compendiumName, journalEntryName, pageName) {
const journalEntries = await getJournalEntriesFromCompendium(compendiumName);
for (const journalEntry of journalEntries) {
if (journalEntry.name == journalEntryName) {
if (pageName) {
return journalEntry.pages.find(page => page.name === pageName) || null;
}
return journalEntry.pages
}
}
}
async function handleGenerate(options = {
html,
type,
highlightedText,
journalEntryName,
originalTitle,
originalContent,
globalContext,
journalEntryId
}) {
$(options.html).find(".dialog-button.generate")[0].innerHTML=`<i class="fas fa-sparkle fa-spin"></i> Generating...`;
const formElements = $(options.html).find('input, textarea, button, a');
formElements.prop('disabled', true);
const model = $(options.html).find(".legend-lore.gpt-model")[0].value;
let templateContentJSON = ''
templateContentJSON = ElementHandler.htmlToJson($(options.html).find('.legend-lore.template-preview')[0]);
let context, additionalContext, subject;
if(options.type === "context"){
subject = options.highlightedText;
context=ElementHandler.htmlToJson(options.originalContent.activeElement);
additionalContext = $(options.html).find(".legend-lore.context")[0].value;
} else if (options.type === "generate") {
subject = $(options.html).find(".legend-lore.entry-title")[0].value;
context=$(options.html).find(".legend-lore.context")[0].value;
}
let data = await processGPTRequest({
type: options.type,
subject: subject,
journalEntryName: options.journalEntryName,
context: context,
originalTitle: options.originalTitle,
context: context,
globalContext: context,
additionalContext: additionalContext,
journalEntryId: options.journalEntryId,
templateContent: templateContentJSON,
model
});
const content = JSON.parse(data.apiResponseContent.choices[0].message.content.trim());
try {
let jsonObject = content;
const text = ElementHandler.jsonToHtml(content.output);
updateUIAfterResponse(options.html, text, data.apiResponseContent.usage);
} catch (error) {
log({
message:"Error parsing JSON.",
error: error,
type: ["error"],
display: ["error", "ui"]
})
}
formElements.prop('disabled', false);
}
function updateUIAfterResponse(html, returnedContent, tokens) {
updatePreviewStyle("generation-preview");
$(html).find('.legend-lore.generation-preview').html(returnedContent);
$(html).find('#token-count').html(`<strong>Tokens sent: ${tokens.prompt_tokens}, Tokens received: ${tokens.completion_tokens}, Total Tokens Used: ${tokens.total_tokens}</strong>`);
$(html).find('#response-container').show();
$(html).find(".dialog-button.generate")[0].innerHTML=`<i class="fas fa-sparkle"></i> Generate`;
}
async function populateJournalDropdown(selectedJournalEntryId = null) {
const dropdown = document.querySelector('.journal-entry-dropdown');
dropdown.innerHTML = '';
const journalEntries = game.journal.map(entry => ({ id: entry.id, name: entry.name }));
for (const entry of journalEntries) {
let option = document.createElement("option");
option.value = entry.id;
option.textContent = entry.name;
option.selected = entry.id === selectedJournalEntryId;
dropdown.appendChild(option);
}
}```