]> git.draconx.ca Git - homepage.git/blobdiff - lib/scss-var.rb
Automatically adjust colour scheme for "dark mode".
[homepage.git] / lib / scss-var.rb
index c6cf65464f415e750460e41c0b130bb1422112e7..b15680f6787deae166c5572b06e2a34f3368920e 100644 (file)
@@ -1,6 +1,6 @@
 # Nick's web site: Helper to retrieve global style variables in ruby.
 #
 # Nick's web site: Helper to retrieve global style variables in ruby.
 #
-# Copyright © 2020 Nick Bowler
+# 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
 #
 # 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
@@ -22,11 +22,9 @@ class GetSCSSGlobals < Sass::Tree::Visitors::Perform
         x = new(nil)
         x.send(:visit, root)
         result = x.instance_variable_get(:@globals)
         x = new(nil)
         x.send(:visit, root)
         result = x.instance_variable_get(:@globals)
-        if name.nil?
-            return result.freeze
-        else
-            return result[name]
-        end
+        return result.freeze if name.nil?
+
+        x.send(:rubify_result, result[name])
     end
 
     protected
     end
 
     protected
@@ -40,15 +38,35 @@ class GetSCSSGlobals < Sass::Tree::Visitors::Perform
 
     def visit_variable(node)
         super
 
     def visit_variable(node)
         super
-        
+
         x = @environment.global_env.var(node.name)
         x = @environment.global_env.var(node.name)
-        if !x.nil?
-            @globals[node.name] = x
+        @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"])
         end
     end
 end
 
 def scss_get_var(variable, item = @items["/style.scss"])
-    engine = Sass::Engine.for_file(item.raw_filename, { :syntax => :scss })
+    engine = Sass::Engine.for_file(item.raw_filename, {
+        :syntax => :scss,
+        :load_paths => ["."],
+    })
     return GetSCSSGlobals.visit(engine.to_tree, variable)
 end
     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