34415b5f32421623a21b6279a5975ed2d469c16c
[sdlgit/SDL-Site.git] / sdl.cgi
1 #!/usr/bin/perl
2
3 use FindBin;
4 use lib $FindBin::RealBin.'/code';
5 use Web::Simple 'SDL_Perl::WebSite';
6
7 sub SDL_Perl::WebSite::Page::html { ${+shift} }
8
9 package SDL_Perl::WebSite;
10
11 use HTML::Zoom;
12
13 default_config(
14   pages_dir => $FindBin::RealBin.'/pages',
15 );
16
17 sub page {
18   my ($self, $page) = @_;
19   my $file = $self->config->{pages_dir}.'/'.$page.'.html-inc';
20   return () unless -e $file;
21   return bless(
22     \do { local (@ARGV, $/) = $file; <> },
23     'SDL_Perl::WebSite::Page'
24   )
25 }
26
27 dispatch [
28   sub (GET + /) { redispatch_to '/index.html' },
29   sub (GET + /**/) {
30     redispatch_to do { my $x = join('/','',$_[1],'index.html'); warn $x; $x };
31   },
32   sub (.html) {
33     filter_response { $self->render_html($_[1]) }
34   },
35   sub (GET + /**) {
36     $self->page($_[1])
37   },
38 ];
39
40 { my $DATA; sub _read_data { $DATA ||= do { local $/; <DATA>; } } }
41
42 sub layout_zoom {
43   my $self = shift;
44   $self->{layout_zoom} ||= do {
45     HTML::Zoom->from_string($self->_read_data)
46   };
47 }
48
49 sub render_html {
50   my ($self, $data) = @_;
51   return $data if ref($data) eq 'ARRAY';
52   my ($zoom) = map {
53     if ($data->isa('SDL_Perl::WebSite::Page')) {
54       $_->with_selectors(
55         '#main' => {
56           -replace_content_raw => $data->html
57         }
58       );
59     } else {
60       die "WTF is ${data} supposed to be? A mallard?";
61     }
62   } ($self->layout_zoom);
63   $self->zoom_to_response($zoom);
64 }
65
66 sub zoom_to_response {
67   my ($self, $zoom) = @_;
68   open my $fh, '>', \my $out_str;
69   $zoom->render_to($fh);
70   return [
71     200,
72     [ 'Content-type' => 'text/html' ],
73     [ $out_str ]
74   ];
75 }
76
77
78 SDL_Perl::WebSite->run_if_script;
79 __DATA__
80 <html>
81   <body>
82     <div id="main"/>
83   </body>
84 </html>