PageSourceSearch

https://www.pangao.vip/js/color-schema.js

js pangao.vip collected 2026-09-28 06:50:10 UTC 8,806 bytes, 279 lines download raw bytes

1/* global Fluid */
2
3/**
4 * Modified from https://blog.skk.moe/post/hello-darkmode-my-old-friend/
5 */
6(function(window, document) {
7  var rootElement = document.documentElement;
8  var colorSchemaStorageKey = 'Fluid_Color_Scheme';
9  var colorSchemaMediaQueryKey = '--color-mode';
10  var userColorSchemaAttributeName = 'data-user-color-scheme';
11  var defaultColorSchemaAttributeName = 'data-default-color-scheme';
12  var colorToggleButtonSelector = '#color-toggle-btn';
13  var colorToggleIconSelector = '#color-toggle-icon';
14
15  function setLS(k, v) {
16    try {
17      localStorage.setItem(k, v);
18    } catch (e) {}
19  }
20
21  function removeLS(k) {
22    try {
23      localStorage.removeItem(k);
24    } catch (e) {}
25  }
26
27  function getLS(k) {
28    try {
29      return localStorage.getItem(k);
30    } catch (e) {
31      return null;
32    }
33  }
34
35  function getSchemaFromHTML() {
36    var res = rootElement.getAttribute(defaultColorSchemaAttributeName);
37    if (typeof res === 'string') {
38      return res.replace(/["'\s]/g, '');
39    }
40    return null;
41  }
42
43  function getSchemaFromCSSMediaQuery() {
44    var res = getComputedStyle(rootElement).getPropertyValue(
45      colorSchemaMediaQueryKey
46    );
47    if (typeof res === 'string') {
48      return res.replace(/["'\s]/g, '');
49    }
50    return null;
51  }
52
53  function resetSchemaAttributeAndLS() {
54    rootElement.setAttribute(userColorSchemaAttributeName, getDefaultColorSchema());
55    removeLS(colorSchemaStorageKey);
56  }
57
58  var validColorSchemaKeys = {
59    dark : true,
60    light: true
61  };
62
63  function getDefaultColorSchema() {
64    // 取默认字段的值
65    var schema = getSchemaFromHTML();
66    // 如果明确指定了 schema 则返回
67    if (validColorSchemaKeys[schema]) {
68      return schema;
69    }
70    // 默认优先按 prefers-color-scheme
71    schema = getSchemaFromCSSMediaQuery();
72    if (validColorSchemaKeys[schema]) {
73      return schema;
74    }
75    // 否则按本地时间是否大于 18 点或凌晨 0 ~ 6 点
76    var hours = new Date().getHours();
77    if (hours >= 18 || (hours >= 0 && hours <= 6)) {
78      return 'dark';
79    }
80    return 'light';
81  }
82
83  function applyCustomColorSchemaSettings(schema) {
84    // 接受从「开关」处传来的模式,或者从 localStorage 读取,否则按默认设置值
85    var current = schema || getLS(colorSchemaStorageKey) || getDefaultColorSchema();
86
87    if (current === getDefaultColorSchema()) {
88      // 当用户切换的显示模式和默认模式相同时,则恢复为自动模式
89      resetSchemaAttributeAndLS();
90    } else if (validColorSchemaKeys[current]) {
91      rootElement.setAttribute(
92        userColorSchemaAttributeName,
93        current
94      );
95    } else {
96      // 特殊情况重置
97      resetSchemaAttributeAndLS();
98      return;
99    }
100
101    // 根据当前模式设置图标
102    setButtonIcon(current);
103
104    // 设置代码高亮
105    setHighlightCSS(current);
106
107    // 设置其他应用
108    setApplications(current);
109  }
110
111  var invertColorSchemaObj = {
112    dark : 'light',
113    light: 'dark'
114  };
115
116  function getIconClass(scheme) {
117    return 'icon-' + scheme;
118  }
119
120  function toggleCustomColorSchema() {
121    var currentSetting = getLS(colorSchemaStorageKey);
122
123    if (validColorSchemaKeys[currentSetting]) {
124      // 从 localStorage 中读取模式,并取相反的模式
125      currentSetting = invertColorSchemaObj[currentSetting];
126    } else if (currentSetting === null) {
127      // 当 localStorage 中没有相关值,或者 localStorage 抛了 Error
128      // 先按照按钮的状态进行切换
129      var iconElement = document.querySelector(colorToggleIconSelector);
130      if (iconElement) {
131        currentSetting = iconElement.getAttribute('data');
132      }
133      if (!iconElement || !validColorSchemaKeys[currentSetting]) {
134        // 当 localStorage 中没有相关值,或者 localStorage 抛了 Error,则读取默认值并切换到相反的模式
135        currentSetting = invertColorSchemaObj[getSchemaFromCSSMediaQuery()];
136      }
137    } else {
138      return;
139    }
140    // 将相反的模式写入 localStorage
141    setLS(colorSchemaStorageKey, currentSetting);
142
143    return currentSetting;
144  }
145
146  function setButtonIcon(schema) {
147    if (validColorSchemaKeys[schema]) {
148      // 切换图标
149      var icon = getIconClass('dark');
150      if (schema) {
151        icon = getIconClass(schema);
152      }
153      var iconElement = document.querySelector(colorToggleIconSelector);
154      if (iconElement) {
155        iconElement.setAttribute(
156          'class',
157          'iconfont ' + icon
158        );
159        iconElement.setAttribute(
160          'data',
161          invertColorSchemaObj[schema]
162        );
163      } else {
164        // 如果图标不存在则说明图标还没加载出来,等到页面全部加载再尝试切换
165        Fluid.utils.waitElementLoaded(colorToggleIconSelector, function() {
166          var iconElement = document.querySelector(colorToggleIconSelector);
167          if (iconElement) {
168            iconElement.setAttribute(
169              'class',
170              'iconfont ' + icon
171            );
172            iconElement.setAttribute(
173              'data',
174              invertColorSchemaObj[schema]
175            );
176          }
177        });
178      }
179      if (document.documentElement.getAttribute('data-user-color-scheme')) {
180        var color = getComputedStyle(document.documentElement).getPropertyValue('--navbar-bg-color').trim()
181        document.querySelector('meta[name="theme-color"]').setAttribute('content', color)
182      }
183    }
184  }
185
186  function setHighlightCSS(schema) {
187    // 启用对应的代码高亮的样式
188    var lightCss = document.getElementById('highlight-css');
189    var darkCss = document.getElementById('highlight-css-dark');
190    if (schema === 'dark') {
191      if (darkCss) {
192        darkCss.removeAttribute('disabled');
193      }
194      if (lightCss) {
195        lightCss.setAttribute('disabled', '');
196      }
197    } else {
198      if (lightCss) {
199        lightCss.removeAttribute('disabled');
200      }
201      if (darkCss) {
202        darkCss.setAttribute('disabled', '');
203      }
204    }
205
206    setTimeout(function() {
207      // 设置代码块组件样式
208      document.querySelectorAll('.markdown-body pre').forEach((pre) => {
209        var cls = Fluid.utils.getBackgroundLightness(pre) >= 0 ? 'code-widget-light' : 'code-widget-dark';
210        var widget = pre.querySelector('.code-widget-light, .code-widget-dark');
211        if (widget) {
212          widget.classList.remove('code-widget-light', 'code-widget-dark');
213          widget.classList.add(cls);
214        }
215      });
216    }, 200);
217  }
218
219  function setApplications(schema) {
220    // 设置 remark42 评论主题
221    if (window.REMARK42) {
222      window.REMARK42.changeTheme(schema);
223    }
224
225    // 设置 cusdis 评论主题
226    if (window.CUSDIS) {
227      window.CUSDIS.setTheme(schema);
228    }
229
230    // 设置 utterances 评论主题
231    var utterances = document.querySelector('.utterances-frame');
232    if (utterances) {
233      var utterancesTheme = schema === 'dark' ? window.UtterancesThemeDark : window.UtterancesThemeLight;
234      const message = {
235        type : 'set-theme',
236        theme: utterancesTheme
237      };
238      utterances.contentWindow.postMessage(message, 'https://utteranc.es');
239    }
240
241    // 设置 giscus 评论主题
242    var giscus = document.querySelector('iframe.giscus-frame');
243    if (giscus) {
244      var giscusTheme = schema === 'dark' ? window.GiscusThemeDark : window.GiscusThemeLight;
245      const message = {
246        setConfig: {
247          theme: giscusTheme,
248        }
249      };
250      giscus.contentWindow.postMessage({ 'giscus': message }, 'https://giscus.app');
251    }
252  }
253
254  // 当页面加载时,将显示模式设置为 localStorage 中自定义的值(如果有的话)
255  applyCustomColorSchemaSettings();
256
257  Fluid.utils.waitElementLoaded(colorToggleIconSelector, function() {
258    applyCustomColorSchemaSettings();
259    var button = document.querySelector(colorToggleButtonSelector);
260    if (button) {
261      // 当用户点击切换按钮时,获得新的显示模式、写入 localStorage、并在页面上生效
262      button.addEventListener('click', function() {
263        applyCustomColorSchemaSettings(toggleCustomColorSchema());
264      });
265      var icon = document.querySelector(colorToggleIconSelector);
266      if (icon) {
267        // 光标悬停在按钮上时,切换图标
268        button.addEventListener('mouseenter', function() {
269          var current = icon.getAttribute('data');
270          icon.classList.replace(getIconClass(invertColorSchemaObj[current]), getIconClass(current));
271        });
272        button.addEventListener('mouseleave', function() {
273          var current = icon.getAttribute('data');
274          icon.classList.replace(getIconClass(current), getIconClass(invertColorSchemaObj[current]));
275        });
276      }
277    }
278  });
279})(window, document);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.