darthapo (owner)

Revisions

gist: 32569 Download_button fork
public
Public Clone URL: git://gist.github.com/32569.git
Embed All Files: show embed
redshift_styles.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# For use with red: http://github.com/backtik/red/tree/master
require 'redshift'
 
#
# Usage:
#
# // The following are all comparable
# Styles.selectors['.task-entry'].properties[:width] = '300px'
# Styles['.task-entry'].properties[:width] = '300px'
# Styles['.task-entry'][:width] = '300px'
#
# The preceding example code will update the CSS Rule, so all
# elements with the classname of 'task-entry' will be updated.
# Which saves a bunch of looping over elements.
#
# Known to work on Safari 3 and Firefox 3
#
module Styles
  
  def self.[](key)
    @cache ||= {}
    # Would love to use Hash.new {|hash,key| ... } here, but it doesn't seem to work yet.
    @cache[key] = iterate_styles_for(key) unless @cache.has_key?(key)
    @cache[key]
  end
  
  def self.selectors
    Styles
  end
  
  def self.iterate_styles_for(ruleName)
    found_rule = nil
    `if(!document.styleSheets) return nil`
    `for( var s=0; s<document.styleSheets.length; s++) {
var rules = document.styleSheets[s].cssRules || document.styleSheets[s].rules;
for (var r=0; r<rules.length; r++) {
if(rules[r].selectorText == ruleName) { found_rule = rules[r]; break;}
};
}`
    found_rule ? Styles::Rule.new(found_rule) : nil
  end
  
  class Rule
    
    attr_accessor :selector, :properties
    
    def initialize(nativeRule)
      `this.__native__ = nativeRule`
      @selector = `this.__native__.selectorText`
      @properties = Styles::Styleset.new(`this.__native__.style`)
    end
    
    def [](key)
      @properties[key]
    end
    def []=(key, value)
      @properties[key] = value
    end
    
  end
  
  class Styleset
    
    def initialize(nativeStyle)
      `this.__native__ = nativeStyle`
    end
    
    def [](key)
      `this.__native__[(key.__value__ || key)]`
    end
    
    def []=(key, value)
      # Tweaked it so that you can pass it raw js strings too...
      `this.__native__[(key.__value__ || key)] = value.__value__ || value`
    end
    
  end
  
end