color-schema.js 8.8 KB

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