-
-
Notifications
You must be signed in to change notification settings - Fork 322
Expand file tree
/
Copy pathelement_editor.js
More file actions
605 lines (543 loc) · 15.1 KB
/
element_editor.js
File metadata and controls
605 lines (543 loc) · 15.1 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
import IngredientAnchorLink from "alchemy_admin/ingredient_anchor_link"
import { post } from "alchemy_admin/utils/ajax"
import { createHtmlElement } from "alchemy_admin/utils/dom_helpers"
import { growl } from "alchemy_admin/growler"
import "alchemy_admin/components/element_editor/publish_element_button"
import "alchemy_admin/components/element_editor/delete_element_button"
export function dispatchPageDirtyEvent(data) {
document.dispatchEvent(
new CustomEvent("alchemy:page-dirty", {
detail: { tooltip: data.publishButtonTooltip }
})
)
}
export class ElementEditor extends HTMLElement {
#form = null
#header = null
#toggleButton = null
connectedCallback() {
// The placeholder while be being dragged is empty.
if (this.classList.contains("ui-sortable-placeholder")) {
return
}
// Add event listeners
this.addEventListener("click", this)
// Triggered by child elements
this.addEventListener("alchemy:element-update-title", this)
// We use of @rails/ujs for Rails remote forms
this.addEventListener("ajax:complete", this)
// Dirty observer still needs to be jQuery
// in order to support select2.
this.#form = this.form
if (this.#form) {
$(this.#form).on("change", this.onChange)
}
this.#header = this.header
this.#header?.addEventListener("dblclick", this.#onHeaderDblclick)
this.#toggleButton = this.toggleButton
this.#toggleButton?.addEventListener("click", this.#onToggleClick)
// When newly created, focus the element and refresh the preview
if (this.hasAttribute("created")) {
this.focusElement()
this.previewWindow?.refresh().then(() => {
this.focusElementPreview()
})
this.removeAttribute("created")
}
}
disconnectedCallback() {
this.removeEventListener("click", this)
this.removeEventListener("alchemy:element-update-title", this)
this.removeEventListener("ajax:complete", this)
if (this.#form) {
$(this.#form).off("change", this.onChange)
this.#form = null
}
this.#header?.removeEventListener("dblclick", this.#onHeaderDblclick)
this.#header = null
this.#toggleButton?.removeEventListener("click", this.#onToggleClick)
this.#toggleButton = null
}
handleEvent(event) {
switch (event.type) {
case "click":
const elementEditor = event.target.closest("alchemy-element-editor")
if (elementEditor === this) {
this.onClickElement()
}
break
case "ajax:complete":
if (event.target === this.body) {
const xhr = event.detail[0]
event.stopPropagation()
this.onSaveElement(xhr)
}
break
case "alchemy:element-update-title":
if (!this.hasEditors && event.target == this.firstChild) {
this.setTitle(event.detail.title)
}
break
}
}
onChange = (event) => {
const target = event.target
// SortableJS fires a native change event :/
// and we do not want to set the element editor dirty
// when this happens
if (target.classList.contains("nested-elements")) {
return
}
this.setDirty(target)
event.stopPropagation()
return false
}
/**
* Scrolls to and highlights element
* Expands if collapsed
* Also chooses the right fixed elements tab, if necessary.
* Can be triggered through custom event 'FocusElementEditor.Alchemy'
* Used by the elements on click events in the preview frame.
*/
async focusElement() {
// Select tab if necessary
if (document.querySelector("#fixed-elements")) {
await this.selectTabForElement()
}
// Expand if necessary
await this.expand()
this.selectElement(true)
}
focusElementPreview() {
this.previewWindow?.postMessage({
message: "Alchemy.focusElement",
element_id: this.elementId
})
}
onClickElement() {
this.selectElement()
this.focusElementPreview()
}
/**
* Sets the element to saved state
* Updates title
* JS event bubbling will also update the parents element quote.
* Shows error messages if ingredient validations fail
* @argument {XMLHttpRequest} xhr
*/
onSaveElement(xhr) {
const data = JSON.parse(xhr.responseText)
// Reset errors that might be visible from last save attempt
this.setClean()
// If validation failed
if (xhr.status === 422) {
const warning = data.warning
// Create error messages
// Mark ingredients as failed
data.ingredientsWithErrors.forEach((ingredient) => {
const ingredientEditor = this.querySelector(
`[data-ingredient-id="${ingredient.id}"]`
)
const errorDisplay = createHtmlElement(
`<small class="error">${ingredient.errorMessage}</small>`
)
ingredientEditor?.appendChild(errorDisplay)
ingredientEditor?.classList.add("validation_failed")
})
// Show message
growl(warning, "warn")
this.elementErrors.classList.remove("hidden")
} else {
growl(data.notice)
this.previewWindow?.refresh().then(() => {
this.focusElementPreview()
})
this.updateTitle(data.previewText)
data.ingredientAnchors.forEach((anchor) => {
IngredientAnchorLink.updateIcon(anchor.ingredientId, anchor.active)
})
if (data.pageHasUnpublishedChanges) {
dispatchPageDirtyEvent(data)
}
}
}
/**
* Smoothly scrolls to element
*/
scrollToElement() {
// The timeout gives the browser some time to calculate the position
// of nested elements correctly
setTimeout(() => {
this.scrollIntoView({
behavior: "smooth"
})
}, 50)
}
/**
* Highlight element and optionally scroll into view
* @param {boolean} scroll smoothly scroll element into view. Default (false)
*/
selectElement(scroll = false) {
document
.querySelectorAll("alchemy-element-editor.selected")
.forEach((el) => {
el.classList.remove("selected")
})
window.requestAnimationFrame(() => {
this.classList.add("selected")
})
if (scroll) this.scrollToElement()
}
/**
* Selects tab for given element
* Resolves the promise if this is done.
* @returns {Promise}
*/
selectTabForElement() {
return new Promise((resolve, reject) => {
const tabs = document.querySelector("#fixed-elements")
const panel = this.closest("sl-tab-panel")
if (tabs && panel) {
tabs.show(panel.getAttribute("name"))
resolve()
} else {
reject(new Error("No tabs present"))
}
})
}
/**
* Sets the element into clean (safed) state
*/
setClean() {
this.dirty = false
window.onbeforeunload = null
this.elementErrors.classList.add("hidden")
if (this.hasEditors) {
this.body.querySelectorAll(".ingredient-editor").forEach((el) => {
el.classList.remove("dirty", "validation_failed")
el.querySelectorAll("small.error").forEach((e) => e.remove())
})
}
}
/**
* Sets the element into dirty (unsafed) state
* @param {HTMLElement} editor
*/
setDirty(editor) {
if (this.hasEditors) {
this.dirty = true
if (!window.onbeforeunload) {
window.onbeforeunload = (event) => event.preventDefault()
}
editor?.closest(".ingredient-editor")?.classList.add("dirty")
}
}
/**
* Sets the title quote
* @param {string} title
*/
setTitle(title) {
const quote = this.querySelector(".element-header .preview_text_quote")
quote.textContent = title
}
/**
* Expands or collapses element editor
* If the element is dirty (has unsaved changes) it displays a confirm first.
*/
async toggle() {
if (this.collapsed) {
await this.expand()
} else {
await this.collapse()
}
}
/**
* Collapses the element editor and persists the state on the server
* @returns {Promise}
*/
collapse() {
if (this.collapsed || this.compact || this.fixed) {
return Promise.resolve("Element is already collapsed.")
}
const spinner = new Alchemy.Spinner("small")
spinner.spin(this.toggleButton)
this.toggleIcon?.classList?.add("hidden")
return post(Alchemy.routes.collapse_admin_element_path(this.elementId))
.then((response) => {
const data = response.data
this.collapsed = true
this.toggleButton?.setAttribute("title", data.title)
// Collapse all nested elements if necessarry
if (data.nestedElementIds.length) {
const selector = data.nestedElementIds
.map((id) => `#element_${id}`)
.join(", ")
this.querySelectorAll(selector).forEach((nestedElement) => {
nestedElement.collapsed = true
nestedElement.toggleButton?.setAttribute("title", data.title)
})
}
})
.catch((error) => {
growl(error.message, "error")
console.error(error)
})
.finally(() => {
this.toggleIcon?.classList?.remove("hidden")
spinner.stop()
})
}
/**
* Collapses the element editor and persists the state on the server
* @* @returns {Promise}
*/
expand() {
if (this.expanded && !this.compact) {
return Promise.resolve("Element is already expanded.")
}
if (this.compact && this.parentElementEditor) {
return this.parentElementEditor.expand()
} else {
const spinner = new Alchemy.Spinner("small")
spinner.spin(this.toggleButton)
this.toggleIcon?.classList.add("hidden")
return new Promise((resolve, reject) => {
post(Alchemy.routes.expand_admin_element_path(this.elementId))
.then((response) => {
const data = response.data
// First expand all parent elements if necessary
if (data.parentElementIds.length) {
const selector = data.parentElementIds
.map((id) => `#element_${id}`)
.join(", ")
document.querySelectorAll(selector).forEach((parentElement) => {
parentElement.collapsed = false
parentElement.toggleButton?.setAttribute("title", data.title)
})
}
// Finally expand ourselve
this.collapsed = false
this.toggleButton?.setAttribute("title", data.title)
// Resolve the promise that scrolls to the element very last
resolve()
})
.catch((error) => {
growl(error.message, "error")
console.error(error)
reject(error)
})
.finally(() => {
this.toggleIcon?.classList?.remove("hidden")
spinner.stop()
})
})
}
}
/**
* Updates the quote in the element header and dispatches event
* to parent elements
* @param {string} title
*/
updateTitle(title) {
this.setTitle(title)
this.dispatchEvent(
new CustomEvent("alchemy:element-update-title", {
bubbles: true,
detail: { title }
})
)
}
/**
* Sets element published or hidden
* @param {boolean}
*/
set published(isPublished) {
if (isPublished) {
this.classList.remove("element-hidden")
} else {
this.classList.add("element-hidden")
}
}
/**
* Is element published or hidden
* @returns {boolean}
*/
get published() {
return !this.classList.contains("hidden")
}
/**
* @returns {boolean}
*/
get compact() {
return this.getAttribute("compact") !== null
}
/**
* @returns {boolean}
*/
get fixed() {
return this.getAttribute("fixed") !== null
}
/**
* @param {boolean} value
*/
set collapsed(value) {
this.classList.toggle("folded", value)
this.classList.toggle("expanded", !value)
this.toggleIcon &&
(this.toggleIcon.name = value ? "arrow-left-s" : "arrow-down-s")
}
/**
* @returns {boolean}
*/
get collapsed() {
return this.classList.contains("folded")
}
/**
* @returns {boolean}
*/
get expanded() {
return !this.collapsed
}
/**
* Toggles the dirty class
*
* @param {boolean} value
*/
set dirty(value) {
this.classList.toggle("dirty", value)
}
/**
* Returns the dirty state of this element
*
* @returns {boolean}
*/
get dirty() {
return this.classList.contains("dirty")
}
/**
* Returns the element header
*
* @returns {HTMLElement|undefined}
*/
get header() {
return this.querySelector(`.element-header`)
}
/**
* Returns the immediate body container of this element if present
*
* Makes sure it does not return a nested elements body
* by scoping the selector to this elements id.
*
* @returns {HTMLElement|undefined}
*/
get body() {
return this.querySelector(this.bodySelector)
}
get bodySelector() {
return `#${this.id} > .element-body`
}
/**
* Returns the immediate footer container of this element if present
*
* Makes sure it does not return a nested elements footer
* by scoping the selector to this elements id.
*
* @returns {HTMLElement|undefined}
*/
get footer() {
return this.querySelector(`#${this.id} > .element-footer`)
}
/**
* The collapse/expand toggle button
*
* @returns {HTMLButtonElement|undefined}
*/
get toggleButton() {
return this.querySelector(".element-toggle")
}
/**
* The collapse/expand toggle buttons icon
*
* @returns {HTMLElement|undefined}
*/
get toggleIcon() {
return this.toggleButton?.querySelector("alchemy-icon")
}
/**
* The validation messages list container
*
* @returns {HTMLElement}
*/
get elementErrors() {
return this.body.querySelector(".element_errors")
}
/**
* The element database id
*
* @returns {string}
*/
get elementId() {
return this.dataset.elementId
}
/**
* The element defintion name
*
* @returns {string}
*/
get elementName() {
return this.dataset.elementName
}
/**
* Does this element have ingredient editor fields?
*
* @returns {boolean}
*/
get hasEditors() {
return !!this.body?.querySelector(".element-ingredient-editors")
}
/**
* Does this element have nested elements?
*
* @returns {boolean}
*/
get hasChildren() {
return !!this.querySelector(".nested-elements")
}
/**
* The first child element editor if present
*
* @returns {HTMLButtonElement|undefined}
*/
get firstChild() {
return this.querySelector("alchemy-element-editor")
}
/**
* The form element if present
*
* @returns {HTMLFormElement|undefined}
*/
get form() {
return this.querySelector("form.element-body")
}
/**
* The parent element editor if present
*
* @returns {ElementEditor|undefined}
*/
get parentElementEditor() {
return this.parentElement?.closest("alchemy-element-editor")
}
get previewWindow() {
return document.getElementById("alchemy_preview_window")
}
#onHeaderDblclick = () => {
this.toggle()
}
#onToggleClick = (evt) => {
const elementEditor = evt.target.closest("alchemy-element-editor")
if (elementEditor === this) {
this.toggle()
}
}
}
customElements.define("alchemy-element-editor", ElementEditor)