Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
374 lines (349 loc) · 9.74 KB
/
Copy pathindex.js
File metadata and controls
374 lines (349 loc) · 9.74 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
// add injected methods to entire app
import "@helpers/utilityMethods.js";
// frameworks
import Vue from "vue";
import VueRouter from "vue-router";
import Vuetify from "vuetify";
// general dependencies
import axios from "axios";
import { DateTime } from "luxon";
import DOMPurify from "dompurify";
import { marked } from "marked";
import { createPinia, mapState } from "pinia";
// pinia stores
import authStore from "./stores/authStore.js";
import translationStore from "./stores/translationStore.js";
import themeStore from "./stores/themeStore.js";
// layout components and tabs
import ALL_TABS from "@helpers/tabs.js";
import NavAppBar from "@components/navbar/index.vue";
import NavSidebar from "@components/sidebar/index.vue";
import NavFooter from "@components/nav-footer.vue";
import SnackbarStatus from "@components/snackbar-status.vue";
import LoadingPage from "@layouts/loading-page.vue";
import MissingPage from "./pages/404/index.vue";
Vue.config.devtools = import.meta.env.MODE === "development";
Vue.use(Vuetify);
Vue.use(VueRouter);
const pinia = createPinia();
Vue.use(pinia);
/**
* PWA REGISTRATION
*/
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("/service-worker.js").catch((err) => {
console.error("Failed to register PWA Service Worker:", err);
});
}
/**
* ROUTING
*/
const router = new VueRouter({
mode: "history",
});
router.beforeEach((to, _from, next) => {
Vue.nextTick(() => {
if (to.name) document.title = `${to.name} - Faithful Studio`;
else document.title = "Faithful Studio";
});
// redirect to dashboard if base url
if (to.fullPath === "/") {
next("/dashboard");
return;
}
// replace hash router (legacy urls) with history router
if (["/#", "/?#"].some((p) => to.fullPath.startsWith(p))) {
const path = to.fullPath.replace("/#", "").replace("/?#", "");
next(path);
return;
}
next();
});
window.apiURL = import.meta.env.VITE_API_URL;
// fix trailing slash
if (apiURL.endsWith("/")) window.apiURL = window.apiURL.slice(0, -1);
function syncRoutes(routes) {
// accepts any number of routes
const curRoutes = router.getRoutes().map((r) => r.path);
const diff = routes.filter((r) => !curRoutes.includes(r.path));
diff.forEach((r) => router.addRoute(r));
}
// add all public routes
syncRoutes(
ALL_TABS.filter((t) => t.roles === undefined)
.flatMap((t) => t.subtabs)
.filter((s) => s.public)
.flatMap((s) => s.routes),
);
// add missing route last (prevents some weird fallback shenanigans)
router.addRoute({ path: "*", name: "404", component: MissingPage });
// needed for some pages to not completely die
window.settings = {};
const DARK_SIDEBAR_KEY = "sidebar_dark";
const SIDEBAR_OPEN_KEY = "sidebar_open";
/**
* VUE INITIALIZATION
*/
const app = new Vue({
el: "#app",
components: {
NavAppBar,
NavSidebar,
NavFooter,
SnackbarStatus,
LoadingPage,
},
data() {
return {
auth: authStore(),
translation: translationStore(),
theme: themeStore(),
darkSidebar: localStorage.getItem(DARK_SIDEBAR_KEY) === "true" || false,
sidebarOpen: localStorage.getItem(SIDEBAR_OPEN_KEY)
? localStorage.getItem(SIDEBAR_OPEN_KEY) === "true"
: !this.$vuetify.breakpoint.mobile,
badgeData: {},
snackbars: {},
settingsLoaded: false,
loginResolved: false,
showActions: false,
};
},
methods: {
/** log reactive object */
log(...objs) {
const cleaned = structuredClone(objs);
console.log(cleaned);
},
/** for debugging snackbars */
testSnackbars() {
this.showSnackbar(
"Success title\nLorem ipsum dolor sit amet, consectetur adipiscing elit.",
"success",
{ timeout: -1 },
);
this.showSnackbar(
"Info title\nLorem ipsum dolor sit amet, consectetur adipiscing elit.",
"info",
{ timeout: -1 },
);
this.showSnackbar(
"Warning title\nLorem ipsum dolor sit amet, consectetur adipiscing elit.",
"warning",
{ timeout: -1 },
);
this.showSnackbar(
"Error title\nLorem ipsum dolor sit amet, consectetur adipiscing elit.",
"error",
{ timeout: -1 },
);
this.showSnackbar(
"Custom title\nLorem ipsum dolor sit amet, consectetur adipiscing elit.",
"purple",
{ timeout: -1, icon: "mdi-star-circle-outline" },
);
},
async loadBadge(cb, key) {
if (!this.isAdmin) return;
// use await to prevent sync callbacks not having a then() method
const value = await cb(this);
this.$set(this.badgeData, key, value);
// since it's recursive you don't need setInterval
return setTimeout(() => this.loadBadge(cb, key), 30000);
},
showSnackbar(message, type, { timeout, icon } = {}) {
// can surgically remove keys without affecting other indices so we use a record
const key = crypto.randomUUID();
this.$set(this.snackbars, key, { message, type, timeout, icon });
return key;
},
closeSnackbar(id) {
this.$delete(this.snackbars, id);
},
// this is such a common operation it should really be a macro
async wrapSnackbar(promise, successMessage = "") {
try {
const result = await promise;
this.showSnackbar(successMessage || this.lang().global.success_message, "success");
// so it can still be used
return result;
} catch (err) {
console.error(err);
this.showSnackbar(err, "error");
// re-throw so it doesn't accidentally trigger the .then handler
throw err;
}
},
compileMarkdown(rawText) {
if (!rawText) return "";
return DOMPurify.sanitize(marked(rawText));
},
// DATE_MED is the most common (e.g. Mar 15, 2026)
formatDate(date, format = DateTime.DATE_MED) {
// wrap the date so you can pass in anything the date constructor accepts
// e.g. unix timestamps YMD dates etc
return DateTime.fromJSDate(new Date(date))
.setLocale(this.translation.current.bcp47)
.toLocaleString(format);
},
syncRoutes(tabs) {
return syncRoutes(tabs.flatMap((r) => r.subtabs).flatMap((s) => s.routes));
},
async reloadSettings() {
this.settingsLoaded = false;
try {
window.settings = await axios.get(`${window.apiURL}/settings/raw`).then((res) => res.data);
this.settingsLoaded = true;
} catch (err) {
this.showSnackbar(err, "error");
}
},
},
computed: {
// the entire user store state becomes the user property
...mapState(authStore, {
user: (store) => store.$state,
}),
...mapState(translationStore, {
lang: (store) => store.lang,
}),
loginURL() {
return `${this.apiURL}/auth/discord/studio`;
},
apiURL() {
if (
Vue.config.devtools &&
window.apiURL &&
window.apiURL.includes("localhost") &&
location.host !== "localhost"
)
return window.apiURL.replace("localhost", location.host.split(":")[0]);
return window.apiURL;
},
apiOptions() {
// can be adjusted with new auth values as needed
return {
headers: { discord: this.user.access_token },
};
},
/**
* Check user perms & add (or not) tabs & routes following user perms
* @returns all tabs to be added in the html
*/
availableTabs() {
return (
ALL_TABS
// first filter categories
.filter((tab) => !tab.roles || tab.roles.some((r) => this.userRoles.includes(r)))
.map((tab) => ({
// must create a new object so if the user logs in the old tabs aren't deleted
...tab,
subtabs: tab.subtabs
.filter((subtab) => {
if (subtab.public) return true;
// if there's no roles then it's available to all logged in users
if (!subtab.roles) return this.isLoggedIn;
return subtab.roles.some((r) => this.userRoles.includes(r));
})
.map((s) => {
s.to = s.routes[0].cleanPath || s.routes[0].path;
return s;
}),
}))
// then when subtabs are filtered filter again
.filter((tab) => tab.subtabs.length)
);
},
/**
* Tell if the user is logged in
*/
isLoggedIn() {
return this.user && this.user.id && this.user.id !== undefined;
},
/**
* Tell if the user has administrator permissions (manager/dev)
*/
isAdmin() {
// if not logged in
if (!this.isLoggedIn) return false;
// if user not loaded
if (!this.user) return false;
// check roles
return this.user.roles.includes("Administrator");
},
/**
* Get user's roles in real time
* @returns user discord roles
*/
userRoles() {
return this.user.roles;
},
appLoading() {
return !this.settingsLoaded || !this.loginResolved;
},
},
watch: {
// bit more granular than subscribing to the whole store
"theme.isDark": {
handler(n) {
this.$vuetify.theme.dark = n;
},
immediate: true,
deep: true,
},
darkSidebar(n) {
localStorage.setItem(DARK_SIDEBAR_KEY, String(n));
},
sidebarOpen(n) {
// don't set preference on small screens (pointless)
if (this.$vuetify.breakpoint.mobile) return;
localStorage.setItem(SIDEBAR_OPEN_KEY, String(n));
},
userRoles(n) {
if (!Array.isArray(n)) return;
// add all routes with no role
this.$nextTick(() => {
this.availableTabs
.flatMap((t) => t.subtabs)
.filter((s) => s.badge)
.forEach((s) => this.loadBadge(s.badge, s.id));
});
},
availableTabs(n) {
this.syncRoutes(n);
},
},
created() {
// can't load after five seconds, show error message
setTimeout(() => {
this.showActions = true;
}, 5000);
if (this.$vuetify.breakpoint.mdAndDown) this.sidebarOpen = false;
this.reloadSettings();
this.translation.setup();
this.theme.setup(this);
this.auth.login(this, Vue.config.devtools);
},
// plugins
router,
vuetify: new Vuetify({
theme: {
dark: true,
themes: {
dark: {
primary: "#76c945",
accent: "#00a2ff",
success: "#22a831",
},
light: {
primary: "#4ea229",
// lightest fully accessible color (easier to style around)
secondary: "#757575",
accent: "#00a2ff",
success: "#22a831",
},
},
},
}),
});
if (Vue.config.devtools) window.app = app;