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