Files
hexo-theme-butterfly/layout/includes/third-party/math/chartjs.pug
SeaYJ 975134fb14 添加对 ChartJS 双模式的支持
1. 增加了 ChartJS 图表官方语法;
2. 新增了 ChartJS 的双模式(浅色/深色模式)显示功能;
3. 扩展了 ChartJS 的 config 语法,支持双模式配置。
4. 修复了 ChartJS 在双模式下默认样式的问题,简化用户配置图表过程。
2024-10-03 23:41:47 +08:00

80 lines
3.3 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
script.
(() => {
const $chartjs = document.querySelectorAll('#article-container .chartjs-wrap')
if ($chartjs.length === 0) return
const applyThemeDefaultsConfig = (theme) => {
if (theme === 'dark-mode') {
Chart.defaults.color = "!{theme.chartjs.color.dark}"
Chart.defaults.borderColor = "!{theme.chartjs.borderColor.dark}"
Chart.defaults.scale.ticks.backdropColor = "!{theme.chartjs.scale.ticks.backdropColor.dark}"
} else {
Chart.defaults.color = "!{theme.chartjs.color.light}"
Chart.defaults.borderColor = "!{theme.chartjs.borderColor.light}"
Chart.defaults.scale.ticks.backdropColor = "!{theme.chartjs.scale.ticks.backdropColor.light}"
}
}
// 递归遍历 config 对象,自动根据当前主题选择双模式配色方案
const applyThemeConfig = (obj, theme) => {
if (typeof obj !== 'object' || obj === null) return
Object.keys(obj).forEach(key => {
const value = obj[key]
// 如果属性是对象,并且有与主题相关的选项,进行应用
if (typeof value === 'object' && value !== null) {
if (value[theme]) {
obj[key] = value[theme] // 应用当前主题的值
} else {
// 递归处理子对象
applyThemeConfig(value, theme)
}
}
})
}
const runChartJS = () => {
window.loadChartJS = true
Array.from($chartjs).forEach((item, index) => {
const chartSrc = item.firstElementChild
const chartID = item.getAttribute('data-chartjs-id') || ('chartjs-' + index) // 使用自定义 ID 或默认 ID
const existingCanvas = document.getElementById(chartID)
// 如果已经存在 canvas先将其移除避免重复渲染
if (existingCanvas) {
existingCanvas.remove()
}
const chartDefinition = chartSrc.textContent
const canvas = document.createElement('canvas')
canvas.id = chartID
chartSrc.insertAdjacentElement('afterend', canvas)
const ctx = document.getElementById(chartID).getContext('2d')
const config = JSON.parse(chartDefinition)
// 根据当前主题选择相应的配色方案
const theme = document.documentElement.getAttribute('data-theme') === 'dark' ? 'dark-mode' : 'light-mode'
// 设置默认样式(默认初始化)
applyThemeDefaultsConfig(theme)
// 自动遍历 config应用双模式配色方案
applyThemeConfig(config, theme)
new Chart(ctx, config)
})
}
const loadChartJS = () => {
window.loadChartJS ? runChartJS() : btf.getScript('!{url_for(theme.asset.chartjs)}').then(runChartJS)
}
// 监听主题切换
btf.addGlobalFn('themeChange', runChartJS, 'chartjs')
window.pjax ? loadChartJS() : document.addEventListener('DOMContentLoaded', loadChartJS)
})()