color-schema.js 8.6 KB

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