-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathsection.js
More file actions
84 lines (69 loc) · 2.3 KB
/
section.js
File metadata and controls
84 lines (69 loc) · 2.3 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
const ThemeEditorEventHandlerMixin = (Base) =>
class extends Base {
connectedCallback() {
if (Shopify.designMode) {
this.boundEventMap = this.createThemeEditorEventMap()
Object.entries(this.boundEventMap).forEach(([event, boundHandler]) => {
const target = event.includes('section') ? document : this
target.addEventListener(event, boundHandler)
})
if (typeof this.onSectionLoad === 'function') {
this.onSectionLoad()
}
}
}
disconnectedCallback() {
if (Shopify.designMode) {
Object.entries(this.boundEventMap).forEach(([event, boundHandler]) => {
if (event.includes('section')) {
document.removeEventListener(event, boundHandler)
}
})
if (typeof this.onSectionUnload === 'function') {
this.onSectionUnload()
}
}
}
createThemeEditorEventMap() {
const events = [
'shopify:section:select',
'shopify:section:deselect',
'shopify:section:reorder',
'shopify:block:select',
'shopify:block:deselect'
]
return events.reduce((acc, eventName) => {
const methodName = this.convertEventToMethodName(eventName)
if (typeof this[methodName] === 'function') {
acc[eventName] = this.createEventBoundHandler(this[methodName])
}
return acc
}, {})
}
convertEventToMethodName(eventName) {
const capitalize = (str) => {
return str.charAt(0).toUpperCase() + str.slice(1)
}
return `on${eventName.split(':').slice(1).map(capitalize).join('')}`
}
createEventBoundHandler(handler) {
return (event) => {
if (event.detail && event.detail.sectionId === this.sectionId) {
handler.call(this, event)
}
}
}
}
class Section extends HTMLElement {
get sectionId() {
if (!this._sectionId) {
this._sectionId = this.getAttribute('section-id') || this.extractSectionId(this)
}
return this._sectionId
}
extractSectionId(element) {
element = element.classList.contains('shopify-section') ? element : element.closest('.shopify-section')
return element.id.replace('shopify-section-', '')
}
}
export class HTMLSectionElement extends ThemeEditorEventHandlerMixin(Section) {}