css.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // SiYuan - Build Your Eternal Digital Garden
  2. // Copyright (c) 2020-present, b3log.org
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. package model
  17. import (
  18. "github.com/88250/css"
  19. "github.com/siyuan-note/logging"
  20. "github.com/siyuan-note/siyuan/kernel/util"
  21. "os"
  22. "path/filepath"
  23. "strings"
  24. )
  25. func currentCSSValue(key string) string {
  26. var themeName string
  27. if 0 == Conf.Appearance.Mode {
  28. themeName = Conf.Appearance.ThemeLight
  29. } else {
  30. themeName = Conf.Appearance.ThemeDark
  31. }
  32. themePath := filepath.Join(util.ThemesPath, themeName)
  33. theme := filepath.Join(themePath, "theme.css")
  34. data, err := os.ReadFile(theme)
  35. if nil != err {
  36. logging.LogErrorf("read theme css [%s] failed: %s", theme, err)
  37. return "#ffffff"
  38. }
  39. ss := css.Parse(string(data))
  40. rules := ss.GetCSSRuleList()
  41. for _, rule := range rules {
  42. for _, style := range rule.Style.Styles {
  43. fixStyle(style)
  44. if key == style.Property {
  45. return style.Value.Text()
  46. }
  47. }
  48. }
  49. return ""
  50. }
  51. func fixStyle(style *css.CSSStyleDeclaration) {
  52. // css 解析库似乎有 bug,这里做修正
  53. if strings.HasPrefix(style.Property, "-") && !strings.HasPrefix(style.Property, "--") {
  54. style.Property = "-" + style.Property
  55. }
  56. if strings.HasPrefix(style.Value.Text(), "- ") {
  57. value := style.Value.Text()[2:]
  58. style.Value = css.NewCSSValue(value)
  59. }
  60. }