blob: 2b1205099d6bf4b854ce3860343dc3c0f1d773b7 [file] [log] [blame]
jdc6ea0e2022-04-26 16:03:27 -07001/**
2 * @file Fluid UI JavaScript Modules
3 * @author jottocraft
4 * @version v5.0.0-dep
5 *
6 * @copyright Made by jottocraft 2017-2021. All code in this repository is in the public domain (https://github.com/jottocraft/fluid-old/blob/master/LICENSE).
7 * @license unlicense
8 */
9
10/**
11 * Global Fluid UI object.
12 * All global Fluid UI functions and variables are stored in this object.
13 *
14 * @global
15 * @namespace fluid
16 * @property {object} screens Fluid UI screens object containing functions for local screens and URLs for external screens
17 * @property {object} externalScreens Contains all of the functions for external screens, which are added to this object as needed
18 * @property {string[]} includedThemes The list of color theme IDs included in this version of Fluid UI. This should NOT be changed for custom themes.
19 * @property {Object.<string, Theme>} themes Contains all of the color theme objects
20 * @property {FluidConfig} config Fluid UI configuration variables
21 */
22var fluid = {
23 screens: {},
24 externalScreens: {},
25 includedThemes: ["midnight", "tome"],
26 themes: {
27 /**
28 * @typedef {object} Theme
29 * @description Color theme objects
30 * @property {string} name Theme display name
31 * @property {string} icon Theme icon
32 * @property {'light'|'dark'} type Theme type. Must be "light" if the theme uses dark text on a light background or "dark" if the theme uses light text on a dark background.
33 * @property {ThemeColors} [colors] Contains all of the theme colors. This can be omitted if there is CSS for the theme.
34 * @property {boolean} [isColorTheme=false] True if this theme is a color theme, false if the theme is black/white/gray.
35 */
36 /**
37 * @typedef {object} ThemeColors
38 * @description An object containing colors for a Fluid UI theme. Each key in the object corresponds exactly to the name of the CSS variable that it sets.
39 * @property {string} background Page background color
40 * @property {string} text Primary text color
41 * @property {string} lightText Color used for slightly less important text (somewhere between text and secText)
42 * @property {string} secText Secondary text color
43 * @property {string} elements Color used for clickable elements (e.g. buttons, switches, etc.)
44 * @property {string} elementText Text color for clickable elements
45 * @property {string} elementHover Clickable elements hover color
46 * @property {string} switchHead Switch head color
47 * @property {string} inputColor Color for input elements (like text boxes)
48 * @property {string} navbar Navigation bar color
49 * @property {string} sidebar Sidebar background
50 * @property {string} sidebarActive Selected sidebar item background
51 * @property {string} sidenav Sidenav background
52 * @property {string} sidenavActive Selected sidenav item background
53 * @property {string} cards Cards color
54 * @property {string} content Background used for code blocks and the theme selector. Presented with lightShadow. Somewhere between background and inputColor.
55 * @property {string} theme Color used for active items (like enabled switches). This may be overridden (on all themes) to match the site's brand colors.
56 * @property {string} themeText Text color used on top of the "theme" color
57 * @property {string} [themeSelectorColor] Text color used when showing this theme in the theme selector in black/white themes. Optional, and should only be used for color themes.
58 */
59 midnight: {
60 name: "Midnight",
61 icon: "brightness_3",
62 type: "dark",
63 isColorTheme: false
64 //The midnight theme's colors are defined in CSS
65 },
66 tome: {
67 name: "Tome",
68 icon: "bookmark_border",
69 type: "dark",
70 isColorTheme: true,
71 colors: {
72 background: "#18161d",
73
74 text: "#efefef",
75 lightText: "#8e82a2",
76 secText: "#6a6179",
77
78 elements: "#322e3c",
79 elementText: "#ffffff",
80 elementHover: "#403a50",
81 switchHead: "#cccccc",
82
83 inputColor: "#2d2935",
84
85 navbar: "#211e29",
86 sidebar: "#1f1c26",
87 sidebarActive: "#2c2736",
88 sidenav: "#26232d",
89 sidenavActive: "#2a2631",
90
91 cards: "#232029",
92 content: "#1e1b25",
93
94 theme: "#5c3e7b",
95 themeText: "#f8f0ff",
96
97 highlight: "#ffffff12",
98 acrylic: "#282333cc",
99 mediumAcrylic: "#28233380",
100 lightAcrylic: "#28233366",
101 backgroundTint: "#18161de6",
102
103 themeSelectorColor: "#7c68b1"
104 }
105 }
106 },
107 /**
108 * @typedef {object} FluidConfig
109 * @description Contains customization options
110 * @property {string} [defaultTheme=system] The theme ID to use by default
111 * @proeprty {boolean} [themeLock=false] Prevents the user from using a theme other than the default
112 * @property {boolean} [allowBackgroundImages=true] Allows the user to set a background image theme
113 * @property {boolean|string[]} [allowedThemes=true] Either an array of themeIDs to allow, or true to allow all themes. Light, dark, and system are always allowed.
114 */
115 config: { //These configuration settings affects how built-in UI elements behave. Users can bypass these restrictions using the web inspector.
116 defaultTheme: "system", //The theme ID to use by default
117 themeLock: false, //Prevents the user from using a theme other than the default
118 allowBackgroundImages: true, //Allow the user to set background images.
119 allowedThemes: true //An array of theme IDs to allow, or true to allow all themes. Ignored if allowThemeMenu is false. Dark, light, and auto are always allowed.
120 },
121 /**
122 * @typedef {object} strings
123 * @description An object containing all of the strings (or functions if the text is adaptive) for text displayed in the UI. This is provided so that websites can override the text in Fluid UI.
124 */
125 strings: {
126 SYSTEM: "System",
127 LIGHT: "Light",
128 DARK: "Dark",
129 BACKGROUND_IMAGE: "Background Image",
130 USE_BACKGROUND_IMAGE: "Use a background image",
131 IMAGE_URL: "Image URL",
132 FILE_UPLOADED: "File uploaded",
133 UPLOAD_IMAGE: "Upload image",
134 REMOVE_FILE: "Remove file"
135 }
136};
137
138/**
139 * Global Fluid UI configuration object.
140 * All Fluid UI features, as configured by the site developer, are passed to Fluid UI through this object.
141 * This object must be defined globally, before Fluid UI is loaded, for it to take effect.
142 *
143 * @global
144 * @namespace fluidConfig
145 * @property {FluidConfig} config Fluid UI configuration options. This will be merged with the defaults, so only options that differ from the default need to be provided.
146 * @property {Object.<string, Theme>} themes Custom themes to add to Fluid UI.
147 */
148
149//Listen for system theme change
150window.matchMedia("(prefers-color-scheme: dark)").addListener(function (e) {
151 if (document.documentElement.dataset.theme == "system") {
152 fluid.theme("system", true);
153 }
154});
155
156//Listen for theme or preference changes
157window.addEventListener('storage', function (e) {
158 if (e.key.startsWith("pref-")) {
159 fluid.set(e.key, e.newValue, true)
160 }
161 if (e.key == "fluidTheme") {
162 fluid.theme(e.newValue, true)
163 }
164});
165
166//Listen for window resize
167window.onresize = function (event) {
168 if (window.innerWidth <= 900) {
169 $("body").addClass("collapsedSidebar");
170 } else {
171 if (window.localStorage.getItem("fluidSidebarCollapsed") == "true") {
172 $("body").addClass("collapsedSidebar");
173 } else {
174 $("body").removeClass("collapsedSidebar");
175 }
176 }
177};
178
179//Listen for screen change
180window.onhashchange = function () {
181 if (fluid.screensEnabled) {
182 //get url screen
183 var { screenID, param } = fluid.getURLScreen();
184
185 //Load screen from hash
186 fluid.loadScreen(screenID, param);
187
188 //Broadcast screen change
189 document.dispatchEvent(new CustomEvent("fluidScreen", { detail: screenID }));
190 }
191}
192
193/**
194 * Gets the current screen from the URL parameter
195 *
196 * @returns {object} The screenID and parameter from the URL
197 */
198fluid.getURLScreen = function () {
199 var screenID = null, param = null;
200
201 if (document.location.hash == "#/") {
202 screenID = fluid.defaultScreen;
203 } else if (document.location.hash.startsWith("#/")) {
204 screenID = document.location.hash.split("/")[1];
205 param = document.location.hash.split("/").slice(2).join("/");
206 }
207
208 if (param) {
209 param = decodeURI(param);
210 if (param && param.startsWith("{")) try { param = JSON.parse(param); } catch (e) { }
211 }
212
213 return { screenID, param };
214}
215
216/**
217 * Applies a theme, stores the preference, and updates the theme selection UI
218 *
219 * @param {string} requestedTheme The ID of the theme to apply
220 * @param {boolean} [temporary=false] If the theme is only being applied temporarily. When true, the theme will be applied, but the preference will not be saved.
221 */
222fluid.theme = function (requestedTheme, temporary) {
223 //Check for theme lock config
224 if (fluid.config.themeLock && (requestedTheme !== fluid.config.defaultTheme)) return;
225
226 // TOGGLE THEME SHORTCUT
227 if (requestedTheme == "toggle") {
228 if (document.documentElement.dataset.themeType == "dark") {
229 return fluid.theme("light");
230 } else {
231 return fluid.theme("dark");
232 }
233 }
234
235 // GET CURRENT THEME -----------------------
236 var currentTheme = null;
237
238 if (document.documentElement.dataset.theme == "system") {
239 currentTheme = document.documentElement.dataset.themeType;
240 } else {
241 currentTheme = document.documentElement.dataset.theme;
242 }
243
244 if (requestedTheme == undefined) return currentTheme;
245 // -----------------------------------------
246
247 // APPLY REQUESTED THEME -------------------
248 if (requestedTheme && !requestedTheme.startsWith("image.")) {
249 //Set theme vars
250 if ((requestedTheme == "light") || (requestedTheme == "dark")) {
251 document.documentElement.dataset.theme = requestedTheme;
252 document.documentElement.dataset.themeType = requestedTheme;
253 } else if (requestedTheme == "system") {
254 //Use system theme
255 document.documentElement.dataset.theme = "system";
256 if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
257 document.documentElement.dataset.themeType = "dark";
258 } else {
259 document.documentElement.dataset.themeType = "light";
260 }
261 } else if (fluid.themes[requestedTheme]) {
262 document.documentElement.dataset.theme = requestedTheme;
263 document.documentElement.dataset.themeType = fluid.themes[requestedTheme].type;
264 }
265
266 //Set color theme vars for JavaScript themes
267 if (fluid.themes[requestedTheme] && fluid.themes[requestedTheme].colors) {
268 if (!$("style#fluidTheme")[0]) $("head").append(`<style id="fluidTheme"></style>`);
269
270 var themeVars = "";
271 Object.keys(fluid.themes[requestedTheme].colors).forEach(color => {
272 themeVars += `--${color}: ${fluid.themes[requestedTheme].colors[color]};`
273 });
274 $("style#fluidTheme").html(`[data-theme=${requestedTheme}][data-theme-type=${fluid.themes[requestedTheme].type}] { ${themeVars} }`);
275 } else {
276 $("style#fluidTheme").remove();
277 }
278 }
279
280 //Apply theme image
281 if (requestedTheme.startsWith("image.")) {
282 var imageURL = requestedTheme.split("image.")[1];
283
284 if (imageURL) {
285 document.documentElement.dataset.themeImage = imageURL;
286 document.documentElement.style.setProperty("--themeImage", "url('" + imageURL + "')");
287 } else {
288 document.documentElement.style.removeProperty("--themeImage");
289 delete document.documentElement.dataset.themeImage;
290 }
291 }
292 // -----------------------------------------
293
294 // SAVE THEME PREF AND UPDATE UI -------------------
295 if (requestedTheme && requestedTheme.startsWith("image.")) {
296 if (requestedTheme !== "image.") {
297 if (temporary !== true) {
298 localStorage.setItem("fluidThemeImageURL", document.documentElement.dataset.themeImage);
299 localStorage.setItem("fluidThemeImage", true);
300 }
301
302 //Update UI
303 $("#themeMenu #fluidThemeImage").addClass("active");
304 $("#themeMenu #fluidThemeImageInput").show();
305 $("#themeMenu #fluidThemeImageInput input").val(document.documentElement.dataset.themeImage);
306 } else {
307 if (temporary !== true) localStorage.removeItem("fluidThemeImage");
308
309 //Update UI
310 $("#themeMenu #fluidThemeImage").removeClass("active");
311 $("#themeMenu #fluidThemeImageInput").hide();
312 $("#themeMenu #fluidThemeImageInput input").val("");
313 }
314 } else if (requestedTheme) {
315 if (temporary !== true) {
316 localStorage.setItem("fluidTheme", requestedTheme);
317 }
318
319 //Update UI
320 $(".themeOptions .themeSelection").removeClass("active");
321 $(".themeOptions .themeSelection." + requestedTheme).addClass("active");
322
323 //Legacy themeSelector
324 $(".btns.themeSelector .btn").removeClass("active");
325 $(".btns.themeSelector .btn[data-theme=" + requestedTheme + "]").addClass("active");
326
327 if (fluid.themes[requestedTheme] && fluid.themes[requestedTheme].isColorTheme) {
328 $(".themeOptions").addClass("noSelectorColors");
329 } else {
330 $(".themeOptions").removeClass("noSelectorColors");
331 }
332 }
333 // -----------------------------------------
334
335 // OTHER THEME THINGS ----------------------
336 if ((requestedTheme !== currentTheme) && (currentTheme !== null)) {
337 //emit theme change event if the theme has changed
338 document.dispatchEvent(new CustomEvent('fluidTheme', { detail: requestedTheme }))
339 }
340 // -----------------------------------------
341
342}
343
344/**
345 * Applies a theme, stores the preference, and updates the theme selection UI
346 *
347 * @param {string|boolean} requestedImage The URL of the image to apply. If false, the theme image will be disabled.
348 * @param {boolean} [temporary=false] If the image is only being applied temporarily. When true, the theme will be applied, but the preference will not be saved.
349 */
350fluid.themeImage = function (requestedImage, temporary) {
351 //Check for theme image config
352 if (!fluid.config.allowBackgroundImages && requestedImage) return;
353
354 // GET CURRENT THEME -----------------------
355 var prop = getComputedStyle(document.documentElement).getPropertyValue('--themeImage');
356 var currentImage = prop && prop.match(/(?<=^url\(("|'))(.*)(?=("|')\)$)/)[0];
357 if (requestedImage == undefined) return currentImage;
358 // -----------------------------------------
359
360 //Apply theme image
361 var isDataImage = requestedImage && requestedImage.startsWith("data:image/");
362 if (requestedImage) {
363 if (!$("#fluidImageCSS")[0]) $("head").append('<style id="fluidImageCSS"></style>');
364 $("#fluidImageCSS").html(`:root { --themeImage:url("${requestedImage}"); }`);
365 document.documentElement.dataset.themeImage = "";
366 } else {
367 $("#fluidImageCSS").remove();
368 delete document.documentElement.dataset.themeImage;
369 }
370 // -----------------------------------------
371
372 // SAVE THEME PREF AND UPDATE UI -------------------
373 if (requestedImage) {
374 if (temporary !== true) {
375 localStorage.setItem("fluidThemeImageURL", requestedImage);
376 localStorage.setItem("fluidThemeImage", true);
377 }
378
379 //Update UI
380 $("#fluidThemeImage").addClass("active");
381 $("#fluidThemeImageInput").show();
382
383 if (isDataImage) {
384 $("#fluidImageURL").val(fluid.strings.FILE_UPLOADED);
385 $("#fluidThemeImageInput i.inputIcon").html("insert_drive_file");
386 $("#fluidImageURL").attr("disabled", true);
387
388 $("#fluidImageFileRemove").show();
389 $("#fluidImageFileAdd").hide();
390 } else {
391 $("#fluidThemeImageInput input").val(requestedImage);
392 $("#fluidThemeImageInput i.inputIcon").html("link");
393 $("#fluidImageURL").attr("disabled", false);
394
395 $("#fluidImageFileRemove").hide();
396 $("#fluidImageFileAdd").show();
397 }
398 } else {
399 if (temporary !== true) localStorage.removeItem("fluidThemeImage");
400
401 //Update UI
402 $("#fluidThemeImage").removeClass("active");
403 $("#fluidThemeImageInput").hide();
404
405 $("#fluidThemeImageInput input").val("");
406 $("#fluidThemeImageInput i.inputIcon").html("link");
407 $("#fluidImageURL").attr("disabled", false);
408
409 $("#fluidImageFileRemove").hide();
410 $("#fluidImageFileAdd").show();
411 }
412 // -----------------------------------------
413
414 // OTHER THEME THINGS ----------------------
415 if (requestedImage !== currentImage) {
416 //emit theme change event if the theme has changed
417 document.dispatchEvent(new CustomEvent('fluidThemeImage', { detail: requestedImage }));
418 }
419 // -----------------------------------------
420}
421
422/**
423 * Gets a Fluid UI preference
424 *
425 * @param {string} key The name of the preference to get
426 */
427fluid.get = function (key) {
428 return window.localStorage.getItem(key);
429}
430
431/**
432 * Sets a Fluid UI preference
433 *
434 * @param {string} key The name of the preference to set
435 * @param {string} val The value of the preference to set
436 * @param {'load'} [trigger] This is "load" if setting the preference during initial page load
437 */
438fluid.set = function (key, val, trigger) {
439 if (key.startsWith("pref-")) {
440 if ((String(val) == "true") || (String(val) == "false") || (val == undefined)) {
441 //boolean value
442 if (val == undefined) {
443 if (fluid.get(key) !== null) {
444 //toggle boolean value
445 if (fluid.get(key) == "true") { val = false; } else { val = true; }
446 } else {
447 //no value to toggle, get value from switch activity
448 val = !$("." + key).hasClass("active");
449 }
450 }
451 if (String(val) == "true") {
452 $(".switch." + key + ", .btn." + key + ", .checkbox." + key).addClass("active");
453 } else {
454 $(".switch." + key + ", .btn." + key + ", .checkbox." + key).removeClass("active");
455 }
456 } else {
457 //value pref
458 $(".btns." + key + " .btn, .radio." + key + " .checkbox").removeClass("active")
459 $(".btns." + key + " .btn." + val + ", .radio." + key + " .checkbox." + val).addClass("active")
460 }
461 if (trigger == undefined) window.localStorage.setItem(key, val);
462 if (trigger !== "load") {
463 document.dispatchEvent(new CustomEvent(key, { detail: val }));
464 }
465 } else {
466 console.error("Error: Calling fluid.set with invalid prefrence name. Make sure the name of your prefrence starts with 'pref-'. See https://fluid-old.jottocraft.com/#input-prefs.")
467 }
468}
469
470/**
471 * Applies the fluidConfig configuration parameters, if provided. Ran automatically from fluid.onLoad, but can be called manually after if needed.
472 * If ran multiple times, each fluidConfig acts as a patch over the previous.
473 */
474fluid.applyConfig = function () {
475 //Apply fluid config
476 if (window.fluidConfig) {
477 //Apply fluid config from fluidConfig if provided
478 if (fluidConfig.config) {
479 Object.assign(fluid.config, fluidConfig.config);
480 }
481
482 //Add themes from config if provided
483 if (fluidConfig.themes) {
484 Object.keys(fluidConfig.themes).forEach(id => {
485 //Filter out reserved theme names
486 if ((id == "dark") || (id == "light") || (id == "auto") || (id == "system")) return;
487
488 if (fluid.themes[id]) {
489 fluid.themes[id] = Object.assign(fluid.themes[id], fluidConfig.themes[id]);
490 } else {
491 fluid.themes[id] = fluidConfig.themes[id];
492 }
493 });
494 }
495
496 //Apply string overrides from fluidConfig if provided
497 if (fluidConfig.strings) {
498 Object.assign(fluid.strings, fluidConfig.strings);
499 }
500 }
501}
502
503/**
504 * Loads Fluid UI JavaScript features for initial page load.
505 * This should only run once. fluid.init should be used instead for initializing new elements page.
506 */
507fluid.onLoad = function () {
508 //NOTE: fluid.onLoad should ONLY be loaded on the initial page load. Use fluid.init to initialize elements added after page load.
509
510 //Apply configuration
511 fluid.applyConfig();
512
513 //Unsupported browser alert
514 if (window.navigator.userAgent.includes('MSIE ') || window.navigator.userAgent.includes('Trident/')) {
515 alert("Internet Explorer is not supported. Please upgrade to a modern browser like Microsoft Edge or Google Chrome.")
j0f3d7db2026-10-13 04:56:55 +0000516 throw new Error("[Fluid UI] Error: Unsupported browser");
jdc6ea0e2022-04-26 16:03:27 -0700517 }
518
519 //load initial fluid ui theme
520 if (window.localStorage.getItem("fluidTheme") !== null) {
521 fluid.theme(window.localStorage.getItem("fluidTheme"), true);
522 } else if (fluid.config.defaultTheme) {
523 fluid.theme(fluid.config.defaultTheme, true);
524 } else {
525 fluid.theme("system", true);
526 }
527
528 //load initial theme image
529 if (window.localStorage.getItem("fluidThemeImage") == "true") {
530 if (window.localStorage.getItem("fluidThemeImageURL")) {
531 fluid.themeImage(window.localStorage.getItem("fluidThemeImageURL"), true);
532 } else {
533 window.localStorage.removeItem("fluidThemeImage");
534 }
535 }
536
537 //initialize elements when document is ready
538 $(document).ready(() => fluid.init());
539}
540
541/**
542 * Used to initialize new elements added to the document
543 */
544fluid.init = function () {
545 //generate overlay
546 fluid.generateOverlay();
547
548 //Load initial prefrences
549 for (var i = 0; i < Object.keys(window.localStorage).length; i++) {
550 if (Object.keys(window.localStorage)[i].startsWith("pref-")) {
551 fluid.set(Object.keys(window.localStorage)[i], window.localStorage.getItem(Object.keys(window.localStorage)[i]), "load");
552 }
553 }
554
555 //Legacy theme selector
556 $(".btns.row.themeSelector").html(`
557 <button onclick="fluid.theme('system')" data-theme="system" class="btn ${fluid.currentTheme == "system" ? 'active' : ""}"><div class="lightDarkSplit"></div><div class="themeName"><i class="fluid-icon">computer</i> ${fluid.strings.SYSTEM}</div></button>
558 <button onclick="fluid.theme('light')" data-theme="light" data-theme-type="light" class="btn ${document.documentElement.dataset.theme == "light" ? 'active' : ""}"><div class="themeName"><i class="fluid-icon">light_mode</i> ${fluid.strings.LIGHT}</div></button>
559 <button onclick="fluid.theme('dark')" data-theme="dark" data-theme-type="dark" class="btn ${document.documentElement.dataset.theme == "dark" ? 'active' : ""}"><div class="themeName"><i class="fluid-icon">dark_mode</i> ${fluid.strings.DARK}</div></button>
560 `);
561
562 //New theme selection UI
563 var hasThemeImage = window.localStorage.getItem("fluidThemeImage") == "true";
564 $(".themeSelectionUI").html(/*html*/`
565 <div class="themeOptions ${fluid.themes[document.documentElement.dataset.theme] && fluid.themes[document.documentElement.dataset.theme].isColorTheme ? "noSelectorColors" : ""}">
566 <div onclick="fluid.theme('system')" style="--themeSelectorColor: none;" class="themeSelection system ${document.documentElement.dataset.theme == "system" ? "active" : ""}"><i class="fluid-icon">computer</i> <span>${fluid.strings.SYSTEM}</span></div>
567 <div onclick="fluid.theme('light')" data-theme="light" data-theme-type="light" class="themeSelection light ${document.documentElement.dataset.theme == "light" ? "active" : ""}"><i class="fluid-icon">light_mode</i> <span>${fluid.strings.LIGHT}</span></div>
568 <div onclick="fluid.theme('dark')" data-theme="dark" data-theme-type="dark" class="themeSelection dark ${document.documentElement.dataset.theme == "dark" ? "active" : ""}"><i class="fluid-icon">dark_mode</i> <span>${fluid.strings.DARK}</span></div>
569 <div class="divider"></div>
570 ${Object.keys(fluid.themes).filter(id => fluid.config.allowedThemes.includes ? fluid.config.allowedThemes.includes(id) : true).map(id => {
571 var theme = fluid.themes[id];
572 return `<div onclick="fluid.theme('${id}')" ${theme.colors ? `style="--themeSelectorColor: ${theme.colors.themeSelectorColor || "none"};"` : `data-theme="${id}" data-theme-type="${theme.type}"`} class="themeSelection ${id} ${document.documentElement.dataset.theme == id ? "active" : ""}"><i class="fluid-icon">${theme.icon}</i> <span>${theme.name}</span></div>`
573 }).join("")}
574 </div>
575 <div class="themeCustomization">
576 <h5><i class="fluid-icon">wallpaper</i> <span>${fluid.strings.BACKGROUND_IMAGE}</span></h5>
577 <div style="margin-bottom: 20px;">
578 <div id="fluidThemeImage" init="true" class="switch ${hasThemeImage ? "active" : ""}"><span class="head"></span></div>
579 <div class="label">${fluid.strings.USE_BACKGROUND_IMAGE}</div>
580 </div>
581 <div id="fluidThemeImageInput" ${!hasThemeImage ? `style="display: none;"` : ``}>
582 ${window.localStorage.getItem("fluidThemeImageURL") && window.localStorage.getItem("fluidThemeImageURL").startsWith("data:image/") ? `
583 <i class="inputIcon fluid-icon">insert_drive_file</i>
584 <input id="fluidImageURL" value="${fluid.strings.FILE_UPLOADED}" disabled style="margin-bottom: 10px;" class="inputIcon" placeholder="${fluid.strings.IMAGE_URL}" />
585 <button id="fluidImageFileRemove" class="btn small"><i class="fluid-icon">remove_circle_outline</i> ${fluid.strings.REMOVE_FILE}</button>
586 <button id="fluidImageFileAdd" style="display: none;" class="btn small"><i class="fluid-icon">file_upload</i> ${fluid.strings.UPLOAD_IMAGE}</button>
587 ` : `
588 <i class="inputIcon fluid-icon">link</i>
589 <input id="fluidImageURL" value="${window.localStorage.getItem("fluidThemeImageURL") || ""}" style="margin-bottom: 10px;" class="inputIcon" placeholder="${fluid.strings.IMAGE_URL}" />
590 <button id="fluidImageFileRemove" style="display: none;" class="btn small"><i class="fluid-icon">remove_circle_outline</i> ${fluid.strings.REMOVE_FILE}</button>
591 <button id="fluidImageFileAdd" class="btn small"><i class="fluid-icon">file_upload</i> ${fluid.strings.UPLOAD_IMAGE}</button>
592 `}
593
594 <input id="fluidImageFile" type="file" accept="image/*" style="display: none;">
595 </div>
596 </div>
597 `);
598
599 $("#fluidImageFileAdd").click(() => $("#fluidImageFile").click());
600 $("#fluidImageFileRemove").click(() => {
601 localStorage.removeItem("fluidThemeImageURL");
602 fluid.themeImage(false);
603 });
604
605 $(".switch#fluidThemeImage").click(e => {
606 $(".switch#fluidThemeImage").toggleClass("active");
607
608 if ($(".switch#fluidThemeImage").hasClass("active")) {
609 if (window.localStorage.getItem("fluidThemeImageURL")) {
610 fluid.themeImage(window.localStorage.getItem("fluidThemeImageURL"));
611 } else {
612 $("#fluidThemeImageInput").show();
613 }
614 } else {
615 fluid.themeImage(false);
616 }
617 });
618
619 $("#fluidImageURL").change(e => {
620 var val = $("#fluidImageURL").val();
621 if (val) {
622 fluid.themeImage(val);
623 } else {
624 window.localStorage.removeItem("fluidThemeImageURL");
625 fluid.themeImage(false);
626 }
627 });
628
629 $("#fluidImageFile").on("change", function () {
630 var file = this.files[0];
631 var reader = new FileReader();
632
633 reader.addEventListener("load", function () {
634 fluid.themeImage(reader.result);
635 }, false);
636 reader.readAsDataURL(file);
637 });
638
639 //Sidebar collapsed
640 if (window.localStorage.getItem("fluidSidebarCollapsed") == "true") {
641 $("body").addClass("collapsedSidebar");
642 }
643
644 //Sidebar group collapsed state
645 for (var i = 0; i < $(".sidebar .group").length; i++) {
646 var group = $($(".sidebar .group")[i]);
647 if (group.attr("id") && window.localStorage.getItem("fluidSidebar-" + group.attr("id"))) {
648 //Sidebar collapsed state pref
649 if (window.localStorage.getItem("fluidSidebar-" + group.attr("id")) == "open") {
650 group.addClass("open");
651 } else if (window.localStorage.getItem("fluidSidebar-" + group.attr("id")) == "closed") {
652 group.removeClass("open");
653 }
654 }
655 }
656
657 $(".btns:not(.themeSelector) .btn:not(.manual):not([init='true']), .list.select .item:not(.manual):not([init='true']), .sidenav .item:not(.manual):not([init='true']), .sidebar .item:not(.group .name):not(.manual):not(.footer):not([init='true']), .radio .checkbox:not([init='true'])").click(function (event) {
658 if (!($(this).parent().attr("class") || "").includes("pref-") && !($(this).parents(".radio").attr("class") || "").includes("pref-")) {
659 //not a pref
660 if ($(this).parent().hasClass("multiple")) {
661 //Multiple selection mode
662 $(this).toggleClass("active")
663 } else if ($(this).parents(".sidebar").length) {
664 //Sidebar
665 $(this).parents(".sidebar").find(".item:not(.group .name)").removeClass("active");
666 $(this).addClass("active");
667 } else if ($(this).parents(".radio").length) {
668 //radio button
669 $(this).parent().siblings().children(".checkbox").removeClass("active")
670 $(this).addClass("active")
671 } else {
672 $(this).siblings().removeClass("active")
673 $(this).addClass("active")
674 }
675 }
676 });
677 $(".btns:not(.themeSelector) .btn:not(.manual):not([init='true']), .list.select .item:not(.manual):not([init='true']), .sidenav .item:not(.manual):not([init='true']), .sidebar .item:not(.group .name):not(.manual):not(.footer):not([init='true']), .radio .checkbox:not([init='true'])").attr("init", "true");
678
679 $(".sidebar .group .name:not([init='true'])").click(function () {
680 $(this).parent().toggleClass("open");
681
682 if ($(this).parent().attr("id")) {
683 if ($(this).parent().hasClass("open")) {
684 window.localStorage.setItem("fluidSidebar-" + $(this).parent().attr("id"), "open");
685 } else {
686 window.localStorage.setItem("fluidSidebar-" + $(this).parent().attr("id"), "closed");
687 }
688 }
689 });
690 $(".sidebar .group .name:not([init='true'])").attr("init", "true");
691
692 $(".navbar .profile:not([init='true'])").click(function () {
693 if ($(".card.profileMenu").length) {
694 fluid.generateOverlay();
695 $(".card.profileMenu").show();
696 fluid.blur(true);
697 }
698 });
699 $(".navbar .profile:not([init='true'])").attr("init", "true");
700
701 $(".sidebar .collapse:not([init='true'])").click(function () {
702 $('body').toggleClass('collapsedSidebar');
703 if ($('body').hasClass('collapsedSidebar')) {
704 window.localStorage.setItem("fluidSidebarCollapsed", "true");
705 } else {
706 window.localStorage.setItem("fluidSidebarCollapsed", "false");
707 }
708 });
709 $(".sidebar .collapse:not([init='true'])").attr("init", "true");
710
711 fluid.shouldSwitch = true;
712 $(".switch:not([init='true']), .checkbox:not([init='true'])").click(function (event) {
713 if (!$(this).parents(".radio")[0]) {
714 //not a radio button
715 if (fluid.shouldSwitch && !$(this).attr("class").includes("pref-")) {
716 //not a pref
717 $(this).toggleClass("active");
718 fluid.shouldSwitch = false;
719 setTimeout(() => fluid.shouldSwitch = true, 400)
720 }
721 }
722 });
723 $(".switch:not([init='true']), .checkbox:not([init='true'])").attr("init", "true");
724
725 $("div.nav.active li:not([init='true'])").click(function (event) {
726 $(this).siblings().removeClass("active")
727 $(this).addClass("active")
728 });
729 $("div.nav.active li:not([init='true'])").attr("init", "true");
730
731 $(".section.collapse .header:not([init='true'])").click(function (event) {
732 if ($(this).parent().hasClass("collapsed")) {
733 if ($(this).parent().hasClass("one")) {
734 $(this).parent().siblings().addClass("collapsed");
735 }
736 }
737 $(this).parent().toggleClass("collapsed");
738 });
739 $(".section.collapse .header:not([init='true'])").attr("init", "true");
740}
741
742/**
743 * Updates the current screen state and loads a new screen
744 *
745 * @param {string} [requestedID] The ID of the screen to load
746 * @param {string|object} [ctx] The context passed to the screen
747 */
748fluid.screen = function (requestedID, ctx) {
749 //mark screens as enabled for back button listener
750 fluid.screensEnabled = true;
751
752 //update screen
753 if (fluid.screens[requestedID]) {
754 var hash = null;
755
756 if (requestedID == fluid.defaultScreen ? ctx : true) {
757 hash = "#/" + requestedID + (ctx ? "/" + (typeof ctx == "object" ? JSON.stringify(ctx) : ctx) : "");
758 } else {
759 hash = "#/";
760 }
761
762 if (decodeURI(document.location.hash) == hash) {
763 //Load screen directly if the hash is already set
764 fluid.loadScreen(requestedID, ctx);
765 } else {
766 //Change the hash which will automatically trigger a screen load
767 if (!window.location.pathname.endsWith("/")) history.replaceState({}, '', window.location.pathname + "/");
768 document.location.hash = hash;
769 }
770 } else if (!requestedID) {
771 //Reload existing screen or default screen if no ID is provided
772 var { screenID, param } = fluid.getURLScreen();
773 if (screenID) {
774 fluid.screen(screenID, param);
775 } else {
776 fluid.screen(fluid.defaultScreen, ctx);
777 }
778 } else {
779 //screen not found
780 console.error("[FLUID UI] fluid.screen was called, but no screen could be found. Make sure you have defined the screen you are trying to navigate to or the default screen.");
781 }
782}
783
784/**
785 * Loads a screen. This should not be called directly (see fluid.screen instead).
786 *
787 * @param {string} screenID The ID of the screen to load
788 * @param {string|object} [ctx] The context parameter passed to the screen
789 */
790fluid.loadScreen = function (screenID, ctx) {
791 if (typeof fluid.screens[screenID] == "string") {
792 //external screen
793 if (fluid.externalScreens[screenID]) {
794 //external screen already loaded
795 fluid.externalScreens[screenID](ctx);
796 } else {
797 //external screen not yet loaded
798 $.getScript(fluid.screens[screenID], () => {
799 if (fluid.externalScreens[screenID]) {
800 fluid.externalScreens[screenID](ctx);
801 } else {
802 console.error("[FLUID UI] Error: The scriptURL for screen '" + screenID + "' does not define fluid.externalScreens['" + screenID + "']");
803 }
804 });
805 }
806 } else {
807 fluid.screens[screenID](ctx);
808 }
809}
810
811/**
812 * Generates the blur overlay used when a card is opened.
813 * This should not be called directly.
814 */
815fluid.generateOverlay = function () {
816 if (!$("#fluidUIOverlay").length) {
817 $("body").prepend(`<div class="hidden" id="fluidUIOverlay"></div>`);
818 $(".card.focus").appendTo("#fluidUIOverlay");
819 $("#fluidUIOverlay").append("<div id='themeMenu' class='focus card close' style='height: 100%;'></div>");
820
821 $("#fluidUIOverlay").click(function (e) {
822 if (e.target !== this) return;
823 fluid.exitAlert();
824 fluid.cards.close();
825 });
826 }
827}
828
829/**
830 * Shows the page blur effect.
831 * This should not be called directly.
832 *
833 * @param {boolean} [noBlur=false] If this is true, the blur container will be shown without the blur effect
834 */
835fluid.blur = function (noBlur) {
836 function getScrollbarWidth() {
837 return window.innerWidth - document.documentElement.clientWidth;
838 }
839
840 if ($("#fluidUIOverlay").hasClass("hidden")) {
841 $("body").css("--scrollbarWidth", getScrollbarWidth() + "px");
842 }
843
844 if (noBlur) {
845 $("body").removeClass("disableOverflow");
846 $("#fluidUIOverlay").removeClass("noBlur").removeClass("hidden").addClass("visible").addClass("noBlur");
847 } else {
848 $("body").addClass("disableOverflow");
849 $("#fluidUIOverlay").removeClass("noBlur").removeClass("hidden").addClass("visible");
850 }
851}
852
853/**
854 * Removes the blur effect.
855 * This should not be called directly.
856 */
857fluid.unblur = function () {
858 if (!$("#fluidUIOverlay").hasClass("hidden") && $("#fluidUIOverlay").hasClass("visible")) {
859 $("#fluidUIOverlay").removeClass("visible");
860 $("body").removeClass("disableOverflow");
861
862 setTimeout(function () {
863 if (!$("#fluidUIOverlay").hasClass("visible")) $("#fluidUIOverlay").addClass("hidden");
864 }, 200)
865 }
866}
867
868/**
869 * Shows a splash screen
870 *
871 * @param {Element|string} element The element to show
872 */
873fluid.splash = function (element) {
874 $("body").addClass("disableOverflow");
875 $(element).show();
876}
877
878/**
879 * Hides all splash screens
880 */
881fluid.unsplash = function () {
882 $(".splashScreen").hide();
883 $("body").removeClass("disableOverflow");
884}
885
886/**
887 * Shows a card
888 *
889 * @param {Element|string} element The card element to show
890 */
891fluid.cards = function (element) {
892 fluid.generateOverlay();
893 $(".card.focus:not(.close)").addClass("close");
894 $(".card.profileMenu").hide();
895 fluid.blur();
896 $(element).addClass('container');
897 $(element).removeClass('close');
898}
899
900/**
901 * Closes the current card
902 */
903fluid.cards.close = function () {
904 if (window?.dtps?.closeScreen()) return;
905 $(".card.focus:not(.close)").addClass('close');
906 fluid.unblur();
907 $('.card.focus').removeClass("blur");
908 $(".card.profileMenu").hide();
909}
910
911/**
912* @typedef {object} AlertAction
913* @description Sets the actions for an alert
914* @property {string} icon Action icon
915* @property {string} name Action name
916* @property {function} action The function to run when the action is clicked
917*/
918
919/**
920 * Shows a Fluid UI alert.
921 * If only one parameter is provided (e.g. fluid.alert('Test alert')), a generic alert will be shown
922 *
923 * @param {string} title The alert title
924 * @param {string} body Alert body HTML
925 * @param {string} [icon] Alert icon
926 * @param {AlertAction[]} [actions] Alert actions
927 * @param {string} [color] The icon color
928 */
929fluid.alert = function (title, body, icon, actions, color) {
930 if (title && !body) {
931 body = title;
932 title = "Alert";
933 icon = "notifications";
934 }
935
936 if (!color && (icon == "check")) color = "#3ba842";
937 if (!color && (icon == "error")) color = "#a83b3b";
938 if (!color && (icon == "warning")) color = "#d1a045";
939 if (!color && (icon == "info")) color = "#459ed1";
940
941 //Generate overlay
942 fluid.generateOverlay();
943
944 $("#activeAlert").remove();
945 $("#fluidUIOverlay").append(`<div id="activeAlert" class="card alert">
946<i class="fluid-icon close" onclick="fluid.exitAlert()">close</i>
947
948 ${icon ? `<i style="color: ` + (color ? color : "var(--text)") + `" class="fluid-icon">${icon}</i>` : ""}
949 <h5>${title}</h5>
950 <div class="body">
951 <div>${body}</div>
952 </div>
953 ` + (actions ? `<div class="footer">` + actions.map((action, key) => {
954 return `<button class="btn ${key}">
955 ` + (action.icon ? `<i class="fluid-icon">` + action.icon + `</i> ` : "") + action.name + `
956 </button>`
957 }).join("") + `</div>` : "") + `
958</div>`);
959
960 //Add onclick listeners
961 if (actions) {
962 actions.forEach((action, key) => {
963 $("#activeAlert .footer .btn." + key).click(() => {
964 if (action.action) action.action();
965 fluid.exitAlert();
966 })
967 });
968 }
969
970 fluid.blur();
971 $('.card.focus:not(.close)').addClass("blur");
972}
973
974/**
975 * Closes the active alert
976 */
977fluid.exitAlert = function () {
978 $("#activeAlert").remove();
979 if (!$('.card.focus:not(.close)').length) fluid.unblur();
980 $('.card.focus').removeClass("blur");
981};
982
983//Load Fluid UI
984(function checkReady() {
985 if (document.body) return fluid.onLoad();
986 window.requestAnimationFrame(checkReady);
987})();
988
jdc6ea0e2022-04-26 16:03:27 -0700989//Fluid UI commands
990var allowedKeys = {
991 38: 'up',
992 40: 'down',
993 119: 'f8',
994 120: 'f9',
995 37: 'left',
996 39: 'right',
997 66: 'b',
998 65: 'a'
999};
1000var darkOverride = ['up', 'up', 'down', 'down', 'f8'];
1001var darkOverridePosition = 0;
1002var imageOverride = ['up', 'up', 'down', 'down', 'f9'];
1003var imageOverridePosition = 0;
jdc6ea0e2022-04-26 16:03:27 -07001004document.addEventListener('keydown', function (e) {
1005 var key = allowedKeys[e.keyCode];
1006 var requiredKey = darkOverride[darkOverridePosition];
1007 if (key == requiredKey) {
1008 darkOverridePosition++;
1009 if (darkOverridePosition == darkOverride.length) {
1010 fluid.theme("toggle");
1011 darkOverridePosition = 0;
1012 e.preventDefault();
1013 }
1014 } else {
1015 darkOverridePosition = 0;
1016 }
1017
1018 var requiredKey = imageOverride[imageOverridePosition];
1019 if (key == requiredKey) {
1020 imageOverridePosition++;
1021 if (imageOverridePosition == imageOverride.length) {
1022 if (window.localStorage.getItem("fluidThemeImageURL") && !document.documentElement.dataset.themeImage) {
1023 fluid.theme("image." + window.localStorage.getItem("fluidThemeImageURL"));
1024 } else {
1025 fluid.theme("image.");
1026 }
1027 imageOverridePosition = 0;
1028 e.preventDefault();
1029 }
1030 } else {
1031 imageOverridePosition = 0;
1032 }
jdc6ea0e2022-04-26 16:03:27 -07001033});