generated from adobe/aem-boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 175
/
Copy pathaem-fragment.js
176 lines (150 loc) · 4.3 KB
/
aem-fragment.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
import { EVENT_AEM_LOAD, EVENT_AEM_ERROR } from './constants.js';
import { getFragmentById } from './getFragmentById.js';
const sheet = new CSSStyleSheet();
sheet.replaceSync(':host { display: contents; }');
const baseUrl =
document.querySelector('meta[name="aem-base-url"]')?.content ??
'https://publish-p22655-e155390.adobeaemcloud.com';
const ATTRIBUTE_FRAGMENT = 'fragment';
const ATTRIBUTE_IMS = 'ims';
let headers;
class FragmentCache {
#fragmentCache = new Map();
clear() {
this.#fragmentCache.clear();
}
add(...fragments) {
fragments.forEach((fragment) => {
const { id: fragmentId } = fragment;
if (fragmentId) {
this.#fragmentCache.set(fragmentId, fragment);
}
});
}
has(fragmentId) {
return this.#fragmentCache.has(fragmentId);
}
get(fragmentId) {
return this.#fragmentCache.get(fragmentId);
}
remove(fragmentId) {
this.#fragmentCache.delete(fragmentId);
}
}
const cache = new FragmentCache();
/**
* Custom element representing an aem fragment.
*
* @attr {string} title - fragment title, optional.
* @attr {string} fragment - fragment id.
*/
export class AemFragment extends HTMLElement {
cache = cache;
data;
/**
* @type {string} fragment id
*/
fragmentId;
/**
* Consonant styling for CTAs.
*/
consonant = false;
/**
* @type {boolean} whether an access token should be used via IMS.
*/
ims = false;
/**
* Internal promise to track the readiness of the web-component to render.
*/
_readyPromise;
static get observedAttributes() {
return [ATTRIBUTE_FRAGMENT];
}
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.adoptedStyleSheets = [sheet];
const ims = this.getAttribute(ATTRIBUTE_IMS);
if (['', true].includes(ims)) {
this.ims = true;
if (!headers) {
headers = {
Authorization: `Bearer ${window.adobeid?.authorize?.()}`,
pragma: 'no-cache',
'cache-control': 'no-cache',
};
}
} else {
this.ims = false;
}
}
attributeChangedCallback(name, oldValue, newValue) {
if (name === ATTRIBUTE_FRAGMENT) {
this.fragmentId = newValue;
this.refresh(false);
}
}
connectedCallback() {
if (!this.fragmentId) {
this.#fail('Missing fragment id');
return;
}
}
async refresh(flushCache = true) {
if (this._readyPromise) {
const ready = await Promise.race([
this._readyPromise,
Promise.resolve(false),
]);
if (!ready) return; // already fetching data
}
if (flushCache) {
cache.remove(this.fragmentId);
}
this._readyPromise = this.fetchData()
.then(() => {
this.dispatchEvent(
new CustomEvent(EVENT_AEM_LOAD, {
detail: this.data,
bubbles: true,
composed: true,
}),
);
return true;
})
.catch(() => {
this.#fail('Network error: failed to load fragment');
this._readyPromise = null;
return false;
});
}
#fail(error) {
this.classList.add('error');
this.dispatchEvent(
new CustomEvent(EVENT_AEM_ERROR, {
detail: error,
bubbles: true,
composed: true,
}),
);
}
async fetchData() {
let fragment = cache.get(this.fragmentId);
if (!fragment) {
fragment = await getFragmentById(
baseUrl,
this.fragmentId,
this.ims ? headers : undefined,
);
cache.add(fragment);
}
this.data = fragment;
}
get updateComplete() {
return (
this._readyPromise ??
Promise.reject(new Error('AEM fragment cannot be loaded'))
);
}
}
customElements.define('aem-fragment', AemFragment);