DEV: Apply syntax_tree formatting to app/*

This commit is contained in:
David Taylor
2023-01-09 12:20:10 +00:00
parent a641ce4b62
commit 5a003715d3
696 changed files with 18447 additions and 15481 deletions

View File

@@ -1,7 +1,7 @@
# frozen_string_literal: true
require 'csv'
require 'json_schemer'
require "csv"
require "json_schemer"
class Theme < ActiveRecord::Base
include GlobalPath
@@ -17,44 +17,67 @@ class Theme < ActiveRecord::Base
has_many :theme_fields, dependent: :destroy
has_many :theme_settings, dependent: :destroy
has_many :theme_translation_overrides, dependent: :destroy
has_many :child_theme_relation, class_name: 'ChildTheme', foreign_key: 'parent_theme_id', dependent: :destroy
has_many :parent_theme_relation, class_name: 'ChildTheme', foreign_key: 'child_theme_id', dependent: :destroy
has_many :child_theme_relation,
class_name: "ChildTheme",
foreign_key: "parent_theme_id",
dependent: :destroy
has_many :parent_theme_relation,
class_name: "ChildTheme",
foreign_key: "child_theme_id",
dependent: :destroy
has_many :child_themes, -> { order(:name) }, through: :child_theme_relation, source: :child_theme
has_many :parent_themes, -> { order(:name) }, through: :parent_theme_relation, source: :parent_theme
has_many :parent_themes,
-> { order(:name) },
through: :parent_theme_relation,
source: :parent_theme
has_many :color_schemes
belongs_to :remote_theme, dependent: :destroy
has_one :theme_modifier_set, dependent: :destroy
has_one :settings_field, -> { where(target_id: Theme.targets[:settings], name: "yaml") }, class_name: 'ThemeField'
has_one :settings_field,
-> { where(target_id: Theme.targets[:settings], name: "yaml") },
class_name: "ThemeField"
has_one :javascript_cache, dependent: :destroy
has_many :locale_fields, -> { filter_locale_fields(I18n.fallbacks[I18n.locale]) }, class_name: 'ThemeField'
has_many :upload_fields, -> { where(type_id: ThemeField.types[:theme_upload_var]).preload(:upload) }, class_name: 'ThemeField'
has_many :extra_scss_fields, -> { where(target_id: Theme.targets[:extra_scss]) }, class_name: 'ThemeField'
has_many :yaml_theme_fields, -> { where("name = 'yaml' AND type_id = ?", ThemeField.types[:yaml]) }, class_name: 'ThemeField'
has_many :var_theme_fields, -> { where("type_id IN (?)", ThemeField.theme_var_type_ids) }, class_name: 'ThemeField'
has_many :builder_theme_fields, -> { where("name IN (?)", ThemeField.scss_fields) }, class_name: 'ThemeField'
has_many :locale_fields,
-> { filter_locale_fields(I18n.fallbacks[I18n.locale]) },
class_name: "ThemeField"
has_many :upload_fields,
-> { where(type_id: ThemeField.types[:theme_upload_var]).preload(:upload) },
class_name: "ThemeField"
has_many :extra_scss_fields,
-> { where(target_id: Theme.targets[:extra_scss]) },
class_name: "ThemeField"
has_many :yaml_theme_fields,
-> { where("name = 'yaml' AND type_id = ?", ThemeField.types[:yaml]) },
class_name: "ThemeField"
has_many :var_theme_fields,
-> { where("type_id IN (?)", ThemeField.theme_var_type_ids) },
class_name: "ThemeField"
has_many :builder_theme_fields,
-> { where("name IN (?)", ThemeField.scss_fields) },
class_name: "ThemeField"
validate :component_validations
after_create :update_child_components
scope :user_selectable, ->() {
where('user_selectable OR id = ?', SiteSetting.default_theme_id)
}
scope :user_selectable, -> { where("user_selectable OR id = ?", SiteSetting.default_theme_id) }
scope :include_relations, -> {
includes(:child_themes,
:parent_themes,
:remote_theme,
:theme_settings,
:settings_field,
:locale_fields,
:user,
:color_scheme,
:theme_translation_overrides,
theme_fields: :upload
)
}
scope :include_relations,
-> {
includes(
:child_themes,
:parent_themes,
:remote_theme,
:theme_settings,
:settings_field,
:locale_fields,
:user,
:color_scheme,
:theme_translation_overrides,
theme_fields: :upload,
)
}
def notify_color_change(color, scheme: nil)
scheme ||= color.color_scheme
@@ -78,11 +101,11 @@ class Theme < ActiveRecord::Base
theme_modifier_set.save!
if saved_change_to_name?
theme_fields.select(&:basic_html_field?).each(&:invalidate_baked!)
end
theme_fields.select(&:basic_html_field?).each(&:invalidate_baked!) if saved_change_to_name?
Theme.expire_site_cache! if saved_change_to_color_scheme_id? || saved_change_to_user_selectable? || saved_change_to_name?
if saved_change_to_color_scheme_id? || saved_change_to_user_selectable? || saved_change_to_name?
Theme.expire_site_cache!
end
notify_with_scheme = saved_change_to_color_scheme_id?
reload
@@ -115,11 +138,12 @@ class Theme < ActiveRecord::Base
end
def update_javascript_cache!
all_extra_js = theme_fields
.where(target_id: Theme.targets[:extra_js])
.order(:name, :id)
.pluck(:name, :value)
.to_h
all_extra_js =
theme_fields
.where(target_id: Theme.targets[:extra_js])
.order(:name, :id)
.pluck(:name, :value)
.to_h
if all_extra_js.present?
js_compiler = ThemeJavascriptCompiler.new(id, name)
@@ -135,9 +159,7 @@ class Theme < ActiveRecord::Base
after_destroy do
remove_from_cache!
if SiteSetting.default_theme_id == self.id
Theme.clear_default!
end
Theme.clear_default! if SiteSetting.default_theme_id == self.id
if self.id
ColorScheme
@@ -145,9 +167,7 @@ class Theme < ActiveRecord::Base
.where("id NOT IN (SELECT color_scheme_id FROM themes where color_scheme_id IS NOT NULL)")
.destroy_all
ColorScheme
.where(theme_id: self.id)
.update_all(theme_id: nil)
ColorScheme.where(theme_id: self.id).update_all(theme_id: nil)
end
Theme.expire_site_cache!
@@ -162,7 +182,7 @@ class Theme < ActiveRecord::Base
GlobalSetting.s3_cdn_url,
GlobalSetting.s3_endpoint,
GlobalSetting.s3_bucket,
Discourse.current_hostname
Discourse.current_hostname,
]
Digest::SHA1.hexdigest(dependencies.join)
end
@@ -199,10 +219,7 @@ class Theme < ActiveRecord::Base
get_set_cache "allowed_remote_theme_ids" do
urls = GlobalSetting.allowed_theme_repos.split(",").map(&:strip)
Theme
.joins(:remote_theme)
.where('remote_themes.remote_url in (?)', urls)
.pluck(:id)
Theme.joins(:remote_theme).where("remote_themes.remote_url in (?)", urls).pluck(:id)
end
end
@@ -239,10 +256,12 @@ class Theme < ActiveRecord::Base
[id]
end
disabled_ids = Theme.where(id: all_ids)
.includes(:remote_theme)
.select { |t| !t.supported? || !t.enabled? }
.map(&:id)
disabled_ids =
Theme
.where(id: all_ids)
.includes(:remote_theme)
.select { |t| !t.supported? || !t.enabled? }
.map(&:id)
all_ids - disabled_ids
end
@@ -250,9 +269,7 @@ class Theme < ActiveRecord::Base
def set_default!
if component
raise Discourse::InvalidParameters.new(
I18n.t("themes.errors.component_no_default")
)
raise Discourse::InvalidParameters.new(I18n.t("themes.errors.component_no_default"))
end
SiteSetting.default_theme_id = id
Theme.expire_site_cache!
@@ -335,22 +352,35 @@ class Theme < ActiveRecord::Base
end
def self.clear_cache!
DB.after_commit do
@cache.clear
end
DB.after_commit { @cache.clear }
end
def self.targets
@targets ||= Enum.new(common: 0, desktop: 1, mobile: 2, settings: 3, translations: 4, extra_scss: 5, extra_js: 6, tests_js: 7)
@targets ||=
Enum.new(
common: 0,
desktop: 1,
mobile: 2,
settings: 3,
translations: 4,
extra_scss: 5,
extra_js: 6,
tests_js: 7,
)
end
def self.lookup_target(target_id)
self.targets.invert[target_id]
end
def self.notify_theme_change(theme_ids, with_scheme: false, clear_manager_cache: true, all_themes: false)
def self.notify_theme_change(
theme_ids,
with_scheme: false,
clear_manager_cache: true,
all_themes: false
)
Stylesheet::Manager.clear_theme_cache!
targets = [:mobile_theme, :desktop_theme]
targets = %i[mobile_theme desktop_theme]
if with_scheme
targets.prepend(:desktop, :mobile, :admin)
@@ -364,7 +394,7 @@ class Theme < ActiveRecord::Base
message = refresh_message_for_targets(targets, theme_ids).flatten
end
MessageBus.publish('/file-change', message)
MessageBus.publish("/file-change", message)
end
def notify_theme_change(with_scheme: false)
@@ -386,20 +416,22 @@ class Theme < ActiveRecord::Base
def self.resolve_baked_field(theme_ids, target, name)
if target == :extra_js
require_rebake = ThemeField.where(theme_id: theme_ids, target_id: Theme.targets[:extra_js]).
where("compiler_version <> ?", Theme.compiler_version)
require_rebake =
ThemeField.where(theme_id: theme_ids, target_id: Theme.targets[:extra_js]).where(
"compiler_version <> ?",
Theme.compiler_version,
)
require_rebake.each { |tf| tf.ensure_baked! }
require_rebake.map(&:theme_id).uniq.each do |theme_id|
Theme.find(theme_id).update_javascript_cache!
end
require_rebake
.map(&:theme_id)
.uniq
.each { |theme_id| Theme.find(theme_id).update_javascript_cache! }
caches = JavascriptCache.where(theme_id: theme_ids)
caches = caches.sort_by { |cache| theme_ids.index(cache.theme_id) }
return caches.map do |c|
<<~HTML.html_safe
return caches.map { |c| <<~HTML.html_safe }.join("\n")
<link rel="preload" href="#{c.url}" as="script">
<script defer src='#{c.url}' data-theme-id='#{c.theme_id}'></script>
HTML
end.join("\n")
end
list_baked_fields(theme_ids, target, name).map { |f| f.value_baked || f.value }.join("\n")
end
@@ -413,8 +445,10 @@ class Theme < ActiveRecord::Base
else
target = :mobile if target == :mobile_theme
target = :desktop if target == :desktop_theme
fields = ThemeField.find_by_theme_ids(theme_ids)
.where(target_id: [Theme.targets[target], Theme.targets[:common]])
fields =
ThemeField.find_by_theme_ids(theme_ids).where(
target_id: [Theme.targets[target], Theme.targets[:common]],
)
fields = fields.where(name: name.to_s) unless name.nil?
fields = fields.order(:target_id)
end
@@ -455,12 +489,14 @@ class Theme < ActiveRecord::Base
target_id = Theme.targets[target.to_sym]
raise "Unknown target #{target} passed to set field" unless target_id
type_id ||= type ? ThemeField.types[type.to_sym] : ThemeField.guess_type(name: name, target: target)
type_id ||=
type ? ThemeField.types[type.to_sym] : ThemeField.guess_type(name: name, target: target)
raise "Unknown type #{type} passed to set field" unless type_id
value ||= ""
field = theme_fields.find { |f| f.name == name && f.target_id == target_id && f.type_id == type_id }
field =
theme_fields.find { |f| f.name == name && f.target_id == target_id && f.type_id == type_id }
if field
if value.blank? && !upload_id
theme_fields.delete field.destroy
@@ -473,16 +509,25 @@ class Theme < ActiveRecord::Base
end
field
else
theme_fields.build(target_id: target_id, value: value, name: name, type_id: type_id, upload_id: upload_id) if value.present? || upload_id.present?
if value.present? || upload_id.present?
theme_fields.build(
target_id: target_id,
value: value,
name: name,
type_id: type_id,
upload_id: upload_id,
)
end
end
end
def add_relative_theme!(kind, theme)
new_relation = if kind == :child
child_theme_relation.new(child_theme_id: theme.id)
else
parent_theme_relation.new(parent_theme_id: theme.id)
end
new_relation =
if kind == :child
child_theme_relation.new(child_theme_id: theme.id)
else
parent_theme_relation.new(parent_theme_id: theme.id)
end
if new_relation.save
child_themes.reload
parent_themes.reload
@@ -500,13 +545,20 @@ class Theme < ActiveRecord::Base
def translations(internal: false)
fallbacks = I18n.fallbacks[I18n.locale]
begin
data = locale_fields.first&.translation_data(with_overrides: false, internal: internal, fallback_fields: locale_fields)
data =
locale_fields.first&.translation_data(
with_overrides: false,
internal: internal,
fallback_fields: locale_fields,
)
return {} if data.nil?
best_translations = {}
fallbacks.reverse.each do |locale|
best_translations.deep_merge! data[locale] if data[locale]
end
ThemeTranslationManager.list_from_hash(theme: self, hash: best_translations, locale: I18n.locale)
fallbacks.reverse.each { |locale| best_translations.deep_merge! data[locale] if data[locale] }
ThemeTranslationManager.list_from_hash(
theme: self,
hash: best_translations,
locale: I18n.locale,
)
rescue ThemeTranslationParser::InvalidYaml
{}
end
@@ -517,9 +569,11 @@ class Theme < ActiveRecord::Base
return [] unless field && field.error.nil?
settings = []
ThemeSettingsParser.new(field).load do |name, default, type, opts|
settings << ThemeSettingsManager.create(name, default, type, self, opts)
end
ThemeSettingsParser
.new(field)
.load do |name, default, type, opts|
settings << ThemeSettingsManager.create(name, default, type, self, opts)
end
settings
end
@@ -532,15 +586,13 @@ class Theme < ActiveRecord::Base
def cached_default_settings
Theme.get_set_cache "default_settings_for_theme_#{self.id}" do
settings_hash = {}
self.settings.each do |setting|
settings_hash[setting.name] = setting.default
end
self.settings.each { |setting| settings_hash[setting.name] = setting.default }
theme_uploads = build_theme_uploads_hash
settings_hash['theme_uploads'] = theme_uploads if theme_uploads.present?
settings_hash["theme_uploads"] = theme_uploads if theme_uploads.present?
theme_uploads_local = build_local_theme_uploads_hash
settings_hash['theme_uploads_local'] = theme_uploads_local if theme_uploads_local.present?
settings_hash["theme_uploads_local"] = theme_uploads_local if theme_uploads_local.present?
settings_hash
end
@@ -548,15 +600,13 @@ class Theme < ActiveRecord::Base
def build_settings_hash
hash = {}
self.settings.each do |setting|
hash[setting.name] = setting.value
end
self.settings.each { |setting| hash[setting.name] = setting.value }
theme_uploads = build_theme_uploads_hash
hash['theme_uploads'] = theme_uploads if theme_uploads.present?
hash["theme_uploads"] = theme_uploads if theme_uploads.present?
theme_uploads_local = build_local_theme_uploads_hash
hash['theme_uploads_local'] = theme_uploads_local if theme_uploads_local.present?
hash["theme_uploads_local"] = theme_uploads_local if theme_uploads_local.present?
hash
end
@@ -564,9 +614,7 @@ class Theme < ActiveRecord::Base
def build_theme_uploads_hash
hash = {}
upload_fields.each do |field|
if field.upload&.url
hash[field.name] = Discourse.store.cdn_url(field.upload.url)
end
hash[field.name] = Discourse.store.cdn_url(field.upload.url) if field.upload&.url
end
hash
end
@@ -574,9 +622,7 @@ class Theme < ActiveRecord::Base
def build_local_theme_uploads_hash
hash = {}
upload_fields.each do |field|
if field.javascript_cache
hash[field.name] = field.javascript_cache.local_url
end
hash[field.name] = field.javascript_cache.local_url if field.javascript_cache
end
hash
end
@@ -587,9 +633,7 @@ class Theme < ActiveRecord::Base
target_setting.value = new_value
if target_setting.requests_refresh?
self.theme_setting_requests_refresh = true
end
self.theme_setting_requests_refresh = true if target_setting.requests_refresh?
end
def update_translation(translation_key, new_value)
@@ -603,9 +647,7 @@ class Theme < ActiveRecord::Base
theme_translation_overrides.each do |override|
cursor = hash
path = [override.locale] + override.translation_key.split(".")
path[0..-2].each do |key|
cursor = (cursor[key] ||= {})
end
path[0..-2].each { |key| cursor = (cursor[key] ||= {}) }
cursor[path[-1]] = override.value
end
hash
@@ -622,9 +664,9 @@ class Theme < ActiveRecord::Base
end
meta[:assets] = {}.tap do |hash|
theme_fields.where(type_id: ThemeField.types[:theme_upload_var]).each do |field|
hash[field.name] = field.file_path
end
theme_fields
.where(type_id: ThemeField.types[:theme_upload_var])
.each { |field| hash[field.name] = field.file_path }
end
meta[:color_schemes] = {}.tap do |hash|
@@ -632,7 +674,9 @@ class Theme < ActiveRecord::Base
# The selected color scheme may not belong to the theme, so include it anyway
schemes = [self.color_scheme] + schemes if self.color_scheme
schemes.uniq.each do |scheme|
hash[scheme.name] = {}.tap { |colors| scheme.colors.each { |color| colors[color.name] = color.hex } }
hash[scheme.name] = {}.tap do |colors|
scheme.colors.each { |color| colors[color.name] = color.hex }
end
end
end
@@ -643,8 +687,9 @@ class Theme < ActiveRecord::Base
end
end
meta[:learn_more] = "https://meta.discourse.org/t/beginners-guide-to-using-discourse-themes/91966"
meta[
:learn_more
] = "https://meta.discourse.org/t/beginners-guide-to-using-discourse-themes/91966"
end
end
@@ -659,9 +704,9 @@ class Theme < ActiveRecord::Base
def with_scss_load_paths
return yield([]) if self.extra_scss_fields.empty?
ThemeStore::ZipExporter.new(self).with_export_dir(extra_scss_only: true) do |dir|
yield ["#{dir}/stylesheets"]
end
ThemeStore::ZipExporter
.new(self)
.with_export_dir(extra_scss_only: true) { |dir| yield ["#{dir}/stylesheets"] }
end
def scss_variables
@@ -696,12 +741,15 @@ class Theme < ActiveRecord::Base
setting_row = ThemeSetting.where(theme_id: self.id, name: setting.name.to_s).first
if setting_row && setting_row.data_type != setting.type
if (setting_row.data_type == ThemeSetting.types[:list] &&
setting.type == ThemeSetting.types[:string] &&
setting.json_schema.present?)
if (
setting_row.data_type == ThemeSetting.types[:list] &&
setting.type == ThemeSetting.types[:string] && setting.json_schema.present?
)
convert_list_to_json_schema(setting_row, setting)
else
Rails.logger.warn("Theme setting type has changed but cannot be converted. \n\n #{setting.inspect}")
Rails.logger.warn(
"Theme setting type has changed but cannot be converted. \n\n #{setting.inspect}",
)
end
end
end
@@ -713,10 +761,10 @@ class Theme < ActiveRecord::Base
keys = schema["items"]["properties"].keys
return if !keys
current_values = CSV.parse(setting_row.value, **{ col_sep: '|' }).flatten
current_values = CSV.parse(setting_row.value, **{ col_sep: "|" }).flatten
new_values = []
current_values.each do |item|
parts = CSV.parse(item, **{ col_sep: ',' }).flatten
parts = CSV.parse(item, **{ col_sep: "," }).flatten
props = parts.map.with_index { |p, idx| [keys[idx], p] }.to_h
new_values << props
end
@@ -730,13 +778,14 @@ class Theme < ActiveRecord::Base
end
def baked_js_tests_with_digest
tests_tree = theme_fields
.where(target_id: Theme.targets[:tests_js])
.order(name: :asc)
.pluck(:name, :value)
.to_h
tests_tree =
theme_fields
.where(target_id: Theme.targets[:tests_js])
.order(name: :asc)
.pluck(:name, :value)
.to_h
return [nil, nil] if tests_tree.blank?
return nil, nil if tests_tree.blank?
compiler = ThemeJavascriptCompiler.new(id, name)
compiler.append_tree(tests_tree, for_tests: true)
@@ -748,7 +797,8 @@ class Theme < ActiveRecord::Base
content = compiler.content
if compiler.source_map
content += "\n//# sourceMappingURL=data:application/json;base64,#{Base64.strict_encode64(compiler.source_map)}\n"
content +=
"\n//# sourceMappingURL=data:application/json;base64,#{Base64.strict_encode64(compiler.source_map)}\n"
end
[content, Digest::SHA1.hexdigest(content)]
@@ -765,7 +815,11 @@ class Theme < ActiveRecord::Base
def find_disable_action_log
if component? && !enabled?
@disable_log ||= UserHistory.where(context: id.to_s, action: UserHistory.actions[:disable_theme_component]).order("created_at DESC").first
@disable_log ||=
UserHistory
.where(context: id.to_s, action: UserHistory.actions[:disable_theme_component])
.order("created_at DESC")
.first
end
end
end