-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfocal-point-picker.js
421 lines (370 loc) · 10.8 KB
/
focal-point-picker.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
"use strict";
/**
* @typedef {import('jquery')} jQuery
* @typedef {import('jqueryui')} jQueryUI
*/
(($) => {
/**
* Wait for two animation frames
* @returns {Promise<void>}
*/
function nextTick() {
return new Promise((resolve) => {
requestAnimationFrame(() => {
requestAnimationFrame(() => resolve());
});
});
}
/**
* Test if the current browser supports async/await
* @returns {boolean}
*/
function supportsAsyncAwait() {
try {
new Function("return (async () => {})();");
return true;
} catch (e) {
return false;
}
}
/**
* Create an element on the fly
* @param {string} html - The HTML string to create the element from.
* @return {HTMLElement} The created element.
*/
function createElement(html) {
const template = document.createElement("template");
template.innerHTML = html;
return /** @type {HTMLElement} */ (template.content.children[0]);
}
/**
* Self-iniziating custom element for a native experience
*/
class FocalPointPicker extends HTMLElement {
/** @type {HTMLInputElement} preview */
input;
/** @type {HTMLElement} preview */
preview;
/** @type {HTMLButtonElement} handle */
handle;
/** @type {HTMLButtonElement} resetButton */
resetButton;
/** @type {boolean} dragging */
dragging = false;
defaultValue = [0.5, 0.5];
constructor() {
super();
this.input = /** @type {!HTMLInputElement} */ (
this.querySelector("input")
);
this.preview = /** @type {!HTMLInputElement} */ (
this.querySelector("[data-focalpoint-preview]")
);
this.handle = /** @type {!HTMLButtonElement} */ (
this.querySelector("[data-focalpoint-handle]")
);
this.resetButton = /** @type {!HTMLButtonElement} */ (
this.querySelector("[data-focalpoint-reset]")
);
}
/**
* Called when the element is added to the DOM
* @return {void}
*/
connectedCallback() {
if (!supportsAsyncAwait()) {
console.error("The current browser doesn't support async / await.");
return;
}
this.init();
}
/**
* Initialize everyhing when connected to the DOM
* @return {Promise<void>}
*/
async init() {
await nextTick();
if (!document.contains(this)) {
return;
}
const mediaModalRoot = this.closest(".media-frame-content");
const classicRoot = this.closest("#post-body-content");
const imageWrap = mediaModalRoot
? mediaModalRoot.querySelector(".thumbnail-image")
: classicRoot
? classicRoot.querySelector(".wp_attachment_image p")
: undefined;
if (!imageWrap) {
console.error("No imageWrap found", this);
return;
}
if (imageWrap.hasAttribute("data-fcp-wrap")) {
console.log("already initialized", this);
return;
}
imageWrap.setAttribute("data-fcp-wrap", "");
this.imageWrap = imageWrap;
this.img = this.imageWrap.querySelector("img");
if (!this.img) {
console.error("no image found in imageWrap", this.imageWrap);
return;
}
if (this.img.complete) {
this.initializeUI();
} else {
this.img.addEventListener("load", this.initializeUI, { once: true });
}
}
/**
* Clean up after us the element is removed from the DOM
* @return {void}
*/
disconnectedCallback() {
const { handle, preview, img, imageWrap, resetButton } = this;
if (preview) {
this.appendChild(preview);
}
if (handle) {
this.appendChild(handle);
}
if (img) {
img.removeEventListener("click", this.onImageClick);
}
if (imageWrap) {
imageWrap.removeAttribute("data-fcp-wrap");
}
if (resetButton) {
resetButton.removeEventListener("click", this.reset);
}
window.removeEventListener("resize", this.updateUIFromValue);
}
/**
* Initialize the user interface
* @return {void}
*/
initializeUI = () => {
const { imageWrap, img, handle, preview, resetButton } = this;
if (!imageWrap || !img) {
console.error("Some elements are missing", { imageWrap, img });
return;
}
imageWrap.appendChild(handle);
document.body.appendChild(preview);
preview.style.setProperty("--image", `url(${img.src}`);
window.addEventListener("resize", this.updateUIFromValue);
this.updateUIFromValue();
img.addEventListener("click", this.onImageClick);
resetButton.addEventListener("click", this.reset);
$(handle).on("dblclick", this.reset);
$(handle).draggable({
cancel: "none",
scroll: false,
containment: img,
start: () => {
this.dragging = true;
this.togglePreview(true);
document.body.setAttribute("data-fcp-dragging", "");
},
stop: () => {
this.dragging = false;
this.togglePreview(false);
document.body.removeAttribute("data-fcp-dragging");
$(this.input).trigger("change");
},
drag: this.applyFocalPointFromHandle,
});
};
/**
* Handle window resize event
* @return {void}
*/
updateUIFromValue = () => {
const [left, top] = this.getValueFromInput();
this.setHandlePosition(left, top);
this.updatePreview(left, top);
this.adjustResetButton(left, top);
};
/**
* Get the current focal point value from the input
* @return {number[]} The current focal point values [left, top].
*/
getValueFromInput() {
const { input } = this;
if (!input) {
console.error("no input found", { input });
return this.defaultValue;
}
const inputValue = input.value.trim();
const values = inputValue.split(" ");
if (values.length > 2) {
console.error("invalid value:", inputValue);
return this.defaultValue;
}
return values.map(function (/** @type {string} */ value) {
let number = parseFloat(value);
if (number > 1) {
number /= 100;
}
return parseFloat(number.toFixed(2));
});
}
/**
* Get the focal point from the handle position
* @return {number[]} The focal point values [left, top].
*/
getValueFromHandle() {
const { img, handle } = this;
if (!img) {
console.error("missing image", { img });
return this.defaultValue;
}
const handleRect = handle.getBoundingClientRect();
const imgRect = img.getBoundingClientRect();
const point = [
(handleRect.left - imgRect.left) / imgRect.width,
(handleRect.top - imgRect.top) / imgRect.height,
];
return point.map((number) => parseFloat(number.toFixed(2)));
}
/**
* Handle image click event
* @param {MouseEvent} e - The mouse event.
* @return {void}
*/
onImageClick = (e) => {
const { imageWrap, handle } = this;
if (!imageWrap) {
return;
}
const rect = imageWrap.getBoundingClientRect();
this.animateHandle(e.x - rect.x, e.y - rect.y).then(() => {
this.applyFocalPointFromHandle();
$(this.input).trigger("change");
});
};
/**
* Animate the handle to a position and apply the new point
* after the animation
* @param {number} left
* @param {number} top
*/
animateHandle(left, top) {
return /** @type {Promise<void>} */ (
new Promise((resolve, reject) => {
$(this.handle).animate(
{ left, top },
{
duration: 200,
complete: resolve,
},
);
})
);
}
/**
* Resets the focal point
*/
reset = () => {
if (!this.img || !this.imageWrap) {
console.error("Something went wrong while getting the image rect");
return;
}
const rect = this.img.getBoundingClientRect();
this.setHandlePosition(0.5, 0.5);
this.applyFocalPointFromHandle();
$(this.input).trigger("change");
};
/**
* Set the handle position, based on the image
* @param {number} left - The left position as a number between 0-1.
* @param {number} top - The top position as a number between 0-1.
* @return {void}
*/
setHandlePosition(left, top) {
const { img, handle } = this;
if (!img) {
return;
}
const point = {
left: img.offsetLeft + img.offsetWidth * left,
top: img.offsetTop + img.offsetHeight * top,
};
handle.style.setProperty("left", `${point.left}px`);
handle.style.setProperty("top", `${point.top}px`);
}
/**
* Apply the focal point values based on the handle position
* @return {void}
*/
applyFocalPointFromHandle = () => {
const [left, top] = this.getValueFromHandle();
this.updateInput(left, top);
this.updatePreview(left, top);
this.adjustResetButton(left, top);
};
/**
* Update the input
* @param {number} left
* @param {number} top
*/
updateInput(left, top) {
this.input.value = `${left} ${top}`;
}
/**
* Check if a value is equal to the default value
* @param {number} left
* @param {number} top
* @return {void}
*/
adjustResetButton(left, top) {
if (this.resetButton) {
this.resetButton.disabled = this.isDefaultValue(left, top);
}
}
/**
* Check if a value is equal to the default value
* @param {number} left
* @param {number} top
* @return {boolean}
*/
isDefaultValue(left, top) {
return left === this.defaultValue[0] && top === this.defaultValue[1];
}
/**
* Toggles the visibility of the preview pane
* @param {boolean} visible
* @return {void}
*/
togglePreview(visible) {
if (typeof visible !== "boolean") {
throw new Error("togglePreview expects a boolean value");
}
if (!this.preview) {
return;
}
this.preview.classList.toggle("is-visible", visible);
}
/**
* Set the preview position
* @param {number} left
* @param {number} top
* @return {void}
*/
updatePreview(left, top) {
if (!this.preview) {
return;
}
if (typeof left !== "number") {
console.error("'left' must be a number:", left);
return;
}
if (typeof top !== "number") {
console.error("'top' must be a number:", top);
return;
}
this.preview.style.setProperty("--focal-left", `${left * 100}%`);
this.preview.style.setProperty("--focal-top", `${top * 100}%`);
}
}
customElements.define("focal-point-picker", FocalPointPicker);
})(/** @type {jQuery} */ jQuery);