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