Bolt on lemonade to get started.

This commit is contained in:
Chris Eppstein 2010-09-12 10:45:45 -07:00
parent d1708dd2c3
commit a14a4f33ad
20 changed files with 741 additions and 0 deletions

View File

@ -10,3 +10,4 @@ gem "sass", "~> 3.1"
gem "rcov"
gem "rubyzip"
gem "livereload"
gem "chunky_png"

View File

@ -29,6 +29,24 @@ To run with an alternate version of Rails, make test/rails a symlink to that ver
To run with an alternate version of Haml & Sass, make test/haml a symlink to that version.
END
begin
require 'spec/rake/spectask'
Spec::Rake::SpecTask.new(:spec) do |spec|
spec.libs << 'lib' << 'spec'
spec.spec_files = FileList['spec/**/*_spec.rb']
end
Spec::Rake::SpecTask.new(:rcov) do |spec|
spec.libs << 'lib' << 'spec'
spec.pattern = 'spec/**/*_spec.rb'
spec.rcov = true
end
task :default => :spec
rescue LoadError
puts "Rspec (or a dependency) is not available. Try running bundler install"
end
desc "Compile Examples into HTML and CSS"
task :examples do
linked_haml = "tests/haml"

View File

@ -0,0 +1,38 @@
@mixin image-dimensions($file) {
height: image-height($file);
width: image-width($file);
}
@mixin sprite-image($file) {
background: sprite-image($file) $repeat;
}
@mixin sized-sprite-image($file) {
background: sprite-image($file);
@include image-dimensions($file);
}
@mixin sprite-folder($folder, $image-dimensions: false) {
.#{$folder} {
@if $image-dimensions {
background: sprite-url($folder);
}
@else {
background: sprite-url($folder) no-repeat;
}
}
@for $i from 0 to sprite-files-in-folder($folder) {
$file: sprite-file-from-folder($folder, $i);
.#{$folder}-#{image-basename($file)} {
@extend .#{$folder};
background-position: sprite-position(sprite-file-from-folder($folder, $i));
@if $image-dimensions {
@include image-dimensions($file);
}
}
}
}
@mixin sized-sprite-folder($folder) {
@include sprite-folder($folder, true);
}

View File

@ -18,3 +18,5 @@ end
%w(configuration frameworks app_integration actions compiler).each do |lib|
require "compass/#{lib}"
end
require "lemonade"

127
lib/lemonade.rb Normal file
View File

