62d26d762d0f27f78f12fbd7981a56b797f75a2d
[sheet.git] / writer.plp
1 <(common.inc.plp)><:
2
3 Html({
4         title => 'words cheat sheet admin',
5         version => '1.0',
6         nocache => 1,
7         raw => <<'EOT',
8 <style>
9 dl {
10         display: inline-grid;
11         grid: auto-flow / min-content repeat(10, auto);
12 }
13
14 form > ul {
15         display: table;
16         border-spacing: 0 2px;
17 }
18 form > ul > li {
19         display: table-row;
20 }
21 form > ul > li > * {
22         display: table-cell;
23         padding-right: .5em;
24 }
25 form > ul > li > label {
26         /* th */
27         text-align: right;
28 }
29 form > ul > li > label + * {
30         /* td */
31         width: 32em;
32 }
33
34 input,select {
35         box-sizing: border-box;
36         flex-grow: 1;
37 }
38 input:not([type=submit]) {
39         padding: .4rem;
40         font-family: monospace;
41 }
42 input[type=number] {
43         max-width: 7em;
44 }
45 select {
46         padding: .3rem .2rem; /* TODO: input */
47 }
48 #thumbpreview {
49         width: 300px;
50         align-self: start;
51 }
52
53 ul.popup {
54         display: flex;
55         flex-wrap: wrap;
56         align-items: end;
57         position: fixed;
58         left: 0;
59         top: 0;
60         margin: auto;
61         max-height: 90%;
62         max-width: 90%;
63         overflow: auto;
64         background: rgba(0, 0, 0, .8);
65         border: 1px solid #CCC;
66 }
67
68 h1 {
69         margin-bottom: 1ex;
70 }
71 .inline {
72         display: inline-flex;
73         align-items: baseline;
74         margin: 0 -1ex; /* inner gap */
75 }
76 .inline > * {
77         margin: 0 1ex;
78 }
79 .inline .inline {
80         display: flex;
81 }
82
83 #nav > ul,
84 #nav > ul strong,
85 #nav form {
86         margin: 1ex 0;
87         display: inline-block;
88 }
89 </style>
90
91 <script src="/writer.js"></script>
92 EOT
93 });
94
95 use List::Util qw( pairs pairkeys );
96
97 my $db = eval {
98         my @dbinfo = (
99                 'DBI:Pg:dbname=sheet;host=localhost', 'sheetadmin', 'fairuse',
100         ) or die "database not configured\n";
101         require DBIx::Simple;
102         DBIx::Simple->new(@dbinfo[0..2], {
103                 RaiseError => 1,
104                 pg_enable_utf8 => 1,
105         });
106 } or Abort('Database error', 501, $@);
107 $db->abstract->{array_datatypes}++;
108
109 my %lang = (
110         nl => ["\N{REGIONAL INDICATOR SYMBOL LETTER N}\N{REGIONAL INDICATOR SYMBOL LETTER L}", 'nederlands'],
111         en => ["\N{REGIONAL INDICATOR SYMBOL LETTER G}\N{REGIONAL INDICATOR SYMBOL LETTER B}", 'english'],
112         eo => ['<span style="color:green">★</span>', 'esperanto'],
113         ru => ["\N{REGIONAL INDICATOR SYMBOL LETTER R}\N{REGIONAL INDICATOR SYMBOL LETTER U}", 'русский'],
114 );
115 my @wordcols = pairkeys
116 my %wordcol = (
117         lang    => {-label => 'Language', -select => {
118                 map { $_ => "@{$lang{$_}}" } keys %lang
119         }},
120         cat     => [{-label => 'Category'}, 'ref'],
121         ref     => {-label => 'Reference'},
122         prio    => [
123                 {-label => 'Level', -select => [qw(
124                         essential basic common distinctive rare invisible
125                 )]},
126                 'cover', 'grade',
127         ],
128         cover   => {-label => 'Highlighted', type => 'checkbox'},
129         grade   => {-label => 'Order', type => 'number'},
130         form    => {-label => 'Title'},
131         alt     => {-label => 'Synonyms', -multiple => 1},
132         wptitle => {-label => 'Wikipedia'},
133         source  => {-label => 'Image'},
134         thumb   => {-label => 'Convert options', -multiple => 1},
135 );
136 my ($find) = map {{id => $_}} $fields{id} || $Request || ();
137
138 my $row;
139 if ($find) {
140         $row = $db->select(word => '*', $find)->hash
141                 or Abort("Word not found", 404);
142 }
143
144 if (exists $get{copy}) {
145         $row = {%{$row}{ qw(prio lang cat) }};
146 }
147 elsif ($ENV{REQUEST_METHOD} eq 'POST') {{
148         my $replace = $row;
149         $row = {%post{keys %wordcol}};
150         $row->{$_} = [grep {length} @{ $post{"\@$_"} }] for grep {
151                 ref $wordcol{$_} eq 'HASH' and $wordcol{$_}->{-multiple}
152         } keys %wordcol;
153         $_ = length ? $_ : undef for values %{$row};
154
155         if (!$row->{form}) {
156                 if ($row->{ref} ne 'delete') {
157                         Alert("Empty title",
158                                 "Confirm removal by setting <em>Reference</em> to <q>delete</q>."
159                         );
160                 }
161                 else {
162                         $db->delete(word => $find);
163                         Alert("Entry removed");
164                 }
165                 next;
166         }
167
168         eval {
169                 my %res = (returning => '*');
170                 my $query = $find ? $db->update(word => $row, $find, \%res) :
171                         $db->insert(word => $row, \%res);
172                 $row = $query->hash;
173         } or do {
174                 Alert("Entry could not be saved", $@);
175                 next;
176         };
177
178         eval {
179                 while (my ($lang, $val) = each %post) {
180                         my $field = $lang;
181                         $lang =~ s/^trans-// or next;
182                         $db->insert(word => {
183                                 ref   => $row->{id},
184                                 lang  => $lang,
185                                 form  => $val,
186                         });
187                         delete $fields{$field};
188                 }
189                 return 1;
190         } or Alert('Error creating translation entries', $@);
191
192         my $imgpath = Shiar_Sheet::FormRow::imagepath($row, 'source');
193         my $reimage = eval {
194                 ($row->{source} // '') ne ($replace->{source} // '') or return;
195                 # copy changed remote url to local file
196                 unlink $imgpath if -e $imgpath;
197                 my $download = $row->{source} or return 1;
198                 require LWP::UserAgent;
199                 my $ua = LWP::UserAgent->new;
200                 $ua->agent('/');
201                 my $status = $ua->mirror($download, $imgpath);
202                 $status->is_success
203                         or die "Download from <q>$download</q> failed: ".$status->status_line."\n";
204         };
205         !$@ or Alert(["Source image not found", $@]);
206
207         $reimage ||= $row->{thumb} ~~ $replace->{thumb};  # different convert
208         $reimage ||= $row->{cover} ~~ $replace->{cover};  # resize
209         $reimage++ if $fields{rethumb};  # force refresh
210
211         my $thumbpath = Shiar_Sheet::FormRow::imagepath($row => 'thumb');
212         if ($reimage) {
213                 if (-e $imgpath) {
214                         my $xyres = $row->{cover} ? '600x400' : '300x200';
215                         my @cmds = @{ $row->{thumb} // [] };
216                         if (my ($cmdarg) = grep { $cmds[$_] eq '-area' } 0 .. $#cmds) {
217                                 # replace option by permillage crop
218                                 my @dim = map { $_ / 1000 } split /\D/, $cmds[$cmdarg + 1];
219                                 splice @cmds, $cmdarg, 2, (
220                                         -set => 'option:distort:viewport' => sprintf(
221                                                 '%%[fx:w*%s]x%%[fx:h*%s]+%%[fx:w*%s]+%%[fx:h*%s]',
222                                                 ($dim[2] || 1) - $dim[0], # width  = x2 - x1
223                                                 ($dim[3] || 1) - $dim[1], # height = y2 - y1
224                                                 @dim[0, 1]                # offset = x1,y1
225                                         ),
226                                         -distort => SRT => 0, # noop transform to apply viewport
227                                 );
228                         }
229                         @cmds = (
230                                 'convert',
231                                 -delete => '1--1', -background => 'white',
232                                 -gravity => @cmds ? 'northwest' : 'center',
233                                 @cmds,
234                                 -resize => "$xyres^", -extent => $xyres,
235                                 '-strip', -quality => '60%', -interlace => 'plane',
236                                 $imgpath => $thumbpath
237                         );
238                         eval {
239                                 require IPC::Run;
240                                 my $output;
241                                 IPC::Run::run(\@cmds, '<' => \undef, '>&' => \$output)
242                                         or die $output ||
243                                                 ($? & 127 ? "signal $?" : "error code ".($? >> 8))."\n";
244                         } or Alert([
245                                 "Thumbnail image not generated",
246                                 "Failed to convert source image.",
247                         ], "@cmds\n$@");
248                 }
249                 else {
250                         unlink $thumbpath;
251                 }
252         }
253 }}
254 else {
255         $row->{prio} //= 1;
256         $row->{$_} = $get{$_} for keys %get;
257 }
258
259 my $title = $row->{id} ? "entry <small>#$row->{id}</small>" : 'new entry';
260
261 package Shiar_Sheet::FormRow {
262         use PLP::Functions 'EscapeHTML';
263
264         sub input {
265                 my ($row, $col, $attr) = @_;
266                 my $val = $row->{$col} // '';
267                 my $html = '';
268                 $html .= qq( $_="$attr->{$_}") for sort grep {!/^-/} keys %{$attr // {}};
269
270                 if (my $options = $attr->{-select}) {
271                         $options = { map {$_ => $options->[$_]} 0 .. $#{$options} }
272                                 if ref $options eq 'ARRAY';
273                         $options->{$val} //= "unknown ($val)";  # preserve current
274                         return (
275                                 sprintf('<select id="%s" name="%1$s">', $col),
276                                 (map { sprintf('<option value="%s"%s>%s</option>',
277                                         $_, $val eq $_ && ' selected', $options->{$_}
278                                 ) } sort keys %{$options}),
279                                 '</select>',
280                         );
281                 }
282                 elsif ($attr->{type} eq 'checkbox') {
283                         $html .= ' checked' if $val;
284                         return sprintf(
285                                 join('',
286                                         '<label>',
287                                         '<input name="%1$s" value="0" type="hidden" />',
288                                         '<input id="%s" name="%1$s" value="1"%s>',
289                                         ' %s</label>',
290                                 ), $col, $html, $attr->{-label}
291                         );
292                 }
293                 else {
294                         return (
295                                 (map {
296                                         sprintf('<label for="%s">%s</label>', $col, $_)
297                                 } $attr->{-label} // ()),
298                                 (map {
299                                         sprintf('<input name="%s" value="%s" />', $col, EscapeHTML($_))
300                                 } ref $val eq 'ARRAY' ? @{$val} : ()),
301                                 sprintf('<input id="%s" name="%1$s" value="%s"%s />',
302                                         $col, ref $val eq 'ARRAY' ? '' : EscapeHTML($val), $html
303                                 ),
304                                 (map {
305                                         sprintf '<img id="%spreview" src="/%s" alt="%s"%s />',
306                                                 $col, $_, $row->{form}, $col eq 'source' ? ' hidden' : '';
307                                 } grep { -e } $row->imagepath($col)),
308                         );
309                 }
310         }
311
312         sub imagepath {
313                 my ($row, $col) = @_;
314                 return "data/word/org/$row->{id}.jpg"   if $col eq 'source';
315                 return "data/word/en/$row->{form}.jpg"  if $col eq 'thumb';
316                 return;
317         }
318 }
319 bless $row, 'Shiar_Sheet::FormRow';
320 :>
321 <h1>Words <:= $title :></h1>
322
323 <div class="inline">
324
325 <form action="?" method="post">
326 <input id="id" name="id" value="<:= $row->{id} // '' :>" type="hidden" />
327 <ul>
328 <:
329 for my $col (@wordcols) {
330         my $info = $wordcol{$col} or next;
331         my ($attr, @span) = ref $info eq 'ARRAY' ? @{$info} : $info;
332         my $title = ref $attr ? delete $attr->{-label} : $attr;
333         printf '<li><label for="%s">%s</label><p>', $col, $title;
334                 printf '<span class=inline>';
335                 print $row->input($col => $attr);
336                 print $row->input($_ => delete $wordcol{$_}) for @span;
337                 print '</span>';
338         say '</p></li>';
339 }
340
341 if ($row->{id} and not $row->{ref}) {
342         printf '<li><label for="%s">%s</label><div><ul class="inline" id="%1$s">',
343                 'trans', 'Translations';
344         my @children = $db->select(word => '*', {ref => $row->{id}}, 'lang, id')->hashes;
345         while (my ($lang, $val) = each %fields) {
346                 $lang =~ s/^trans-// or next;
347                 push @children, { lang => $lang, form => $val };
348         }
349         for my $ref (@children) {
350                 printf(
351                         '<li><label for="%s" title="%3$s">%s </label>',
352                         "trans-$ref->{lang}", @{$lang{ $ref->{lang} }}, # flag, name
353                 );
354                 printf(
355                         $ref->{id} ? '<a id="%s" href="%s">%s</a></li>' :
356                         '<input id="%s" name="%1$s" value="%3$s" />',
357                         "trans-$ref->{lang}", "/writer/$ref->{id}", Entity($ref->{form}),
358                 );
359         }
360         say '</ul></div></li>';
361 }
362 :>
363 </ul>
364 <p>
365         <input type="submit" value="Save" />
366         <input type="submit" value="New" formaction="/writer?copy=cat" />
367 </p>
368 </form>
369
370 <:
371 if ($row->{id}) {
372 :>
373 <section id="nav">
374 <h2>Hierarchy</h2>
375
376 <:
377 say '<ul>';
378 my $parents = $db->select(word => '*', [{id => $row->{cat}}, {id => $row->{ref}}]);
379 while (my $ref = $parents->hash) {
380         printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
381 }
382 say "<li><strong>$row->{form}</strong></li>";
383 my $children = $db->select(word => '*', {cat => $row->{id}, ref => undef}, 'grade, id');
384 while (my $ref = $children->hash) {
385         printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
386 }
387 :>
388 <li><form action="/writer">
389         <input type="hidden" name="cat" value="<:= $row->{id} :>" />
390         <input type="hidden" name="lang" value="<:= $row->{lang} :>" />
391         <input type="submit" value="Add" />
392 </form></li>
393 </ul>
394 </section>
395 <:
396 }
397 :>
398 </div>