package File::Assets; use warnings; use strict; =head1 NAME File::Assets - Manage .css and .js assets for a web page or application =head1 VERSION Version 0.064 =cut our $VERSION = '0.064'; =head1 SYNOPSIS use File::Assets my $assets = File::Assets->new( base => [ $uri_root, $dir_root ] ) # Put minified files in $dir_root/built/... (the trailing slash is important) $assets->set_output_path("built/") # File::Assets will automatically detect the type based on the extension $assets->include("/static/style.css") # You can also include external assets: $assets->include("http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"); # This asset won't get included twice, as File::Assets will ignore repeats of a path $assets->include("/static/style.css") # And finally ... $assets->export # Or you can iterate (in order) for my $asset ($assets->exports) { print $asset->uri, "\n"; } In your .tt (Template Toolkit) files: [% WRAPPER page.tt %] [% assets.include("/static/special-style.css", 100) %] # The "100" is the rank, which makes sure it is exported after other assets [% asset = BLOCK %] [% END %] [% assets.include(asset) %] # This will include the css into an inline asset with the media type of "print" # ... finally, in your "main" template: [% CLEAR -%] [% assets.export("css") %] [% content %] [% assets.export("js") %] Use the minify option to perform minification before export my $assets = File::Assets->new( minify => 1, ... ) =head1 DESCRIPTION File::Assets is a tool for managing JavaScript and CSS assets in a (web) application. It allows you to "publish" assests in one place after having specified them in different parts of the application (e.g. throughout request and template processing phases). This package has the added bonus of assisting with minification and filtering of assets. Support is built-in for YUI Compressor (L), L, L, L, and L. File::Assets was built with L in mind, although this package is framework agnostic. Look at L for an easy way to integrate File::Assets with Catalyst. =head1 USAGE =head2 Cascading style sheets and their media types A cascading style sheet can be one of many different media types. For more information, look here: L This can cause a problem when minifying, since, for example, you can't bundle a media type of screen with a media type of print. File::Assets handles this situation by treating .css files of different media types separately. To control the media type of a text/css asset, you can do the following: $assets->include("/path/to/printstyle.css", ..., { media => "print" }); # The asset will be exported with the print-media indicator $assets->include_content($content, "text/css", ..., { media => "screen" }); # Ditto, but for the screen type =head2 Including assets in the middle of processing a Template Toolkit template Sometimes, in the middle of a TT template, you want to include a new asset. Usually you would do something like this: [% assets.include("/include/style.css") %] But then this will show up in your output, because ->include returns an object: File::Assets::Asset=HASH(0x99047e4) The way around this is to use the TT "CALL" directive, as in the following: [% CALL assets.include("/include/style.css") %] =head2 Avoid minifying assets on every request (if you minify) By default, File::Assets will avoid re-minifying assets if nothing in the files have changed. However, in a web application, this can be a problem if you serve up two web pages that have different assets. That's because File::Assets will detect different assets being served in page A versus assets being served in page B (think AJAX interface vs. plain HTML with some CSS). The way around this problem is to name your assets object with a unique name per assets bundle. By default, the name is "assets", but can be changed with $assets->name(): my $assets = File::Assets->new(...); $assets->name("standard"); You can change the name of the assets at anytime before exporting. =head2 YUI Compressor 2.2.5 is required If you want to use the YUI Compressor, you should have version 2.2.5 or above. YUI Compressor 2.1.1 (and below) will *NOT WORK* To use the compressor for minification specify the path to the .jar like so: my $assets = File::Assets->new( minify => "/path/to/yuicompressor.jar", ... ) =head2 Specifying an C pattern When aggregating or minifying assets, you need to put the result in a new file. You can use the following directives when crafting a path/filename pattern: %n The name of the asset, "assets" by default %e The extension of the asset (e.g. css, js) %f The fingerprint of the asset collection (a hexadecimal digest of the concatenated digest of each asset in the collection) %k The kind of the asset (e.g. css-screen, css, css-print, js) %h The kind head-part of the asset (e.g. css, js) %l The kind tail-part of the asset (e.g. screen, print) (essentially the media type of a .css asset) In addition, in each of the above, a ".", "/" or "-" can be placed in between the "%" and directive character. This will result in a ".", "/", or "-" being prepended to the directive value. The default pattern is: %n%-l%-f.%e A pattern of C<%n%-l.%e> can result in the following: assets.css # name of "assets", no media type, an asset type of CSS (.css) assets-screen.css # name of "assets", media type of "screen", an asset type of CSS (.css) assets.js # name of "assets", an asset type of JavaScript (.js) If the pattern ends with a "/", then the default pattern will be appended xyzzy/ => xyzzy/%n%-l-%f.%e If the pattern does not have an extension-like ending, then "%.e" will be appended xyzzy => xyzzy.%e =head2 Strange output or "sticky" content File::Assets uses built-in caching to share content across different objects (via File::Assets::Cache). If you're having problems try disabling the cache by passing "cache => 0" to File::Assets->new =head1 METHODS =cut # If the pattern does NOT begin with a "/", then the base dir will be prepended use strict; use warnings; use Object::Tiny qw/cache registry _registry_hash rsc filter_scheme output_path_scheme output_asset_scheme/; use File::Assets::Carp; use Tie::LLHash; use Path::Resource; use Scalar::Util qw/blessed refaddr/; use HTML::Declare qw/LINK SCRIPT STYLE/; use File::Assets::Asset; use File::Assets::Cache; use File::Assets::Kind; use File::Assets::Bucket; =head2 File::Assets->new( base => , output_path => , minify => ) Create and return a new File::Assets object. You can configure the object with the following: base # A hash reference with a "uri" key/value and a "dir" key/value. For example: { uri => http://example.com/assets, dir => /var/www/htdocs/assets } # A URI::ToDisk object # A Path::Resource object minify # "1" or "best" - Will either use JavaScript::Minifier::XS> & CSS::Minifier::XS or JavaScript::Minifier> & CSS::Minifier (depending on availability) for minification # "0" or "" or undef - Don't do any minfication (this is the default) # "./path/to/yuicompressor.jar" - Will use YUI Compressor via the given .jar for minification # "minifier" - Will use JavaScript::Minifier & CSS::Minifier for minification # "xs" or "minifier-xs" - Will use JavaScript::Minifier::XS & CSS::Minifier::XS for minification output_path # Designates the output path for minified .css and .js assets The default output path pattern is "%n%-l%-d.%e" (rooted at the dir of ) See above in "Specifying an output_path pattern" for details =cut sub new { my $self = bless {}, shift; local %_ = @_; $self->set_base($_{rsc} || $_{base_rsc} || $_{base}); $self->set_base_uri($_{uri} || $_{base_uri}) if $_{uri} || $_{base_uri}; $self->set_base_dir($_{dir} || $_{base_dir}) if $_{dir} || $_{base_dir}; $self->set_base_path($_{base_path}) if $_{base_path}; $self->set_output_path($_{output_path} || $_{output_path_scheme} || []); $self->name($_{name}); $_{cache} = 1 unless exists $_{cache}; $self->set_cache($_{cache}) if $_{cache}; # my $rsc = File::Assets::Util->parse_rsc($_{rsc} || $_{base_rsc} || $_{base}); # $rsc->uri($_{uri} || $_{base_uri}) if $_{uri} || $_{base_uri}; # $rsc->dir($_{dir} || $_{base_dir}) if $_{dir} || $_{base_dir}; # $rsc->path($_{base_path}) if $_{base_path}; # $self->{rsc} = $rsc; my %registry; $self->{registry} = tie(%registry, qw/Tie::LLHash/, { lazy => 1 }); $self->{_registry_hash} = \%registry; $self->{filter_scheme} = {}; my $filter_scheme = $_{filter} || $_{filters} || $_{filter_scheme} || []; for my $rule (@$filter_scheme) { $self->filter(@$rule); } if (my $minify = $_{minify}) { if ($minify eq 1 || $minify =~ m/^\s*(?:minifier-)?best\s*$/i) { $self->filter("minifier-best") } elsif ($minify =~ m/^\s*yui-?compressor:/) { $self->filter($minify) } elsif ($minify =~ m/\.jar/i) { $self->filter("yuicompressor:$minify") } elsif ($minify =~ m/^\s*(?:minifier-)?xs\s*$/i) { $self->filter("minifier-xs") } elsif ($minify =~ m/^\s*minifier\s*$/i) { $self->filter("minifier") } elsif ($minify =~ m/^\s*concat\s*$/i) { $self->filter("concat") } else { croak "Don't understand minify option ($minify)" } } return $self; } =head2 $asset = $assets->include(, [ , , { ... } ]) =head2 $asset = $assets->include_path(, [ , , { ... } ]) First, if is a scalar reference or "looks like" some HTML (starts with a angle bracket, e.g.: ), then it will be treated as inline content. Otherwise, this will include an asset located at "/" for processing. The asset will be exported as "/" Optionally, you can specify a rank, where a lower number (i.e. -2, -100) causes the asset to appear earlier in the exports list, and a higher number (i.e. 6, 39) causes the asset to appear later in the exports list. By default, all assets start out with a neutral rank of 0. Also, optionally, you can specify a type override as the third argument. By default, the newly created $asset is NOT inline. Returns the newly created asset. NOTE: See below for how the extra hash on the end is handled =head2 $asset = $assets->include({ ... }) Another way to invoke include is by passing in a hash reference. The hash reference should contain the follwing information: path # The path to the asset file, relative to base content # The content of the asset type # Optional if a path is given, required for content rank # Optional, 0 by default (Less than zero is earlier, greater than zero is later) inline # Optional, by default true if content was given, false is a path was given base # Optional, by default the base of $assets You can also pass extra information through the hash. Any extra information will be bundled in the ->attributes hash of $asset. For example, you can control the media type of a text/css asset by doing something like: $assets->include("/path/to/printstyle.css", ..., { media => "print" }) # The asset will be exported with the print-media indicator NOTE: The order of and doesn't really matter, since we can detect whether something looks like a rank (number) or not, and correct for it (and it does). =cut sub include_path { my $self = shift; return $self->include(@_); } my $rankish = qr/^[\-\+]?[\.\d]+$/; # A regular expression for a string that looks like a rank sub _correct_for_proper_rank_and_type_order ($) { my $asset = shift; if (defined $asset->{type} && $asset->{type} =~ $rankish || defined $asset->{rank} && $asset->{rank} !~ $rankish) { # Looks like someone entered a rank as the type or vice versa, so we'll switch them my $rank = delete $asset->{type}; my $type = delete $asset->{rank}; $asset->{type} = $type if defined $type; $asset->{rank} = $rank if defined $rank; } } sub include { my $self = shift; my (@asset, $path); if (ref $_[0] ne "HASH") { $path = shift; croak "Don't have a path to include" unless defined $path && length $path; if (ref $path eq "SCALAR" || $path =~ m/^\s* $path; } else { return $self->fetch($path) if $self->exists($path); push @asset, path => $path; } } for (qw/rank type/) { last if ! @_ || ref $_[0] eq "HASH"; push @asset, $_ => shift; } push @asset, %{ $_[0] } if @_ && ref $_[0] eq "HASH"; my %asset = @asset; _correct_for_proper_rank_and_type_order \%asset; my $asset = File::Assets::Asset->new(base => $self->rsc, cache => $self->cache, %asset); return $self->fetch_or_store($asset); } =head2 $asset = $assets->include_content(, [ , , { ... } ]) Include an asset with some content and of the supplied type. The value of can be a "plain" string or a scalar reference. You can include content that looks like HTML: In the above case, is optional, as File::Assets can detect from the tag that you're supplying a style sheet. Furthermore, the method will find all the attributes in the tag and put them into the asset. So the resulting asset from including the above will have a type of "text/css" and media of "print". For now, only