move sdl.cgi into cgi-bin/
[sdlgit/SDL-Site.git] / cgi-bin / 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->_layout_html)
46   };
47 }
48
49 sub _layout_html {
50   my $self = shift;
51   my $file = $self->config->{pages_dir}.'/index.html';
52   if (-f $file) {
53     return do { local(@ARGV, $/) = ($file); <> }
54   } else {
55     return $self->_read_data
56   }
57 }
58
59 sub render_html {
60   my ($self, $data) = @_;
61   return $data if ref($data) eq 'ARRAY';
62   my ($zoom) = map {
63     if ($data->isa('SDL_Perl::WebSite::Page')) {
64       $_->with_selectors(
65         '#main' => {
66           -replace_content_raw => $data->html
67         }
68       );
69     } else {
70       die "WTF is ${data} supposed to be? A mallard?";
71     }
72   } ($self->layout_zoom);
73   $self->zoom_to_response($zoom);
74 }
75
76 sub zoom_to_response {
77   my ($self, $zoom) = @_;
78   open my $fh, '>', \my $out_str;
79   $zoom->render_to($fh);
80   return [
81     200,
82     [ 'Content-type' => 'text/html' ],
83     [ $out_str ]
84   ];
85 }
86
87
88 SDL_Perl::WebSite->run_if_script;
89 __DATA__
90 <html>
91   <body>
92     <div id="main"/>
93   </body>
94 </html>