]> git.proxmox.com Git - rustc.git/blob - src/librustdoc/html/static/storage.js
e10e330402f5edf3ca56fae7f527ab7bad8cdcb2
[rustc.git] / src / librustdoc / html / static / storage.js
1 /*!
2 * Copyright 2018 The Rust Project Developers. See the COPYRIGHT
3 * file at the top-level directory of this distribution and at
4 * http://rust-lang.org/COPYRIGHT.
5 *
6 * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
7 * http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
8 * <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
9 * option. This file may not be copied, modified, or distributed
10 * except according to those terms.
11 */
12
13 var currentTheme = document.getElementById("themeStyle");
14 var mainTheme = document.getElementById("mainThemeStyle");
15
16 var savedHref = [];
17
18 function onEach(arr, func) {
19 if (arr && arr.length > 0 && func) {
20 for (var i = 0; i < arr.length; i++) {
21 if (func(arr[i]) === true) {
22 return true;
23 }
24 }
25 }
26 return false;
27 }
28
29 function usableLocalStorage() {
30 // Check if the browser supports localStorage at all:
31 if (typeof(Storage) === "undefined") {
32 return false;
33 }
34 // Check if we can access it; this access will fail if the browser
35 // preferences deny access to localStorage, e.g., to prevent storage of
36 // "cookies" (or cookie-likes, as is the case here).
37 try {
38 window.localStorage;
39 } catch(err) {
40 // Storage is supported, but browser preferences deny access to it.
41 return false;
42 }
43
44 return true;
45 }
46
47 function updateLocalStorage(name, value) {
48 if (usableLocalStorage()) {
49 localStorage[name] = value;
50 } else {
51 // No Web Storage support so we do nothing
52 }
53 }
54
55 function getCurrentValue(name) {
56 if (usableLocalStorage() && localStorage[name] !== undefined) {
57 return localStorage[name];
58 }
59 return null;
60 }
61
62 function switchTheme(styleElem, mainStyleElem, newTheme) {
63 var fullBasicCss = "rustdoc" + resourcesSuffix + ".css";
64 var fullNewTheme = newTheme + resourcesSuffix + ".css";
65 var newHref = mainStyleElem.href.replace(fullBasicCss, fullNewTheme);
66
67 if (styleElem.href === newHref) {
68 return;
69 }
70
71 var found = false;
72 if (savedHref.length === 0) {
73 onEach(document.getElementsByTagName("link"), function(el) {
74 savedHref.push(el.href);
75 });
76 }
77 onEach(savedHref, function(el) {
78 if (el === newHref) {
79 found = true;
80 return true;
81 }
82 });
83 if (found === true) {
84 styleElem.href = newHref;
85 updateLocalStorage('rustdoc-theme', newTheme);
86 }
87 }
88
89 switchTheme(currentTheme, mainTheme, getCurrentValue('rustdoc-theme') || 'light');