docStyle.vue 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. };
  11. },
  12. methods: {
  13. updateDocStyle(e) {
  14. const val = e.global['$--color-primary'] || ORIGINAL_THEME;
  15. const oldVal = this.theme;
  16. const getHandler = (variable, id) => {
  17. return () => {
  18. let newStyle = this.updateStyle(this[variable], ORIGINAL_THEME, val);
  19. updateDomHeadStyle(id, newStyle);
  20. };
  21. };
  22. const docsHandler = getHandler('docs', 'docs-style');
  23. if (!this.docs) {
  24. const links = [].filter.call(document.querySelectorAll('link'), link => {
  25. return /docs\..+\.css/.test(link.href || '');
  26. });
  27. links[0] && this.getCSSString(links[0].href, docsHandler, 'docs');
  28. } else {
  29. docsHandler();
  30. }
  31. const styles = [].slice.call(document.querySelectorAll('style'))
  32. .filter(style => {
  33. const text = style.innerText;
  34. return new RegExp(oldVal, 'i').test(text) && !/Chalk Variables/.test(text);
  35. });
  36. styles.forEach(style => {
  37. const { innerText } = style;
  38. if (typeof innerText !== 'string') return;
  39. style.innerText = this.updateStyle(innerText, oldVal, val);
  40. });
  41. this.theme = val;
  42. },
  43. updateStyle(style, oldColor, newColor) {
  44. return style.replace(new RegExp(oldColor, 'ig'), newColor);
  45. },
  46. getCSSString(url, callback, variable) {
  47. ajaxGet(url).then((res) => {
  48. this[variable] = res;
  49. callback();
  50. });
  51. }
  52. }
  53. };
  54. </script>