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