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