@ -0,0 +1,127 @@
require 'chunky_png'
require 'lemonade/sprite_info.rb'
module Lemonade
@@sprites = {}
@@sprites_path = nil
@@images_path = nil
class << self
def sprites
@@sprites
end
def sprites_path
@@sprites_path || images_path
end
def sprites_path=(path)
@@sprites_path = path
end
def images_path
@@images_path || (defined?(Compass) ? Compass.configuration.images_path : 'public/images')
end
def images_path=(path)
@@images_path = path
end
def reset
@@sprites = {}
end
def generate_sprites
sprites.each do |sprite_name, sprite|
calculate_sprite sprite
if sprite_changed?(sprite_name, sprite)
generate_sprite_image sprite
remember_sprite_info! sprite_name, sprite
end
end
end
def extend_sass!
require 'sass'
require 'sass/plugin'
require File.expand_path('../lemonade/sass_functions', __FILE__)
require File.expand_path('../lemonade/sass_extension', __FILE__)
end
def sprite_changed?(sprite_name, sprite)
existing_sprite_info = YAML.load(File.read(sprite_info_file(sprite_name)))
existing_sprite_info[:sprite] != sprite or existing_sprite_info[:timestamps] != timestamps(sprite)
rescue
true
end
def remember_sprite_info!(sprite_name, sprite)
File.open(sprite_info_file(sprite_name), 'w') do |file|
file << {
:sprite => sprite,
:timestamps => timestamps(sprite),
}.to_yaml
end
end
private
def sprite_info_file(sprite_name)
File.join(Lemonade.images_path, "#{sprite_name}.sprite_info.yml")
end
def timestamps(sprite)
result = {}
sprite[:images].each do |image|
file_name = image[:file]
result[file_name] = File.ctime(file_name)
end
result
end
def calculate_sprite(sprite)
width, margin_bottom, y = 0, 0, 0
sprite[:images].each do |sprite_item|
if sprite_item[:index] == 0
margin_top = 0
elsif sprite_item[:margin_top] > margin_bottom
margin_top = sprite_item[:margin_top]
else
margin_top = margin_bottom
end
y += margin_top
sprite_item[:y] = Sass::Script::Number.new(y, ['px'])
y += sprite_item[:height]
width = sprite_item[:width] if sprite_item[:width] > width
margin_bottom = sprite_item[:margin_bottom]
end
sprite[:height] = y
sprite[:width] = width
end
def generate_sprite_image(sprite)
sprite_image = ChunkyPNG::Image.new(sprite[:width], sprite[:height], ChunkyPNG::Color::TRANSPARENT)
sprite[:images].each do |sprite_item|
sprite_item_image = ChunkyPNG::Image.from_file(sprite_item[:file])
x = (sprite[:width] - sprite_item[:width]) * (sprite_item[:x].value / 100)
y = sprite_item[:y].value
sprite_image.replace sprite_item_image, x, y
end
sprite_image.save File.join(Lemonade.images_path, sprite[:file])
end
end
end
if defined?(ActiveSupport) and Sass::Util.has?(:public_method, ActiveSupport, :on_load)
# Rails 3.0
ActiveSupport.on_load :before_initialize do
Lemonade.extend_sass!
end
else
Lemonade.extend_sass!
end

View File

@ -0,0 +1,21 @@
module Sass
module Tree
class RootNode < Node
alias_method :render_without_lemonade, :render
def render
if result = render_without_lemonade
Lemonade.generate_sprites
result = ERB.new(result).result(binding)
Lemonade.reset
return result
end
end
end
end
end

View File

