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