# Nick's web site: Helper to retrieve global style variables in ruby. # # Copyright © 2020, 2022 Nick Bowler # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . require 'sass' class GetSCSSGlobals < Sass::Tree::Visitors::Perform def self.visit(root, name = nil) x = new(nil) x.send(:visit, root) result = x.instance_variable_get(:@globals) return result.freeze if name.nil? x.send(:rubify_result, result[name]) end protected def initialize(environment) @globals = {} @globals.default_proc = proc { |h, k| if h.key? k.to_s then h[k.to_s] end } super end def visit_variable(node) super x = @environment.global_env.var(node.name) @globals[node.name] = x unless x.nil? end # Convert SASS maps and lists to ruby equivalents that are actually usable. def rubify_result(val) case val when Sass::Script::Value::Map val.to_h.each_with_object({}) do |(k, v), h| h[k.to_s.to_sym] = rubify_result(v) end when Sass::Script::Value::List val.to_a.map { |v| rubify_result(v) } else val end end end def scss_get_var(variable, item = @items["/style.scss"]) engine = Sass::Engine.for_file(item.raw_filename, { :syntax => :scss, :load_paths => ["."], }) return GetSCSSGlobals.visit(engine.to_tree, variable) end def scss_get_colour(colour, index = 0, item = @items["/style.scss"]) cmap = scss_get_var(:colourmap, item); [cmap[colour]].flatten[index] end