@ -0,0 +1,119 @@
module Sass::Script::Functions
def sprite_url(file)
dir, name, basename = extract_names(file)
sprite = sprite_for("#{dir}#{name}")
Sass::Script::SpriteInfo.new(:url, sprite)
end
def sprite_position(file, position_x = nil, position_y_shift = nil, margin_top_or_both = nil, margin_bottom = nil)
sprite, sprite_item = sprite_url_and_position(file, position_x, position_y_shift, margin_top_or_both, margin_bottom)
Sass::Script::SpriteInfo.new(:position, sprite, sprite_item, position_x, position_y_shift)
end
def sprite_image(file, position_x = nil, position_y_shift = nil, margin_top_or_both = nil, margin_bottom = nil)
sprite, sprite_item = sprite_url_and_position(file, position_x, position_y_shift, margin_top_or_both, margin_bottom)
Sass::Script::SpriteInfo.new(:both, sprite, sprite_item, position_x, position_y_shift)
end
alias_method :sprite_img, :sprite_image
def sprite_files_in_folder(folder)
assert_type folder, :String
count = sprite_file_list_from_folder(folder).length
Sass::Script::Number.new(count)
end
def sprite_file_from_folder(folder, n)
assert_type folder, :String
assert_type n, :Number
file = sprite_file_list_from_folder(folder)[n.to_i]
file = File.basename(file)
Sass::Script::String.new(File.join(folder.value, file))
end
def sprite_name(file)
dir, name, basename = extract_names(file)
Sass::Script::String.new(name)
end
def image_basename(file)
dir, name, basename = extract_names(file, :check_file => true)
Sass::Script::String.new(basename)
end
private
def sprite_file_list_from_folder(folder)
dir = File.join(Lemonade.sprites_path, folder.value)
Dir.glob(File.join(dir, '*.png')).sort
end
def sprite_url_and_position(file, position_x = nil, position_y_shift = nil, margin_top_or_both = nil, margin_bottom = nil)
dir, name, basename = extract_names(file, :check_file => true)
filestr = File.join(Lemonade.sprites_path, file.value)
sprite_file = "#{dir}#{name}.png"
sprite = sprite_for(sprite_file)
sprite_item = image_for(sprite, filestr, position_x, position_y_shift, margin_top_or_both, margin_bottom)
# Create a temporary destination file so compass doesn't complain about a missing image
FileUtils.touch File.join(Lemonade.images_path, sprite_file)
[sprite, sprite_item]
end
def extract_names(file, options = {})
assert_type file, :String
unless (file.value =~ %r(^(.+/)?([^\.]+?)(/(.+?)\.(png))?$)) == 0
raise Sass::SyntaxError, 'Please provide a file in a folder: e.g. sprites/button.png'
end
dir, name, basename = $1, $2, $4
if options[:check_file] and basename.nil?
raise Sass::SyntaxError, 'Please provide a file in a folder: e.g. sprites/button.png'
end
[dir, name, basename]
end
def sprite_for(file)
file = "#{file}.png" unless file =~ /\.png$/
Lemonade.sprites[file] ||= {
:file => "#{file}",
:height => 0,
:width => 0,
:images => [],
:margin_bottom => 0
}
end
def image_for(sprite, file, position_x, position_y_shift, margin_top_or_both, margin_bottom)
image = sprite[:images].detect{ |image| image[:file] == file }
margin_top_or_both ||= Sass::Script::Number.new(0)
margin_top = margin_top_or_both.value #calculate_margin_top(sprite, margin_top_or_both, margin_bottom)
margin_bottom = (margin_bottom || margin_top_or_both).value
if image
image[:margin_top] = margin_top if margin_top > image[:margin_top]
image[:margin_bottom] = margin_bottom if margin_bottom > image[:margin_bottom]
else
width, height = ChunkyPNG::Image.from_file(file).size
x = (position_x and position_x.numerator_units == %w(%)) ? position_x : Sass::Script::Number.new(0)
y = sprite[:height] + margin_top
y = Sass::Script::Number.new(y, y == 0 ? [] : ['px'])
image = {
:file => file,
:height => height,
:width => width,
:x => x,
:margin_top => margin_top,
:margin_bottom => margin_bottom,
:index => sprite[:images].length
}
sprite[:images] << image
end
image
rescue Errno::ENOENT
raise Sass::SyntaxError, "#{file} does not exist in sprites_dir #{Lemonade.sprites_path}"
rescue ChunkyPNG::SignatureMismatch
raise Sass::SyntaxError, "#{file} is not a recognized png file, can't use for sprite creation"
end
end

View File

@ -0,0 +1,63 @@
require 'sass/script/literal'
module Sass::Script
class SpriteInfo < Literal
attr_reader :sprite
attr_reader :sprite_item
attr_reader :type
def initialize(type, sprite, sprite_item = nil, position_x = nil, position_y_shift = nil)
super(nil)
@type = type
@sprite = sprite
@sprite_item = sprite_item
@position_x = position_x
@position_y_shift = position_y_shift
end
def to_s(opts = {})
case @type
when :position
position
when :url
url
when :both
pos = position
if pos == '0 0'
url
else
"#{url} #{pos}"
end
end
end
def to_sass
to_s
end
private
def position
x = @position_x || 0
if @sprite_item[:index] == 0 and (@position_y_shift.nil? or @position_y_shift.value == 0)
"#{x.inspect} 0"
else
expression = "Lemonade.sprites['#{@sprite[:file]}'][:images][#{@sprite_item[:index]}][:y].unary_minus"
expression << ".plus(Sass::Script::Number.new(#{@position_y_shift.value}, ['px']))" if @position_y_shift
"#{x.inspect} <%= #{expression} %>"
end
end
def url
if defined?(Compass)
compass = Class.new.extend(Compass::SassExtensions::Functions::Urls)
compass.image_url(Sass::Script::String.new(@sprite[:file])).to_s
else
"url('/#{@sprite[:file]}')"
end
end
end
end

