-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtotalcms.js
More file actions
286 lines (253 loc) · 8.53 KB
/
totalcms.js
File metadata and controls
286 lines (253 loc) · 8.53 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
/**
* Total CMS API constructor
*
* This class serves as a good base class for other Total CMS
* object classes to extend. It handles all of the standard interfaces for
* communicating with Total CMS.
*
* Create global instance that will house global settings
*
* <pre>
* const totalcms = new TotalCMS({
* passport: "topsecret",
* url: "http://localhost:8000/api.php",
* });
* </pre>
*
**/
export default class TotalCMS {
// Creates an instance of TotalCMS.
constructor(options={}) {
// Create global element references
this.collection = null;
const defaults = {
passport : null,
cache : true,
cors : false,
locale : "en",
localizeStrings : {},
config : {},
url : ""
};
// get the global options and merge with defaults/arguments
const globals = typeof window.totalcms === "object" ? window.totalcms.options : {};
this.options = Object.assign({}, defaults, globals, options);
this.cache = this.options.cache;
// Auto-detect API URL from page forms if not provided
if (!this.options.url) {
const form = document.querySelector('form.totalform[data-api]');
if (form) this.options.url = form.dataset.api;
}
// Configuration options that can be set for various CMS components
this.config = this.options.config||{};
// Set up logout listeners
this.logoutListeners();
}
logoutListeners() {
const logoutElements = document.querySelectorAll('.cms-logout');
if (logoutElements.length === 0) return;
logoutElements.forEach(el => {
el.addEventListener('click', (e) => {
e.preventDefault();
window.location.href = this.buildApiQuery('/logout');
});
});
}
clearTwigCacheListeners() {
const clearCacheButtons = Array.from(document.querySelectorAll("button.cms-clear-cache,a.cms-clear-cache,.cms-clear-cache a,.cms-clear-cache button"));
clearCacheButtons.forEach(button => {
button.addEventListener("click", event => {
event.preventDefault();
this.clearTwigCache(event.target);
});
});
}
clearTwigCache(button) {
this.postAPI('/cache', {}, "DELETE").then(response => {
this.toggleButtonContent(button, "✓");
console.log("Cache Cleared", response);
});
}
toggleButtonContent(button, newContent, toggleClass, timeout = 2000) {
const originalText = button.textContent;
button.style.width = `${button.offsetWidth}px`;
if (toggleClass) button.classList.add(toggleClass);
button.textContent = newContent;
setTimeout(() => {
if (toggleClass) button.classList.remove(toggleClass);
button.textContent = originalText;
button.style.width = "";
}, timeout);
}
// Set, Get, Update config values
setConfig(key, value) {
this.config[key] = value;
}
getConfig(key) {
return this.config[key]||{};
}
updateConfig(key, value) {
this.config[key] = Object.assign({}, this.config[key], value);
}
disableCache() {
this.cache = false;
}
clearCache() {
sessionStorage.clear();
}
putAPI(api, data) {
return this.postAPI(api, data, "PUT");
}
patchAPI(api, data) {
return this.postAPI(api, data, "PATCH");
}
deleteAPI(api, data = {}) {
return this.postAPI(api, data, "DELETE");
}
// AJAX Post to the Total CMS API
postAPI(api, data, method = "POST") {
// If the POST API sets new data, we should delete form storage it if it exists
sessionStorage.removeItem(api);
let headers = { "Content-Type":"application/json" };
if (method !== "POST") headers["X-Http-Method-Override"] = method.toUpperCase();
// console.log(method, headers);
return fetch(this.buildApiQuery(api), {
method : "POST",
mode : this.options.cors ? "cors" : "same-origin",
headers : new Headers(headers),
body: JSON.stringify(data)
}).then(response => {
if (!response) {
throw new Error('No response received from server');
}
if (!response.ok) {
return response.json().then(json => {
// Handle both string errors and object errors with message property
const errorMessage = typeof json.error === 'string' ? json.error : (json.error?.message || 'Unknown error');
const error = new Error(errorMessage);
error.data = json;
throw error;
});
}
return response.json();
});
}
postFileAPI(api, data, method = "POST") {
let headers = {};
if (method !== "POST") headers["X-Http-Method-Override"] = method.toUpperCase();
// console.log(method, headers);
return fetch(this.buildApiQuery(api), {
method : "POST",
mode : this.options.cors ? "cors" : "same-origin",
headers : new Headers(headers),
body: data
}).then(response => {
if (!response) {
throw new Error('No response received from server');
}
if (!response.ok) {
return response.json().then(json => {
// Handle both string errors and object errors with message property
const errorMessage = typeof json.error === 'string' ? json.error : (json.error?.message || 'Unknown error');
const error = new Error(errorMessage);
error.data = json;
throw error;
});
}
return response.json();
});
}
// Cached API fetch
fetchCachedAPI(api) {
if (this.cache && sessionStorage.getItem(api)) {
return new Promise((resolve, reject) => {
resolve(sessionStorage.getItem(api));
});
}
return this.fetchAPI(api);
}
// GET from the Total CMS API
fetchAPI(api, method = "GET") {
let headers = {};
if (method !== "GET") headers["X-Http-Method-Override"] = method.toUpperCase();
return fetch(this.buildApiQuery(api), {
method : "GET",
mode : this.options.cors ? "cors" : "same-origin",
headers : new Headers(headers)
}).then(response => {
if (!response) {
throw new Error('No response received from server');
}
if (!response.ok) {
response.json().then(json => console.error("fetchAPI Error",json));
throw Error(response.statusText);
}
// Cache response in storage
const json = response.json();
sessionStorage.setItem(api, json);
return json;
}).catch(error => {
console.error("API Request Failed", error);
});
}
// HEAD from the Total CMS API
existsAPI(api) {
return fetch(this.buildApiQuery(api), {
method : "GET",
mode : this.options.cors ? "cors" : "same-origin",
headers : new Headers({
"X-Http-Method-Override" : "HEAD"
})
}).catch(error => {
console.error("Exists API Request Failed", error);
// Return a mock response indicating "not found" on network errors
// This allows the ID validation to continue gracefully
return { ok: false, status: 0, networkError: true };
});
}
// Utility mathod to figure out if we are on a touch device
isTouch() {
return "ontouchstart" in window || window.DocumentTouch && document instanceof DocumentTouch || false;
}
// Returns the basename of a filenaame string
basename(str) {
const base = str.substring(str.lastIndexOf("/") + 1);
const dotIndex = base.lastIndexOf(".");
if (dotIndex !== -1) {
return base.substring(0, dotIndex);
}
return base;
}
// Convert a string of HTML and return the DOM node
stringToElement(string) {
return document.createRange().createContextualFragment(string);
}
// Convert a comma delimited string to an array
stringToArray(string) {
return string.replace(/\s+/g,"").split(",").filter(Boolean);
}
listToArray(list) {
// accepts comma or space delimited lists
return list.trim().replace(/,/g," ").replace(/\s+/g,",").split(",");
}
// This is a utility method to get a parameter from the url query string
getUrlParameter(name) {
const params = new URLSearchParams(window.location.search);
return params.get(name) || false;
}
// Build a URL with a query string
buildApiQuery(api, params) {
let baseUrl = this.options.url || '';
if (!baseUrl.includes(window.location.origin)) {
baseUrl = window.location.origin + baseUrl;
}
const url = new URL(baseUrl + api);
if (typeof params === "object") {
const newParams = new URLSearchParams(params);
for (const [key, value] of newParams) {
url.searchParams.append(key, value);
}
}
return url.toString();
}
}