This repository has been archived by the owner on Sep 18, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
pin-cushion.js
571 lines (506 loc) · 19.6 KB
/
pin-cushion.js
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
import PinCushionAboutApp from "./about.js";
import { libWrapper } from "./lib-wrapper-shim.js";
/**
* A class for managing additional Map Pin functionality
* @author Evan Clarke (errational#2007)
*/
class PinCushion {
constructor() {
// Storage for requests sent over a socket, pending GM execution
this._requests = {};
}
/* -------------------------------- Constants ------------------------------- */
static get MODULE_NAME() {
return "pin-cushion";
}
static get MODULE_TITLE() {
return "Pin Cushion";
}
static get PATH() {
return "modules/pin-cushion";
}
static get DIALOG() {
const defaultPermission = game.settings.get(PinCushion.MODULE_NAME, "defaultJournalPermission");
const defaultFolder = game.settings.get(PinCushion.MODULE_NAME, "defaultJournalFolder");
const folders = game.journal.directory.folders
.filter(folder => folder.displayed)
.map(folder => `<option value="${folder.id}">${folder.name}</option>`).join("\n");
return {
content: `
<div class="form-group">
<p class="notes">${game.i18n.localize("PinCushion.Name")}</p>
</label>
<input name="name" type="text">
<p class="notes">${game.i18n.localize("PinCushion.DefaultPermission")}</p>
</label>
<select id="cushion-permission" style="width: 100%;">
<option value="0" ${defaultPermission == "0" ? "selected" : ""}>${game.i18n.localize("PERMISSION.NONE")}</option>
<option value="1" ${defaultPermission == "1" ? "selected" : ""}>${game.i18n.localize("PERMISSION.LIMITED")}</option>
<option value="2" ${defaultPermission == "2" ? "selected" : ""}>${game.i18n.localize("PERMISSION.OBSERVER")}</option>
<option value="3" ${defaultPermission == "3" ? "selected" : ""}>${game.i18n.localize("PERMISSION.OWNER")}</option>
</select>
<p class="notes">${game.i18n.localize("PinCushion.Folder")}</p>
</label>
<select id="cushion-folder" style="width: 100%;">
<option value="none" ${defaultFolder == "none" ? "selected" : ""}>${game.i18n.localize("PinCushion.None")}</option>
${game.user.isGM ? `` : `<option value="perUser" ${defaultFolder == "perUser" ? "selected" : ""}>${game.i18n.localize("PinCushion.PerUser")}</option>`}
<option disabled>──${game.i18n.localize("PinCushion.ExistingFolders")}──</option>
${folders}
</select>
</div>
</br>
`,
title: "Create a Map Pin"
}
}
static get NOTESLAYER() {
return "NotesLayer";
}
static get FONT_SIZE() {
return 16;
}
/* --------------------------------- Methods -------------------------------- */
/**
* Creates and renders a dialog for name entry
* @param {*} data
* @todo break callbacks out into separate methods
*/
_createDialog(data) {
new Dialog({
title: PinCushion.DIALOG.title,
content: PinCushion.DIALOG.content,
buttons: {
save: {
label: "Save",
icon: `<i class="fas fa-check"></i>`,
callback: html => {
return this.createNoteFromCanvas(html, data);
}
},
cancel: {
label: "Cancel",
icon: `<i class="fas fa-times"></i>`,
callback: e => {
// Maybe do something in the future
}
}
},
default: "save"
}).render(true);
}
/**
* Creates a Note from the Pin Cushion dialog
* @param {*} html
* @param {*} data
*/
async createNoteFromCanvas(html, eventData) {
const input = html.find("input[name='name']");
if (!input[0].value) {
ui.notifications.warn(game.i18n.localize("PinCushion.Warn.MissingPinName"));
return;
}
// Permissions the Journal Entry will be created with
const permission = {
[game.userId]: CONST.ENTITY_PERMISSIONS.OWNER,
default: parseInt($("#cushion-permission").val())
}
// Get folder ID for Journal Entry
let folder;
const selectedFolder = $("#cushion-folder").val();
if (selectedFolder === "none") folder = undefined;
else if (selectedFolder === "perUser") {
folder = PinCushion.getFolder(game.user.name, selectedFolder);
if (!game.user.isGM && folder === undefined) {
// Request folder creation when perUser is set and the entry is created by a user
// Since only the ID is required, instantiating a Folder from the data is not necessary
folder = (await PinCushion.requestEvent({ action: "createFolder" }))?._id;
}
} else folder = selectedFolder; // Folder is already given as ID
const entry = await JournalEntry.create({name: `${input[0].value}`, permission, ...folder && {folder}});
if (!entry) {
return;
}
// Manually add fields required by Foundry's drop handling
const entryData = entry.data.toJSON();
entryData.id = entry.id;
entryData.type = "JournalEntry";
if (canvas.activeLayer.name !== PinCushion.NOTESLAYER) {
await canvas.notes.activate();
}
await canvas.activeLayer._onDropData(eventData, entryData);
}
/**
* Request an action to be executed with GM privileges.
*
* @static
* @param {object} message - The object that will get emitted via socket
* @param {string} message.action - The specific action to execute
* @returns {Promise} The promise of the action which will be resolved after execution by the GM
*/
static requestEvent(message) {
// A request has to define what action should be executed by the GM
if (!"action" in message) return;
const promise = new Promise((resolve, reject) => {
const id = `${game.user.id}_${Date.now()}_${randomID()}`;
message.id = id;
game.pinCushion._requests[id] = {resolve, reject};
game.socket.emit(`module.${PinCushion.MODULE_NAME}`, message);
setTimeout(() => {
delete game.pinCushion._requests[id];
reject(new Error (`${PinCushion.MODULE_TITLE} | Call to ${message.action} timed out`));
}, 5000);
});
return promise;
}
/**
* Gets the JournalEntry Folder ID to be used for JournalEntry creations, if any.
*
* @static
* @param {string} name - The player name to check folders against, defaults to current user's name
* @returns {string|undefined} The folder's ID, or undefined if there is no target folder
*/
static getFolder(name, setting) {
name = name ?? game.user.name;
switch (setting) {
// No target folder set
case "none":
return undefined;
// Target folder should match the user's name
case "perUser":
return game.journal.directory.folders.find((f) => f.name === name)?.id ?? undefined;
default:
return name;
}
}
/**
* Checks for missing Journal Entry folders and creates them
*
* @static
* @private
* @returns {void}
*/
static async _createFolders() {
// Collect missing folders
const setting = game.settings.get(PinCushion.MODULE_NAME, "defaultJournalFolder");
const missingFolders = game.users
.filter((u) => !u.isGM && PinCushion.getFolder(u.name, setting) === undefined)
.map((user) => ({
name: user.name,
type: "JournalEntry",
parent: null,
sorting: "a",
}));
if (missingFolders.length) {
// Ask for folder creation confirmation in a dialog
const createFolders = await new Promise((resolve, reject) => {
new Dialog({
title: game.i18n.localize("PinCushion.CreateMissingFoldersT"),
content: game.i18n.localize("PinCushion.CreateMissingFoldersC"),
buttons: {
yes: {
label: `<i class="fas fa-check"></i> ${game.i18n.localize("Yes")}`,
callback: () => resolve(true),
},
no: {
label: `<i class="fas fa-times"></i> ${game.i18n.localize("No")}`,
callback: () => reject(),
},
},
default: "yes",
close: () => reject(),
}).render(true);
}).catch((_) => {});
// Create folders
if (createFolders) await Folder.create(missingFolders);
}
}
/**
* Replaces icon selector in Notes Config form with filepicker
* @param {*} app
* @param {*} html
* @param {*} data
*/
static _replaceIconSelector(app, html, data) {
const filePickerHtml =
`<input type="text" name="icon" title="Icon Path" class="icon-path" value="${data.data.icon}" placeholder="/icons/example.svg" data-dtype="String">
<button type="button" name="file-picker" class="file-picker" data-type="image" data-target="icon" title="Browse Files" tabindex="-1">
<i class="fas fa-file-import fa-fw"></i>
</button>`
const iconSelector = html.find("select[name='icon']");
iconSelector.replaceWith(filePickerHtml);
// Detect and activate file-picker buttons
html.find("button.file-picker").on("click", app._activateFilePicker.bind(app));
}
/* -------------------------------- Listeners ------------------------------- */
/**
* Handles doubleclicks
* @param {*} event
*/
static _onDoubleClick(event) {
if (canvas.activeLayer._hover) {
return;
}
// Silently return when note creation permissions are missing
if (!game.user.can("NOTE_CREATE")) return;
// Warn user when notes can be created, but journal entries cannot
if (!game.user.can("JOURNAL_CREATE")) {
ui.notifications.warn(
game.i18n.format("PinCushion.Warn.AllowPlayerNotes", {
permission: game.i18n.localize("PERMISSION.JournalCreate"),
})
);
return;
}
const data = {
clientX: event.data.global.x,
clientY: event.data.global.y
}
game.pinCushion._createDialog(data);
}
/**
* Socket handler
*
* @param {object} message - The socket event's content
* @param {string} message.action - The action the socket receiver should take
* @param {Data} [message.data] - The data to be used for Document actions
* @param {string} [message.id] - The ID used to handle promises
* @param {string} userId - The ID of the user emitting the socket event
* @returns {void}
*/
_onSocket(message, userId) {
const {action, data, id} = message;
const isFirstGM = game.user === game.users.find((u) => u.isGM && u.active)
// Handle resolving or rejecting promises for GM priviliged requests
if (action === "return") {
const promise = game.pinCushion._requests[message.id];
if (promise) {
delete game.pinCushion._requests[message.id];
if ("error" in message) promise.reject(message.error);
promise.resolve(data);
}
return;
}
if (!isFirstGM) return;
// Create a Journal Entry Folder
if (action === "createFolder") {
const userName = game.users.get(userId).name;
return Folder.create({ name: userName, type: "JournalEntry", parent: null, sorting: "a" })
.then((response) => {
game.socket.emit(`module.${PinCushion.MODULE_NAME}`, {
action: "return",
data: response.data,
id: id,
},
{recipients: [userId]});
})
.catch((error) => {
game.socket.emit(`module.${PinCushion.MODULE_NAME}`, {
action: "return",
error: error,
id: id,
});
});
}
}
/**
* Helper function to register settings
*/
static _registerSettings() {
game.settings.registerMenu(PinCushion.MODULE_NAME, "aboutApp", {
name: "SETTINGS.AboutAppN",
label: "SETTINGS.AboutAppN",
hint: "SETTINGS.AboutAppH",
icon: "fas fa-question",
type: PinCushionAboutApp,
restricted: false
});
game.settings.register(PinCushion.MODULE_NAME, "showJournalPreview", {
name: "SETTINGS.ShowJournalPreviewN",
hint: "SETTINGS.ShowJournalPreviewH",
scope: "client",
type: Boolean,
default: false,
config: true,
onChange: s => {
if (!s) {
delete canvas.hud.pinCushion;
}
canvas.hud.render();
}
});
game.settings.register(PinCushion.MODULE_NAME, "previewType", {
name: "SETTINGS.PreviewTypeN",
hint: "SETTINGS.PreviewTypeH",
scope: "client",
type: String,
choices: {
html: "HTML",
text: "Text Snippet"
},
default: "html",
config: true,
onChange: s => {}
});
game.settings.register(PinCushion.MODULE_NAME, "previewMaxLength", {
name: "SETTINGS.PreviewMaxLengthN",
hint: "SETTINGS.PreviewMaxLengthH",
scope: "client",
type: Number,
default: 500,
config: true,
onChange: s => {}
});
game.settings.register(PinCushion.MODULE_NAME, "previewDelay", {
name: "SETTINGS.PreviewDelayN",
hint: "SETTINGS.PreviewDelayH",
scope: "client",
type: Number,
default: 500,
config: true,
onChange: s => {}
});
game.settings.register(PinCushion.MODULE_NAME, "defaultJournalPermission", {
name: "SETTINGS.DefaultJournalPermissionN",
hint: "SETTINGS.DefaultJournalPermissionH",
scope: "world",
type: Number,
choices: Object.entries(CONST.ENTITY_PERMISSIONS).reduce((acc, [perm, key]) => {
acc[key] = game.i18n.localize(`PERMISSION.${perm}`)
return acc;
}, {}),
default: 0,
config: true,
onChange: s => {}
});
game.settings.register(PinCushion.MODULE_NAME, "defaultJournalFolder", {
name: "SETTINGS.DefaultJournalFolderN",
hint: "SETTINGS.DefaultJournalFolderH",
scope: "world",
type: String,
choices: {
none: game.i18n.localize("PinCushion.None"),
perUser: game.i18n.localize("PinCushion.PerUser"),
},
default: "none",
config: true,
onChange: s => {
// Only run check for folder creation for the main GM
if (s === "perUser" && game.user === game.users.find(u => u.isGM && u.active)) {
PinCushion._createFolders();
}
}
});
}
}
/**
* @class PinCushionHUD
*
* A HUD extension that shows the Note preview
*/
class PinCushionHUD extends BasePlaceableHUD {
constructor(note, options) {
super(note, options);
this.data = note;
}
/**
* Retrieve and override default options for this application
*/
static get defaultOptions() {
return mergeObject(super.defaultOptions, {
id: "pin-cushion-hud",
classes: [...super.defaultOptions.classes, "pin-cushion-hud"],
width: 400,
height: 200,
minimizable: false,
resizable: false,
template: "modules/pin-cushion/templates/journal-preview.html"
});
}
/**
* Get data for template
*/
getData() {
const data = super.getData();
const entry = this.object.entry;
const previewType = game.settings.get(PinCushion.MODULE_NAME, "previewType");
let content;
if (previewType === "html") {
content = TextEditor.enrichHTML(entry.data.content, {secrets: entry.isOwner, entities: true});
} else if (previewType === "text") {
const previewMaxLength = game.settings.get(PinCushion.MODULE_NAME, "previewMaxLength");
const textContent = $(entry.data.content).text();
content = textContent.length > previewMaxLength ? `${textContent.substr(0, previewMaxLength)} ...` : textContent;
}
data.title = entry.data.name;
data.body = content;
return data;
}
/**
* Set app position
*/
setPosition() {
if (!this.object) return;
const position = {
width: 400,
height: 500,
left: this.object.x,
top: this.object.y,
"font-size": canvas.grid.size / 5 + "px"
};
this.element.css(position);
}
}
/* -------------------------------------------------------------------------- */
/* Hooks */
/* -------------------------------------------------------------------------- */
/**
* Hook on init
*/
Hooks.on("init", () => {
globalThis.PinCushion = PinCushion;
PinCushion._registerSettings();
libWrapper.register(PinCushion.MODULE_NAME, "NotesLayer.prototype._onClickLeft2", PinCushion._onDoubleClick, "OVERRIDE");
});
/*
* Hook on ready
*/
Hooks.on("ready", () => {
// Instantiate PinCushion instance for central socket request handling
game.pinCushion = new PinCushion();
// Wait for game to exist, then register socket handler
game.socket.on(`module.${PinCushion.MODULE_NAME}`, game.pinCushion._onSocket);
});
/**
* Hook on note config render to inject filepicker and remove selector
*/
Hooks.on("renderNoteConfig", (app, html, data) => {
PinCushion._replaceIconSelector(app, html, data);
});
/**
* Hook on render HUD
*/
Hooks.on("renderHeadsUpDisplay", (app, html, data) => {
const showPreview = game.settings.get(PinCushion.MODULE_NAME, "showJournalPreview");
if (showPreview) {
html.append(`<template id="pin-cushion-hud"></template>`);
canvas.hud.pinCushion = new PinCushionHUD();
}
});
/**
* Hook on Note hover
*/
Hooks.on("hoverNote", (note, hovered) => {
const showPreview = game.settings.get(PinCushion.MODULE_NAME, "showJournalPreview");
const previewDelay = game.settings.get(PinCushion.MODULE_NAME, "previewDelay");
if (!showPreview) {
return;
}
if (!hovered) {
clearTimeout(game.pinCushion.hoverTimer);
return canvas.hud.pinCushion.clear();
}
if (hovered) {
game.pinCushion.hoverTimer = setTimeout(function() { canvas.hud.pinCushion.bind(note) }, previewDelay);
return;
}
});