3
lib/lemonade/version.rb Normal file
View File

@ -0,0 +1,3 @@
module Lemonade
Version = "1.0.0.beta.1"
end

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

66
spec/lemonade_spec.rb Normal file
View File

@ -0,0 +1,66 @@
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe Lemonade do
before :each do
@sprite = {
:info => 'info',
:images => [
{ :file => 'file1' },
{ :file => 'file2' },
]
}
@file = ""
File.stub!(:read => @file)
Lemonade.stub(:images_path).and_return('image_path')
File.stub!(:ctime => Time.parse('2010-01-01 12:00'))
end
###
describe '#remember_sprite_info' do
subject { Lemonade }
it 'should save sprite info into a file' do
File.should_receive(:open).with(File.join('image_path', 'the_sprite.sprite_info.yml'), 'w').and_yield(@file)
@file.should_receive(:<<)
subject.remember_sprite_info!('the_sprite', @sprite)
end
end
###
describe '#sprite_changed?' do
subject { Lemonade }
it 'should be false if nothing changed' do
File.should_receive(:open).and_yield(@file)
subject.remember_sprite_info!('the sprite', @sprite)
subject.sprite_changed?('the sprite', @sprite).should be_false
end
it 'should be true if the sprite info has changed' do
File.should_receive(:open).and_yield(@file)
subject.remember_sprite_info!('the sprite', @sprite)
@sprite[:info] = 'changed info'
subject.sprite_changed?('the sprite', @sprite).should be_true
end
it 'should be true if the images changed' do
File.should_receive(:open).and_yield(@file)
subject.remember_sprite_info!('the sprite', @sprite)
@sprite[:images] = []
subject.sprite_changed?('the sprite', @sprite).should be_true
end
it 'should be true if a images timestamp changed' do
File.should_receive(:open).and_yield(@file)
subject.remember_sprite_info!('the sprite', @sprite)
File.stub!(:ctime => Time.now)
subject.sprite_changed?('the sprite', @sprite).should be_true
end
end
end

216
spec/sass_functions_spec.rb Normal file
View File

