daily pastebin goal
26%
SHARE
TWEET

Untitled

a guest May 16th, 2018 107 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. use CSS::DOM;
  7. use File::Slurp;
  8. use HTML::DOM;
  9. use HTML::TokeParser;
  10.  
  11. die "convert html_file css_file" unless @ARGV == 2;
  12. my ($html_file, $css_file) = @ARGV;
  13.  
  14. my $html_parser = HTML::TokeParser->new($html_file)
  15.     or die "Cannot open '$html_file': $!";
  16.  
  17. my $sheet = CSS::DOM::parse( scalar read_file $css_file );
  18.  
  19. while ( my $token = $html_parser->get_token ) {
  20.     my $type = $token->[0];
  21.     my $text = $type eq 'T' ? $token->[1] : $token->[-1];
  22.     if ( $type eq 'S' ) {
  23.         unless ( skip( $token->[1] ) ) {
  24.             $text = insert_computed_style($sheet, $token);
  25.         }
  26.     }
  27.     print $text;
  28. }
  29.  
  30. sub insert_computed_style {
  31.     my ($sheet, $token) = @_;
  32.     my ($tag, $attr, $attrseq) = @$token[1 .. 3];
  33.     my $doc = HTML::DOM->new;
  34.  
  35.     my $element = $doc->createElement($tag);
  36.  
  37.     for my $attr_name ( @$attrseq ) {
  38.         $element->setAttribute($attr_name, $attr->{$attr_name});
  39.     }
  40.  
  41.     my $style = CSS::DOM::compute_style(
  42.         element => $element, user_sheet => $sheet
  43.     );
  44.  
  45.     my @attrseq = (style => grep { lc $_ ne 'style' } @$attrseq );
  46.     $attr->{style} = $style->cssText;
  47.  
  48.     my $text .= join(" ",
  49.         "<$tag",
  50.         map{ qq/$_='$attr->{$_}'/ } @attrseq );
  51.     $text .= '>';
  52.  
  53.     return $text;
  54. }
  55.  
  56. sub skip {
  57.     my ($tag) = @_;
  58.     $tag = lc $tag;
  59.     return 1 if $tag =~ /^(?:h(?:ead|tml)|link|meta|script|title)$/;
  60. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top