DEV: Backend support for light/dark mode in color palettes (#30893)

We're embarking on a project for overhauling the color palette and theme
systems in Discourse. As part of this project, we're making each color
palette include light and dark modes instead of the status quo of
requiring 2 separate color palettes to implement light and dark modes.

This commit is a first step towards that goal; it adds a code path for
generating and serving `color_definitions` stylesheets using the
built-in dark variant of a color palette. All of this code path is
behind a default-off site setting `use_overhauled_theme_color_palette`,
so there's no change in behavior unless the setting is enabled.

Internal topic: t/141467.
This commit is contained in:
Osama Sayegh
2025-01-23 15:54:49 +03:00
committed by GitHub
parent 13f86c99ea
commit 10f34ddf86
10 changed files with 193 additions and 41 deletions

View File

@@ -409,16 +409,18 @@ class ColorScheme < ActiveRecord::Base
new_color_scheme
end
def self.lookup_hex_for_name(name, scheme_id = nil)
def self.lookup_hex_for_name(name, scheme_id = nil, dark: false)
enabled_color_scheme = find_by(id: scheme_id) if scheme_id
enabled_color_scheme ||= Theme.where(id: SiteSetting.default_theme_id).first&.color_scheme
(enabled_color_scheme || base).colors.find { |c| c.name == name }.try(:hex)
color_record = (enabled_color_scheme || base).colors.find { |c| c.name == name }
return if !color_record
dark ? color_record.dark_hex || color_record.hex : color_record.hex
end
def self.hex_for_name(name, scheme_id = nil)
hex_cache.defer_get_set(scheme_id ? name + "_#{scheme_id}" : name) do
lookup_hex_for_name(name, scheme_id)
end
def self.hex_for_name(name, scheme_id = nil, dark: false)
cache_key = scheme_id ? "#{name}_#{scheme_id}" : name
cache_key += "_dark" if dark
hex_cache.defer_get_set(cache_key) { lookup_hex_for_name(name, scheme_id, dark:) }
end
def colors=(arr)
@@ -450,10 +452,16 @@ class ColorScheme < ActiveRecord::Base
colors || ColorScheme.base_colors
end
def resolved_colors
def resolved_colors(dark: false)
from_base = ColorScheme.base_colors
from_custom_scheme = base_colors
from_db = colors.map { |c| [c.name, c.hex] }.to_h
from_db =
colors
.map do |c|
hex = dark ? (c.dark_hex || c.hex) : c.hex
[c.name, hex]
end
.to_h
resolved = from_base.merge(from_custom_scheme).except("hover", "selected").merge(from_db)

View File

@@ -4,6 +4,7 @@ class ColorSchemeColor < ActiveRecord::Base
belongs_to :color_scheme
validates :hex, format: { with: /\A([0-9a-fA-F]{3}|[0-9a-fA-F]{6})\z/ }
validates :dark_hex, format: { with: /\A([0-9a-fA-F]{3}|[0-9a-fA-F]{6})\z/ }, allow_nil: true
def hex_with_hash
"##{hex}"
@@ -20,6 +21,7 @@ end
# color_scheme_id :integer not null
# created_at :datetime not null
# updated_at :datetime not null
# dark_hex :string(6)
#
# Indexes
#