@ -0,0 +1,216 @@
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe Sass::Script::Functions do
before :each do
Lemonade.reset
FileUtils.cp_r File.dirname(__FILE__) + '/images', IMAGES_TMP_PATH
end
after :each do
FileUtils.rm_r IMAGES_TMP_PATH
end
def image_size(file)
IO.read(IMAGES_TMP_PATH + '/' + file)[0x10..0x18].unpack('NN')
end
def evaluate(*values)
sass = 'div' + values.map{ |value| "\n background: #{value}" }.join
css = Sass::Engine.new(sass, :syntax => :sass).render
# find rendered CSS values
# strip selectors, porperty names, semicolons and whitespace
css = css.gsub(/div \{\s*background: (.+?);\s*\}\s*/m, '\\1').split(/;\s*background: /)
css = css.first if css.length == 1
return css
end
###
it "should return the sprite file name" do
evaluate('sprite-image("sprites/30x30.png")').should == "url('/sprites.png')"
end
it "should also work with `sprite-img`" do
evaluate('sprite-img("sprites/30x30.png")').should == "url('/sprites.png')"
end
it "should work in folders with dashes and underscores" do
evaluate('sprite-image("other_images/more-images/sprites/test.png")').should ==
"url('/other_images/more-images/sprites.png')"
end
it "should not work without any folder" do
lambda { evaluate('sprite-image("test.png")') }.should raise_exception(Sass::SyntaxError)
end
it "should set the background position" do
evaluate('sprite-image("sprites/30x30.png") sprite-image("sprites/150x10.png")').should ==
"url('/sprites.png') url('/sprites.png') 0 -30px"
image_size('sprites.png').should == [150, 40]
end
it "should use the X position" do
evaluate('sprite-image("sprites/30x30.png", 5px, 0)').should == "url('/sprites.png') 5px 0"
image_size('sprites.png').should == [30, 30]
end
it "should include the Y position" do
evaluate('sprite-image("sprites/30x30.png", 0, 3px) sprite-image("sprites/150x10.png", 0, -6px)').should ==
"url('/sprites.png') 0 3px url('/sprites.png') 0 -36px"
end
it "should calculate 20px empty space between sprites" do
# Resulting sprite should look like (1 line = 10px height, X = placed image):
# X
#
#
# XX
# XX
#
#
# XXX
# XXX
# XXX
evaluate(
'sprite-image("sprites/10x10.png")',
'sprite-image("sprites/20x20.png", 0, 0, 20px)',
'sprite-image("sprites/30x30.png", 0, 0, 20px)'
).should == [
"url('/sprites.png')",
"url('/sprites.png') 0 -30px",
"url('/sprites.png') 0 -70px"
]
image_size('sprites.png').should == [30, 100]
end
it "should calculate empty space between sprites and combine space like CSS margins" do
# Resulting sprite should look like (1 line = 10px height, X = placed image):
# X
#
#
#
# XX
# XX
#
# XXX
# XXX
# XXX
evaluate(
'sprite-image("sprites/10x10.png", 0, 0, 0, 30px)',
'sprite-image("sprites/20x20.png", 0, 0, 20px, 5px)',
'sprite-image("sprites/30x30.png", 0, 0, 10px)'
).should == [
"url('/sprites.png')",
"url('/sprites.png') 0 -40px",
"url('/sprites.png') 0 -70px"
]
image_size('sprites.png').should == [30, 100]
end
it "should calculate empty space correctly when 2 output images are uses" do
evaluate(
'sprite-image("sprites/10x10.png", 0, 0, 0, 30px)',
'sprite-image("other_images/test.png")',
'sprite-image("sprites/20x20.png", 0, 0, 20px, 5px)'
).should == [
"url('/sprites.png')",
"url('/other_images.png')",
"url('/sprites.png') 0 -40px"
]
end
it "should allow % for x positions" do
# Resulting sprite should look like (1 line = 10px height, X = placed image):
# XXXXXXXXXXXXXXX
# X
evaluate(
'sprite-image("sprites/150x10.png")',
'sprite-image("sprites/10x10.png", 100%)'
).should == [
"url('/sprites.png')",
"url('/sprites.png') 100% -10px"
]
end
it "should not compose the same image twice" do
evaluate(
'sprite-image("sprites/10x10.png")',
'sprite-image("sprites/20x20.png")',
'sprite-image("sprites/20x20.png")' # reuse image from line above
).should == [
"url('/sprites.png')",
"url('/sprites.png') 0 -10px",
"url('/sprites.png') 0 -10px"
]
image_size('sprites.png').should == [20, 30]
end
it "should calculate the maximum spacing between images" do
evaluate(
'sprite-image("sprites/10x10.png")',
'sprite-image("sprites/20x20.png", 0, 0, 10px)',
'sprite-image("sprites/20x20.png", 0, 0, 99px)' # 99px > 10px
).should == [
"url('/sprites.png')",
"url('/sprites.png') 0 -109px", # use 99px spacing
"url('/sprites.png') 0 -109px"
]
image_size('sprites.png').should == [20, 129]
end
it "should calculate the maximum spacing between images for margin bottom" do
evaluate(
'sprite-image("sprites/10x10.png", 0, 0, 0, 10px)',
'sprite-image("sprites/10x10.png", 0, 0, 0, 99px)', # 99px > 10px
'sprite-image("sprites/20x20.png")'
).should == [
"url('/sprites.png')",
"url('/sprites.png')",
"url('/sprites.png') 0 -109px" # use 99px spacing
]
image_size('sprites.png').should == [20, 129]
end
it "should output the background-position" do
evaluate(
'sprite-position("sprites/10x10.png")',
'sprite-position("sprites/20x20.png")'
).should == [
"0 0",
"0 -10px"
]
end
it "should output the background-image URL" do
evaluate('sprite-url("sprites")').should == "url('/sprites.png')"
evaluate('sprite-url("sprites/10x10.png")').should == "url('/sprites.png')"
evaluate('sprite-url("sprites/20x20.png")').should == "url('/sprites.png')"
evaluate('sprite-url("other_images/test.png")').should == "url('/other_images.png')"
end
it "should count the PNG files in a folder" do
evaluate('sprite-files-in-folder("sprites")').to_i.should == 4
end
it "should output the n-th file in a folder" do
evaluate('sprite-file-from-folder("sprites", 0)').should == "sprites/10x10.png"
evaluate('sprite-file-from-folder("sprites", 1)').should == "sprites/150x10.png"
end
it "should output the filename without extention for the sprite" do
evaluate('sprite-name("sprites")').should == "sprites"
evaluate('sprite-name("sprites/10x10.png")').should == "sprites"
end
it "should output the filename without extention for the sprite item" do
evaluate('image-basename("sprites/10x10.png")').should == "10x10"
end
end

