docStyle.vue 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <script>
  2. const ORIGINAL_THEME = '#409EFF';
  3. import { get as ajaxGet } from './utils/ajax';
  4. import { updateDomHeadStyle } from './utils/utils.js';
  5. export default {
  6. data() {
  7. return {
  8. docs: '', // content of docs css
  9. theme: ORIGINAL_THEME,
  10. asyncCb: true
  11. };
  12. },
  13. methods: {
  14. updateDocStyle(e, cb) {
  15. const val = e.global['$--color-primary'] || ORIGINAL_THEME;
  16. const oldVal = this.theme;
  17. const getHandler = (variable, id) => {
  18. return () => {
  19. let newStyle = this.updateStyle(this[variable], ORIGINAL_THEME, val);
  20. updateDomHeadStyle(id, newStyle);
  21. this.asyncCb && cb();
  22. };
  23. };
  24. const docsHandler = getHandler('docs', 'docs-style');
  25. if (!this.docs) {
  26. const links = [].filter.call(document.querySelectorAll('link'), link => {
  27. return /docs\..+\.css/.test(link.href || '');
  28. });
  29. if (links[0]) {
  30. this.getCSSString(links[0].href, docsHandler, 'docs');
  31. } else {
  32. this.asyncCb = false;
  33. }
  34. } else {
  35. docsHandler();
  36. }
  37. const styles = [].slice.call(document.querySelectorAll('style'))
  38. .filter(style => {
  39. const text = style.innerText;
  40. return new RegExp(oldVal, 'i').test(text) && !/Chalk Variables/.test(text);
  41. });
  42. styles.forEach(style => {
  43. const { innerText } = style;
  44. if (typeof innerText !== 'string') return;
  45. style.innerText = this.updateStyle(innerText, oldVal, val);
  46. });
  47. this.theme = val;
  48. !this.asyncCb && cb();
  49. },
  50. updateStyle(style, oldColor, newColor) {
  51. return style.replace(new RegExp(oldColor, 'ig'), newColor);
  52. },
  53. getCSSString(url, callback, variable) {
  54. ajaxGet(url).then((res) => {
  55. this[variable] = res;
  56. callback();
  57. });
  58. }
  59. }
  60. };
  61. </script>