<?php
/*********************************************************************

  CSSampler: A simple preview of css styles
  $Date: 2005/11/14 23:50:50 $
  $Author: nathan $ nate@natemurray.com

  A simple script to output a preview of all of the styles in a given
  css style sheet. Idea by Matt Pulver. 
  http://www.natemurray.com
  
  This may be used and modified free of charge, however please do
  not distribute it. 

**********************************************************************/

function parse_css( $css )
{
  $segs = preg_split("/\}/", $css); 
  for($i=0; $i<sizeof($segs)-1; ++$i) {
    $split = preg_split("/\{/", $segs[$i]); 
    $tree[cleanup($split[0])] = $split[1];
  }
  ksort($tree);
  return $tree;
}

function cleanup($s) {
  $s = preg_replace("/^\s+/", "", $s);        # strip leading whitespace
  $s = preg_replace("/\s+$/", "", $s);        # strip ending whitespace
  $s = preg_replace("/\/\*.*?\*\//", "", $s); # strip comments
  $s = preg_replace("/\W/",   "_",$s);        # replace nonword chars
  $s = preg_replace("/_+/",   "_", $s);       # remove multiple '_'
  $s = preg_replace("/^_+/",  "", $s);        # remove leading '_' 
  return $s;
}

function load($file) { return file_get_contents($file); }

function inline_style($tree)
{
  $r  = "<style type=\"text/css\">\n";
  $r .= "<!--\n";
  foreach ($tree as $key => $val) $r .= ".".$key ." {". $val ."}". "\n";
  $r .= "-->\n";
  $r .= "</style>";
  return $r;
}

function output_tree($tree)
{
  $text = empty($_GET['text']) ? "The Quick Brown Fox Jumps Over The Lazy Dog" 
                               : $_GET['text'];
  $r = "<table class='styled' bgcolor='white' >";
  $i = 0;
  foreach ($tree as $key => $val) {
    $r .= "<tr bgcolor=";
    $r .= $i % 2 ? "'white'>" : "'#edf3fe'>";
    $r .= "<td>$key:</td>";
    $r .= "<td><div class=\"$key\">$text</div></td>"; 
    $r .= "</tr>\n";
    ++$i;
  }
  $r .= "</table>";
  return $r;
}
?>

<html>
<head>
<title>CSSampler</title>
<?php

  $css_file = empty($_GET['css']) ? 'css.css' : $_GET['css'];
  $css = load($css_file);
  $tree = parse_css($css);
  $inline = inline_style($tree);

?>
<?=$inline?>
</head>
<body background=white>
<?=output_tree($tree);?>
</body>
</html>