4
spec/spec.opts Normal file
View File

@ -0,0 +1,4 @@
--colour
--format s
--loadby mtime
--reverse

14
spec/spec_helper.rb Normal file
View File

@ -0,0 +1,14 @@
$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'rubygems'
require 'compass'
require 'spec'
require 'spec/autorun'
IMAGES_TMP_PATH = File.join(File.dirname(__FILE__), 'images-tmp')
Lemonade.images_path = IMAGES_TMP_PATH
Spec::Runner.configure do |config|
end

49
spec/sprite_info_spec.rb Normal file
View File

@ -0,0 +1,49 @@
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe Sass::Script::SpriteInfo do
def sprite_info(*args)
Sass::Script::SpriteInfo.new(*args).to_s
end
##
it "should output the position for the first sprite" do
sprite = { :file => "sprites.png" }
sprite_item = { :y => Sass::Script::Number.new(20, ['px']), :index => 0 }
x = Sass::Script::Number.new(10, ['px'])
sprite_info(:position, sprite, sprite_item, x).should == "10px 0"
end
it "should output the position for the second+ sprite" do
sprite = { :file => "sprites.png" }
sprite_item = { :y => Sass::Script::Number.new(20, ['px']), :index => 1 }
x = Sass::Script::Number.new(10, ['px'])
sprite_info(:position, sprite, sprite_item, x).should ==
"10px <%= Lemonade.sprites['sprites.png'][:images][1][:y].unary_minus %>"
end
it "should output the position with y shift" do
sprite = { :file => "sprites.png" }
sprite_item = { :y => Sass::Script::Number.new(20, ['px']), :index => 1 }
x = Sass::Script::Number.new(10, ['px'])
y_shift = Sass::Script::Number.new(3, ['px'])
sprite_info(:position, sprite, sprite_item, x, y_shift).should ==
"10px <%= Lemonade.sprites['sprites.png'][:images][1][:y].unary_minus.plus(Sass::Script::Number.new(3, ['px'])) %>"
end
it "should output the position with percentage" do
sprite = { :file => "sprites.png" }
sprite_item = { :y => Sass::Script::Number.new(20, ['px']), :index => 2 }
x = Sass::Script::Number.new(100, ['%'])
sprite_info(:position, sprite, sprite_item, x).should ==
"100% <%= Lemonade.sprites['sprites.png'][:images][2][:y].unary_minus %>"
end
it "should output the url" do
sprite = { :file => "sprites.png" }
sprite_item = { }
sprite_info(:url, sprite, sprite_item).should == "url('/sprites.png')"
end
end