-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathScenery.js
218 lines (200 loc) · 7.19 KB
/
Scenery.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
import { PATH } from '../helpers.js';
export default class Scenery extends FormApplication {
constructor(id) {
super();
this.scene = game.scenes.get(id);
}
static get defaultOptions() {
return mergeObject(super.defaultOptions, {
classes: ['form'],
closeOnSubmit: true,
popOut: true,
editable: game.user.isGM,
width: 700,
template: `${PATH}/templates/scenery.hbs`,
id: 'scenery-config',
title: game.i18n.localize('SCENERY.scenery'),
});
}
/* -------------------------------------------- */
/**
* Obtain module metadata and merge it with game settings which track current module visibility
* @return {Object} The data provided to the template when rendering the form
*/
async getData() {
const flag = this.scene.getFlag('scenery', 'data') || {};
if (!this.bg) this.bg = flag.bg || this.scene.data.img;
if (!this.gm) this.gm = flag.gm || this.scene.data.img;
if (!this.pl) this.pl = flag.pl || this.scene.data.img;
if (!this.variations) {
this.variations = [{ name: 'Default', file: this.bg }];
if (flag.variations) flag.variations.forEach((v) => this.variations.push(v));
}
// Add extra empty variation
this.variations.push({ name: '', file: '' });
// Return data to the template
return { variations: this.variations, gm: this.gm, pl: this.pl };
}
/* -------------------------------------------- */
/* Event Listeners and Handlers */
/* -------------------------------------------- */
/** @override */
activateListeners(html) {
html.find('.delete').click(() => this.deleteVariation());
html.find('.preview').click(() => this.previewVariation());
html.find('.scan').click(() => this.scan());
html.find('.add').click(() => this.add());
super.activateListeners(html);
}
/**
* Display a preview window of the scene
* @param {HTMLCollection} html the html of the form
*/
previewVariation() {
const index = document.activeElement.getAttribute('index');
const url = this.element.find(`#scenery-row-${index} .image`)[0].value;
new ImagePopout(url).render(true);
}
/**
* Remove a row in the variation table
* @param {HTMLCollection} html the html of the form
*/
deleteVariation(index = false) {
if (!index) index = document.activeElement.getAttribute('index');
this.element.find(`#scenery-row-${index}`).remove();
}
removeBlankVariations() {
this.element.find('tr').each((i, el) => {
const file = $(el).find('.scenery-fp input').val();
const name = $(el).find('.scenery-name input').val();
const index = $(el).attr('index');
if (!file && !name) this.deleteVariation(index);
});
}
/**
* Add a new empty row to the form
* @param {Object} formData
*/
async addVariation(name = '', file = '', id = null) {
if (id === null) id = Number(this.element.find('tr:last').attr('index')) + 1;
const row = $(await renderTemplate(`${PATH}/templates/variation.hbs`, { id, name, file }));
row.find('.delete').click(() => this.deleteVariation());
row.find('.preview').click(() => this.previewVariation());
await this.element.find('.scenery-table').append(row);
super.activateListeners(this.element);
}
/**
* This method is called upon form submission after form data is validated
* @param {Event} event The initial triggering submission event
* @param {Object} formData The object of validated form data with which to update the object
* @private
*/
async _updateObject(event, formData) {
const fd = expandObject(formData);
const bg = fd.variations[0].file;
const variations = Object.values(fd.variations)
.slice(1)
.filter((v) => v.file);
const gm = fd.variations[$('input[name="gm"]:checked').val()]?.file;
const pl = fd.variations[$('input[name="pl"]:checked').val()]?.file;
if (!gm || !pl) {
ui.notifications.error(game.i18n.localize('SCENERY.selectError'));
return;
}
const data = { variations, bg, gm, pl };
await this.scene.update({ img: bg });
this.scene.setFlag('scenery', 'data', data);
}
/**
* Scan for variations in current directory of default img
*/
async scan() {
// Get path fo default img
const path = this.element.find('[name="variations.0.file"]')[0].value;
// Load list of files in current dir
const fp = await FilePicker.browse('data', path);
// Isolate file name and remove extension
const defName = path.split('/').pop().split('.').slice(0, -1).join('.');
// For each file in directory...
const variations = fp.files
// Remove default file
.filter((f) => f !== path)
// Find only files which are derivatives of default
.reduce((acc, file) => {
// Isolate filename and remove extension
const fn = file.split('/').pop().split('.').slice(0, -1).join('.');
// If is a derivative...
if (fn.toLowerCase().includes(defName.toLowerCase())) {
// Remove crud from filename
const name = fn.replace(defName, '').replace(/[-_]/g, ' ').replace(/[^a-zA-Z\d\s:]/g, '').trim();
// Add to found array
acc.push({ file, name });
}
return acc;
}, []);
this.removeBlankVariations();
// eslint-disable-next-line no-restricted-syntax
let index = Number(this.element.find('tr:last').attr('index')) + 1;
variations.forEach((v) => {
this.addVariation(v.name, v.file, index);
index++;
});
}
/**
* Add a new empty row to the form
*/
add() {
this.addVariation();
}
/**
* Sets background image of the current scene
* @param {String} img The image URL to be used
* @param {Boolean} draw Used to prevent draw if being called during canvasInit
*/
static async setImage(img, draw = true) {
canvas.scene.data.img = img;
if (draw) {
// Wait for texture to load
await TextureLoader.loader.load([img], game.i18n.localize('SCENERY.loading'));
canvas.draw();
// Backup draw because occasionally above seems to fail
await new Promise((resolve) => setTimeout(resolve, 1000));
canvas.draw();
}
}
/**
* React to canvasInit hook to set custom image if needed
*/
static _onCanvasInit() {
const data = canvas.scene.getFlag('scenery', 'data');
if (!data) return;
const img = (game.user.isGM) ? data.gm : data.pl;
if (img) Scenery.setImage(img, false);
}
/**
* React to updateScene hook to set custom image if needed
* @param {Scene} scene
* @param {Object} data
*/
static _onUpdateScene(scene, data) {
if (!scene._view) return;
if (hasProperty(data, 'flags.scenery.data')) {
const img = (game.user.isGM) ? data.flags.scenery.data.gm : data.flags.scenery.data.pl;
if (img) {
Scenery.setImage(img);
}
}
}
static _onContextMenu(html, entryOptions) {
const viewOption = {
name: game.i18n.localize('SCENERY.scenery'),
icon: '<i class="fas fa-images"></i>',
condition: () => game.user.isGM,
callback: (el) => {
const id = el.attr('data-document-id') || el.attr('data-entity-id') || el.attr('data-scene-id');
new Scenery(id).render(true);
},
};
entryOptions.push(viewOption);
}
}