word edit: null priority to inherit from parent
[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         if (defined $post{username}) {
120                 $cookie{login} = EncodeURI(join ':', @post{qw( username pass )});
121         }
122         elsif (exists $fields{logout}) {
123                 require CGI::Cookie;
124                 if (AddCookie(CGI::Cookie->new(
125                         -name    => 'login',
126                         -value   => '',
127                         -path    => '/writer',
128                         -expires => 'now',
129                 )->as_string)) {
130                         delete $cookie{login};
131                         die "Logged out as requested\n";
132                 }
133                 Alert("Failed to log out", "Login cookie could not be removed.");
134         }
135
136         my $cookiedata = $cookie{login} or return;
137         my ($name, $key) = split /[:\v]/, DecodeURI($cookiedata);
138         my %rowmatch = (username => $name, pass => $key);
139         my $found = $db->select(login => '*', \%rowmatch)->hash
140                 or die "Invalid user or password\n";
141
142         eval {
143                 require CGI::Cookie;
144                 my $httpcookie = CGI::Cookie->new(
145                         -name    => 'login',
146                         -value   => join(':', @{$found}{qw( username pass )}),
147                         -path    => '/writer',
148                 ) or die "prepared object is empty\n";
149                 AddCookie($httpcookie->as_string);
150         } or Abort(["Unable to create login cookie", $@], 403);
151
152         return $found;
153 } or do {
154         say '<h1>Login to edit words</h1>';
155         Alert('Access denied', $@) if $@;
156         say '<form action="?" method="post" class="inline"><ul>';
157         my $loginform = bless {%post}, 'Shiar_Sheet::FormRow';
158         say '<li>', $loginform->input(@{$_}), '</li>' for pairs (
159                 username => {-label => 'User name'},
160                 pass     => {-label => 'Password', type => 'password'},
161         );
162         say '<li><input type="submit" value="Login" /></li>';
163         say '</ul></form>';
164         exit;
165 };
166
167 my %lang = (
168         nl => ["\N{REGIONAL INDICATOR SYMBOL LETTER N}\N{REGIONAL INDICATOR SYMBOL LETTER L}", 'nederlands'],
169         en => ["\N{REGIONAL INDICATOR SYMBOL LETTER G}\N{REGIONAL INDICATOR SYMBOL LETTER B}", 'english'],
170         eo => ['<span style="color:green">★</span>', 'esperanto'],
171         ru => ["\N{REGIONAL INDICATOR SYMBOL LETTER R}\N{REGIONAL INDICATOR SYMBOL LETTER U}", 'русский'],
172 );
173 my @wordcols = pairkeys
174 my %wordcol = (
175         lang    => {-label => 'Language', -select => {
176                 map { $_ => "@{$lang{$_}}" } keys %lang
177         }},
178         cat     => [{-label => 'Category'}, 'ref'],
179         ref     => {-label => 'Reference'},
180         prio    => [
181                 {-label => 'Level', -select => sub {
182                         my ($row) = @_;
183                         my @enum = qw[ essential basic common distinctive optional invisible ];
184                         return {
185                                 ('' => 'parent') x (defined $row->{ref}),
186                                 map { $_ => $enum[$_] } 0 .. $#enum
187                         };
188                 }},
189                 'cover', 'grade',
190         ],
191         cover   => {-label => 'Highlighted', type => 'checkbox'},
192         grade   => {-label => 'Order', type => 'number'},
193         form    => {-label => 'Title'},
194         alt     => {-label => 'Synonyms', -multiple => 1},
195         wptitle => {-label => 'Wikipedia'},
196         source  => {-label => 'Image'},
197         thumb   => {-label => 'Convert options', -multiple => 1},
198 );
199 my ($find) = map {{id => $_}} $fields{id} || $Request || ();
200
201 my $row;
202 if ($find) {
203         $row = $db->select(word => '*', $find)->hash
204                 or Abort("Word not found", 404);
205 }
206
207 if (exists $get{copy}) {
208         $row = {%{$row}{ qw(prio lang cat) }};
209 }
210 elsif (defined $post{form}) {{
211         sub parseinput {
212                 return if not length $_[0];
213                 require Encode;
214                 return Encode::decode_utf8($_[0]);
215         }
216
217         my $replace = $row;
218         $row = {map { $_ =>
219                 ref $wordcol{$_} eq 'HASH' && $wordcol{$_}->{-multiple} ?
220                         [ map { parseinput($_) } $post{'@'.$_}->@* ] :
221                 scalar parseinput($post{$_})
222         } keys %wordcol};
223
224         if (!$row->{form}) {
225                 if ($row->{ref} ne 'delete') {
226                         Alert("Empty title",
227                                 "Confirm removal by setting <em>Reference</em> to <q>delete</q>."
228                         );
229                 }
230                 else {
231                         $db->delete(word => $find);
232                         Alert("Entry removed");
233                 }
234                 next;
235         }
236
237         eval {
238                 my %res = (returning => '*');
239                 $row->{creator} = $user->{id} unless $find;
240                 $row->{updated} = ['now()'];
241                 my $query = $find ? $db->update(word => $row, $find, \%res) :
242                         $db->insert(word => $row, \%res);
243                 $row = $query->hash;
244         } or do {
245                 Alert("Entry could not be saved", $@);
246                 next;
247         };
248
249         eval {
250                 while (my ($lang, $val) = each %post) {
251                         my $field = $lang;
252                         $lang =~ s/^trans-// or next;
253                         $val = parseinput($val) or next;
254                         my %subrow = (
255                                 ref   => $row->{id},
256                                 lang  => $lang,
257                                 form  => $val,
258                                 prio  => undef,
259                         );
260                         $subrow{wptitle} = $1 if $subrow{form} =~ s/\h*\[(.*)\]$//; # [Link] shorthand
261                         $db->insert(word => \%subrow);
262                         delete $fields{$field};
263                 }
264                 return 1;
265         } or Alert('Error creating translation entries', $@);
266
267         my $imgpath = Shiar_Sheet::FormRow::imagepath($row, 'source');
268         my $reimage = eval {
269                 ($row->{source} // '') ne ($replace->{source} // '') or return;
270                 # copy changed remote url to local file
271                 unlink $imgpath if -e $imgpath;
272                 my $download = $row->{source} or return 1;
273                 require LWP::UserAgent;
274                 my $ua = LWP::UserAgent->new;
275                 $ua->agent('/');
276                 my $status = $ua->mirror($download, $imgpath);
277                 $status->is_success
278                         or die "Download from <q>$download</q> failed: ".$status->status_line."\n";
279         };
280         !$@ or Alert(["Source image not found", $@]);
281
282         $reimage ||= $row->{thumb} ~~ $replace->{thumb};  # different convert
283         $reimage ||= $row->{cover} ~~ $replace->{cover};  # resize
284         $reimage++ if $fields{rethumb};  # force refresh
285
286         my $thumbpath = Shiar_Sheet::FormRow::imagepath($row => 'thumb');
287         if ($reimage) {
288                 if (-e $imgpath) {
289                         my $xyres = $row->{cover} ? '600x400' : '300x200';
290                         my @cmds = @{ $row->{thumb} // [] };
291                         if (my ($cmdarg) = grep { $cmds[$_] eq '-area' } 0 .. $#cmds) {
292                                 # replace option by permillage crop
293                                 my @dim = map { $_ / 1000 } split /\D/, $cmds[$cmdarg + 1];
294                                 splice @cmds, $cmdarg, 2, (
295                                         -set => 'option:distort:viewport' => sprintf(
296                                                 '%%[fx:w*%s]x%%[fx:h*%s]+%%[fx:w*%s]+%%[fx:h*%s]',
297                                                 ($dim[2] || 1) - $dim[0], # width  = x2 - x1
298                                                 ($dim[3] || 1) - $dim[1], # height = y2 - y1
299                                                 @dim[0, 1]                # offset = x1,y1
300                                         ),
301                                         -distort => SRT => 0, # noop transform to apply viewport
302                                 );
303                         }
304                         @cmds = (
305                                 'convert',
306                                 $imgpath,
307                                 -delete => '1--1', -background => 'white',
308                                 -gravity => @cmds ? 'northwest' : 'center',
309                                 @cmds,
310                                 -resize => "$xyres^", -extent => $xyres,
311                                 '-strip', -quality => '60%', -interlace => 'plane',
312                                 $thumbpath
313                         );
314                         eval {
315                                 require IPC::Run;
316                                 my $output;
317                                 IPC::Run::run(\@cmds, '<' => \undef, '>&' => \$output)
318                                         or die $output ||
319                                                 ($? & 127 ? "signal $?" : "error code ".($? >> 8))."\n";
320                         } or Alert([
321                                 "Thumbnail image not generated",
322                                 "Failed to convert source image.",
323                         ], "@cmds\n$@");
324                 }
325                 else {
326                         unlink $thumbpath;
327                 }
328         }
329 }}
330 else {
331         $row->{lang} //= $user->{editlang}->[0];
332         $row->{$_} = $get{$_} for keys %get;
333         $row->{prio} = defined $row->{ref} ? undef : 1 unless exists $row->{prio};
334 }
335
336 my $title = $row->{id} ? "entry <small>#$row->{id}</small>" : 'new entry';
337
338 package Shiar_Sheet::FormRow {
339         use PLP::Functions 'EscapeHTML';
340
341         sub input {
342                 my ($row, $col, $attr) = @_;
343                 my $val = $row->{$col} // '';
344                 my $html = '';
345                 $html .= qq( $_="$attr->{$_}") for sort grep {!/^-/} keys %{$attr // {}};
346
347                 if (my $options = $attr->{-select}) {
348                         $options = $options->(@_) if ref $options eq 'CODE';
349                         $options->{$val} //= "unknown ($val)";  # preserve current
350                         return (
351                                 sprintf('<select id="%s" name="%1$s">', $col),
352                                 (map { sprintf('<option value="%s"%s>%s</option>',
353                                         $_, $val eq $_ && ' selected', $options->{$_}
354                                 ) } sort keys %{$options}),
355                                 '</select>',
356                         );
357                 }
358                 elsif ($attr->{type} eq 'checkbox') {
359                         $html .= ' checked' if $val;
360                         return sprintf(
361                                 join('',
362                                         '<label>',
363                                         '<input name="%1$s" value="0" type="hidden" />',
364                                         '<input id="%s" name="%1$s" value="1"%s>',
365                                         ' %s</label>',
366                                 ), $col, $html, $attr->{-label}
367                         );
368                 }
369                 else {
370                         my $multiple = ref $val eq 'ARRAY' || $attr->{-multiple};
371                         return (
372                                 (map {
373                                         sprintf('<label for="%s">%s</label>', $col, $_)
374                                 } $attr->{-label} // ()),
375                                 $multiple ? '<span class="inline multiinput">' : (),
376                                 (map {
377                                         sprintf('<input name="%s" value="%s" />', $col, EscapeHTML($_))
378                                 } ref $val eq 'ARRAY' ? @{$val} : ()),
379                                 sprintf('<input id="%s" name="%1$s" value="%s"%s />',
380                                         $col, $multiple ? '' : EscapeHTML($val), $html
381                                 ),
382                                 $multiple ? '</span>' : (),
383                                 (map {
384                                         sprintf '<img id="%spreview" src="/%s" alt="%s"%s />',
385                                                 $col, $_, $row->{form}, $col eq 'source' ? ' hidden' : '';
386                                 } grep { -e } $row->imagepath($col)),
387                         );
388                 }
389         }
390
391         sub imagepath {
392                 my ($row, $col) = @_;
393                 return "data/word/org/$row->{id}.jpg"   if $col eq 'source';
394                 return "data/word/en/$row->{form}.jpg"  if $col eq 'thumb';
395                 return;
396         }
397 }
398 bless $row, 'Shiar_Sheet::FormRow';
399 :>
400 <h1>Words <:= $title :></h1>
401
402 <div class="inline">
403
404 <form action="?" method="post">
405 <input id="id" name="id" value="<:= $row->{id} // '' :>" type="hidden" />
406 <ul>
407 <:
408 for my $col (@wordcols) {
409         my $info = $wordcol{$col} or next;
410         my ($attr, @span) = ref $info eq 'ARRAY' ? @{$info} : $info;
411         my $title = ref $attr ? delete $attr->{-label} : $attr;
412         printf '<li><label for="%s">%s</label><p>', $col, $title;
413                 printf '<span class=inline>';
414                 print $row->input($col => $attr);
415                 print $row->input($_ => delete $wordcol{$_}) for @span;
416                 print '</span>';
417         say '</p></li>';
418 }
419
420 if (not $row->{ref}) {
421         printf '<li><label for="%s">%s</label><div><ul class="inline" id="%1$s">',
422                 'trans', 'Translations';
423         my @children = !$row->{id} ? () :
424                 $db->select(word => '*', {ref => $row->{id}}, 'lang, id')->hashes;
425         while (my ($lang, $val) = each %fields) {
426                 $lang =~ s/^trans-// or next;
427                 push @children, { lang => $lang, form => $val };
428         }
429         my %existing = map { $_->{lang} => 1 } $row, @children;
430         $existing{$_} or push @children, { lang => $_ } for @{$user->{editlang}};
431
432         for my $ref (@children) {
433                 printf(
434                         '<li><label for="%s" title="%3$s">%s </label>',
435                         "trans-$ref->{lang}", @{$lang{ $ref->{lang} }}, # flag, name
436                 );
437                 printf(
438                         $ref->{id} ? '<a id="%s" href="%s">%s</a></li>' :
439                         '<input id="%s" name="%1$s" value="%3$s" />',
440                         "trans-$ref->{lang}", "/writer/$ref->{id}", Entity($ref->{form} // ''),
441                 );
442         }
443         say '</ul></div></li>';
444 }
445 :>
446 </ul>
447 <p>
448         <input type="submit" value="Save" />
449         <input type="submit" value="New" formaction="/writer?copy=cat" />
450 </p>
451 </form>
452
453 <:
454 if ($row->{id}) {
455 :>
456 <section id="nav">
457 <h2>Hierarchy</h2>
458
459 <:
460 say '<ul>';
461 my $parents = $db->select(word => '*', [{id => $row->{cat}}, {id => $row->{ref}}]);
462 while (my $ref = $parents->hash) {
463         printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
464 }
465 say "<li><strong>$row->{form}</strong></li>";
466 my $children = $db->select(word => '*', {cat => $row->{id}, ref => undef}, 'grade, id');
467 while (my $ref = $children->hash) {
468         printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
469 }
470 :>
471 <li><form action="/writer">
472         <input type="hidden" name="cat" value="<:= $row->{id} :>" />
473         <input type="hidden" name="lang" value="<:= $row->{lang} :>" />
474         <input type="submit" value="Add" />
475 </form></li>
476 </ul>
477 </section>
478 <:
479 }
480 :>
481 </div>