chiark / gitweb /
Add ref to docs on masthead
[ypp-sc-tools.main.git] / yarrg / web / lookup
1 %# This is part of the YARRG website.  YARRG is a tool and website
2 %# for assisting players of Yohoho Puzzle Pirates.
3 %#
4 %# Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
5 %# Copyright (C) 2009 Clare Boothby
6 %#
7 %#  YARRG's client code etc. is covered by the ordinary GNU GPL (v3 or later).
8 %#  The YARRG website is covered by the GNU Affero GPL v3 or later, which
9 %#   basically means that every installation of the website will let you
10 %#   download the source.
11 %#
12 %# This program is free software: you can redistribute it and/or modify
13 %# it under the terms of the GNU Affero General Public License as
14 %# published by the Free Software Foundation, either version 3 of the
15 %# License, or (at your option) any later version.
16 %#
17 %# This program is distributed in the hope that it will be useful,
18 %# but WITHOUT ANY WARRANTY; without even the implied warranty of
19 %# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 %# GNU Affero General Public License for more details.
21 %#
22 %# You should have received a copy of the GNU Affero General Public License
23 %# along with this program.  If not, see <http://www.gnu.org/licenses/>.
24 %#
25 %# Yohoho and Puzzle Pirates are probably trademarks of Three Rings and
26 %# are used without permission.  This program is not endorsed or
27 %# sponsored by Three Rings.
28 %#
29 %#
30 %# This Mason component generates the main `lookup' page, including
31 %# all the entry boxes etc. for every query.
32 %#
33 <%perl>
34 my %a;
35 my %ahtml;
36 my @vars;
37
38 # for output:
39 my @archipelagoes;
40 my @islandids;
41 my %islandid2;
42
43 #---------- "mode" argument parsing and mode menu at top of page ----------
44
45 # for debugging, invoke as
46 #  http://www.chiark.greenend.org.uk/ucgi/~clareb/mason/pirates/pirate-route?debug=1
47
48 @vars= ({       Name => 'Ocean',
49                 Before => 'Ocean: ',
50                 CmpCanon => sub { ucfirst lc $_[0] },
51                 Values => [ ocean_list() ]
52         }, {    Name => 'Dropdowns',
53                 Before => 'Interface: ',
54                 CmpCanon => sub { !!$_[0] },
55                 Values => [     [ 0, 'Type in names' ],
56                                 [ 4, 'Select from menus' ] ]
57         }, {    Name => 'Query',
58                 Before => 'Query: ',
59                 Values => [     [ 'route', 'Trades for route' ],
60                                 [ 'age', 'Data age' ] ]
61         });
62
63 foreach my $var (@vars) {
64         my $name= $var->{Name};
65         my $lname= lc $name;
66         $var->{Before}= '' unless exists $var->{Before};
67         $var->{CmpCanon}= sub { $_[0]; } unless exists $var->{CmpCanon};
68         foreach my $val (@{ $var->{Values} }) {
69                 next if ref $val;
70                 $val= [ $val, encode_entities($val) ];
71         }
72         if (exists $ARGS{$lname}) {
73                 $a{$name}= $ARGS{$lname};
74                 my @html= grep { $_->[0] eq $a{$name} } @{ $var->{Values} };
75                 $ahtml{$name}= @html==1 ? $html[0][1] : '???';
76         } else {
77                 $a{$name}= $var->{Values}[0][0];
78                 $ahtml{$name}= $var->{Values}[0][1];
79         }
80 }
81
82 </%perl>
83 <html><head><title><% ucfirst $ahtml{Query} %> - YARRG</title></head><body>
84
85 <a href="<% $m->current_comp()->name() |u %>">YARRG</a> -
86  Yet Another Revenue Research Gatherer
87 |
88 <a href="docs">documentation</a>
89 <p>
90 <%perl>
91
92 my %baseqf;
93 foreach my $var (@vars) {
94         my $lname= lc $var->{Name};
95         next unless exists $ARGS{$lname};
96         $baseqf{$lname}= $ARGS{$lname};
97 }
98
99 my %queryqf;
100 foreach my $var (keys %ARGS) {
101         next unless $var =~
102                 m/^(?:routestring|islandid\d|archipelago\d|debug)$/;
103         my $val= $ARGS{$var};
104         next if $val eq 'none';
105         $queryqf{$var}= $val;
106 }
107
108 my $quri= sub {
109         my $uri= URI->new('lookup');
110         $uri->query_form(@_);
111         $uri->path_query();
112 };
113
114 foreach my $var (@vars) {
115         my $name= $var->{Name};
116         my $lname= lc $var->{Name};
117         my $delim= $var->{Before};
118         my $canon= &{$var->{CmpCanon}}($a{$name});
119         my $cvalix= 0;
120         foreach my $valr (@{ $var->{Values} }) {
121                 print $delim;  $delim= "\n|\n";
122                 my ($value,$html) = @$valr;
123                 my $iscurrent= &{$var->{CmpCanon}}($value) eq $canon;
124                 my $after;
125                 if ($iscurrent) {
126                         print '<b>';
127                         $after= '</b>';
128                 } else {
129                         my %qf= (%baseqf,%queryqf);
130                         delete $qf{$lname};
131                         $qf{$lname}= $value if $cvalix;
132                         print '<a href="',$quri->(%qf),'">';
133                         $after= '</a>';
134                 }
135                 print $html, $after;
136                 $cvalix++;
137         }
138         print "<p>\n\n";
139 }
140
141 #---------- initial checks, startup, main entry form ----------
142
143 dbw_connect($a{Ocean});
144
145 </%perl>
146 <%args>
147 $debug => 0
148 $routestring => ''
149 </%args>
150
151 <hr>
152
153 %########### query `route' ##########
154 % if ($a{Query} eq 'route') {
155
156 <h1>Specify route</h1>
157 <form action="<% $quri->() %>" method="get">
158
159 %#---------- textbox, user enters route as string ----------
160 % if (!$a{Dropdowns}) {
161
162 Enter route (islands, or archipelagoes, separated by |s or commas;
163  abbreviations are OK):<br/>
164
165 <script type="text/javascript">
166 tr_uri= "routetextstring?format=json&type=text/xml"
167                 + "&ocean=<% uri_escape($a{Ocean}) %>";
168
169 tr_timeout=false;
170 tr_request=false;
171 tr_done='';
172 tr_needed='';
173 function tr_Later(){
174   window.clearTimeout(tr_timeout);
175   tr_timeout = window.setTimeout(tr_Needed, 500);
176 }
177 function tr_Needed(){
178   window.clearTimeout(tr_timeout);
179   tr_element= document.getElementById('routestring');
180   tr_needed= tr_element.value;
181   tr_Request();
182 }
183 function tr_Request(){
184   if (tr_request || tr_needed==tr_done) return;
185   tr_done= tr_needed;
186   tr_request= new XMLHttpRequest();
187   uri= tr_uri+'&string='+encodeURIComponent(tr_needed);
188   tr_request.open('GET', uri);
189   tr_request.onreadystatechange= tr_Ready;
190   tr_request.send(null);
191 }
192 function tr_Ready() {
193   if (tr_request.readyState != 4) return;
194   if (tr_request.status == 200) {
195     response= tr_request.responseText;
196     eval('results='+response);
197     toedit= document.getElementById('routeresults');
198     toedit.innerHTML= results.show;
199   }
200   tr_request= false;
201   tr_Request();
202 }
203 window.onload= tr_Needed;
204 </script>
205
206 <input type="text" id="routestring" name="routestring" size=80
207  value="<% $routestring |h %>"
208  onchange="tr_Needed();"
209  onkeyup="tr_Later();"><br>
210 <div id="routeresults">&nbsp;</div><br/>
211
212 % } else { #---------- dropdowns, user selects from menus ----------
213
214 <%perl>
215 my ($sth,$row);;
216 my @archlistdata;
217 my %islandlistdata;
218 $islandlistdata{'none'}= [ [ "none", "Select island..." ] ];
219
220 my $optionlistmap= sub {
221         my ($optlist, $selected) = @_;
222         my $out='';
223         foreach my $entry (@$optlist) {
224                 $out.= sprintf('<option value="%s" %s>%s</option>',
225                         encode_entities($entry->[0]),
226                         defined $selected && $entry->[0] eq $selected
227                                 ? 'selected' : '',
228                         encode_entities($entry->[1]));
229         }
230         return $out;
231 };
232
233 my $dbh= dbw_connect($a{Ocean});
234
235 $sth= $dbh->prepare("SELECT DISTINCT archipelago FROM islands
236                             ORDER BY archipelago;");
237 $sth->execute();
238
239 while ($row=$sth->fetchrow_arrayref) {
240         my ($arch)= @$row;
241         push @archlistdata, [ $arch, $arch ];
242         $islandlistdata{$arch}= [ [ "none", "Whole arch" ] ];
243 }
244
245 $sth= $dbh->prepare("SELECT islandid,islandname,archipelago
246                             FROM islands
247                             ORDER BY islandname;");
248 $sth->execute();
249
250 while ($row=$sth->fetchrow_arrayref) {
251         my $arch= $row->[2];
252         push @{ $islandlistdata{'none'} }, [ @$row ];
253         push @{ $islandlistdata{$arch} }, [ @$row ];
254         $islandid2{$row->[0]}= { Name => $row->[1], Arch => $arch };
255 }
256
257 my %resetislandlistdata;
258 foreach my $arch (keys %islandlistdata) {
259         $resetislandlistdata{$arch}=
260                 $optionlistmap->($islandlistdata{$arch}, '');
261 }
262
263 </%perl>
264
265 <input type=hidden name=dropdowns value="<% $a{Dropdowns} |h %>">
266
267 <script type="text/javascript">
268 ms_lists= <% to_json(\%resetislandlistdata) %>;
269 function ms_Setarch(dd) {
270   debug('ms_SetArch '+dd+' arch='+arch);
271   var arch= document.getElementsByName('archipelago'+dd).item(0).value;
272   var got= ms_lists[arch];
273   if (got == undefined) return; // unknown arch ?  hrm
274   debug('ms_SetArch '+dd+' arch='+arch+' got ok');
275   var select= document.getElementsByName('islandid'+dd).item(0);
276   select.innerHTML= got;
277   debug('ms_SetArch '+dd+' arch='+arch+' innerHTML set');
278 }
279 </script>
280
281 <table style="table-layout:fixed; width:90%;">
282
283 <tr>
284 %       for my $dd (0..$a{Dropdowns}-1) {
285 <td>
286 <select name="archipelago<% $dd %>" onchange="ms_Setarch(<% $dd %>)">
287 <option value="none">Whole ocean</option>
288 <% $optionlistmap->(\@archlistdata, $ARGS{"archipelago$dd"}) %></select></td>
289 %       }
290 </tr>
291
292 <tr>
293 %       for my $dd (0..$a{Dropdowns}-1) {
294 %               my $arch= $ARGS{"archipelago$dd"};
295 %               $arch= 'none' if !defined $arch;
296 <td>
297 <select name="islandid<% $dd %>">
298 <% $optionlistmap->($islandlistdata{$arch}, $ARGS{"islandid$dd"}) %>
299 </select></td>
300 %       }
301 </tr>
302
303 </table>
304
305 % } #---------- end of dropdowns, now common middle of page code ----------
306
307 <input type=submit name=submit value="Go">
308 </form>
309
310 <%perl>
311 #========== result computations ==========
312
313 my $results_head;
314 $results_head= sub {
315         print "<h1>Results</h1>\n";
316         $results_head= sub { };
317 };
318
319 #---------- result computation - textstring ----------
320 if (!$a{Dropdowns}) {
321   if (length $routestring) {
322         $results_head->();
323         my $rsr= $m->comp('routetextstring',
324                 ocean => $a{Ocean},
325                 string => $routestring,
326                 format => 'return'
327         );
328         if (length $rsr->{Error}) {
329                 print encode_entities($rsr->{Error});
330         } else {
331                 foreach my $entry (@{ $rsr->{Results} }) {
332                         push @archipelagoes,
333                                 defined $entry->[1] ? undef : $entry->[0];
334                         push @islandids, $entry->[1];
335                 } 
336         }
337   }
338
339 } else { #---------- results - dropdowns ----------
340
341 my $argorundef= sub {
342         my ($dd,$base) = @_;
343         my $thing= $ARGS{"${base}${dd}"};
344         $thing= undef if defined $thing and $thing eq 'none';
345         return $thing;
346 };
347
348 for my $dd (0..$a{Dropdowns}-1) {
349         my $arch= $argorundef->($dd,'archipelago');
350         my $island= $argorundef->($dd,'islandid');
351         next unless defined $arch or defined $island;
352         if (defined $island and defined $arch) {
353                 my $ii= $islandid2{$island};
354                 my $iarch= $ii->{Arch};
355                 if ($iarch ne $arch) {
356                         $results_head->();
357 </%perl>
358  Specified archipelago <% $arch %> but
359  island <% $ii->{Name} %>
360  which is in <% $iarch %>; using the island.<br>
361 <%perl>
362                 }
363                 $arch= undef;
364         }
365         push @archipelagoes, $arch;
366         push @islandids, $island;
367 }
368
369 }#---------- result processing, common stuff
370 </%perl>
371
372 % if (@islandids) {
373 %       $results_head->();
374
375 <& routetrade, islandids => \@islandids, archipelagoes => \@archipelagoes &>
376
377 % }
378
379 % } elsif ($a{Query} eq 'age') {
380 % ########### query `age' ##########
381
382 <h1>Market data age</h1>
383 <& dataage, %baseqf, %queryqf &>
384
385 % } ########## end of `age' query ##########
386
387 %#---------- debugging and epilogue ----------
388
389 % if ($debug) {
390 <p>
391 <pre id="debug_log">
392 Debug log:
393 </pre>
394 % }
395
396 <script type="text/javascript">
397 function debug (m) {
398 % if ($debug) {
399   var node= document.getElementById('debug_log');
400   node.innerHTML += "\n" + m + "\n";
401 % }
402 }
403 </script>
404
405 <& footer &>
406
407 <%init>
408 use CommodsWeb;
409 use HTML::Entities;
410 use URI::Escape;
411 use JSON;
412
413 </%init>