Created
December 6, 2008 00:31
-
-
Save mattmccray/32569 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment