76c00b1fecf0e38daf9edeba50ead06f09c675fd
[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                         @cmds = (
213                                 'convert',
214                                 -delete => '1--1', -background => 'white',
215                                 -gravity => @cmds ? 'northwest' : 'center',
216                                 @cmds,
217                                 -resize => "$xyres^", -extent => $xyres,
218                                 '-strip', -quality => '60%', -interlace => 'plane',
219                                 $imgpath => $thumbpath
220                         );
221                         eval {
222                                 require IPC::Run;
223                                 my $output;
224                                 IPC::Run::run(\@cmds, '<' => \undef, '>&' => \$output)
225                                         or die $output ||
226                                                 ($? & 127 ? "signal $?" : "error code ".($? >> 8))."\n";
227                         } or Alert([
228                                 "Thumbnail image not generated",
229                                 "Failed to convert source image.",
230                         ], "@cmds\n$@");
231                 }
232                 else {
233                         unlink $thumbpath;
234                 }
235         }
236 }}
237 else {
238         $row->{prio} //= 1;
239         $row->{$_} = $get{$_} for keys %get;
240 }
241
242 my $title = $row->{id} ? "entry <small>#$row->{id}</small>" : 'new entry';
243
244 package Shiar_Sheet::FormRow {
245         sub input {
246                 my ($row, $col, $attr) = @_;
247                 my $val = $row->{$col} // '';
248                 $val = '{'.join(',', map {s/,/\\,/gr} @{$val}).'}' if ref $val eq 'ARRAY';
249                 my $html = '';
250                 $html .= qq( $_="$attr->{$_}") for sort grep {!/^-/} keys %{$attr // {}};
251
252                 if (my $options = $attr->{-select}) {
253                         $options = { map {$_ => $options->[$_]} 0 .. $#{$options} }
254                                 if ref $options eq 'ARRAY';
255                         $options->{$val} //= "unknown ($val)";  # preserve current
256                         return (
257                                 sprintf('<select id="%s" name="%1$s">', $col),
258                                 (map { sprintf('<option value="%s"%s>%s</option>',
259                                         $_, $val eq $_ && ' selected', $options->{$_}
260                                 ) } sort keys %{$options}),
261                                 '</select>',
262                         );
263                 }
264                 elsif ($attr->{type} eq 'checkbox') {
265                         $html .= ' checked' if $val;
266                         return sprintf(
267                                 join('',
268                                         '<label>',
269                                         '<input name="%1$s" value="0" type="hidden" />',
270                                         '<input id="%s" name="%1$s" value="1"%s>',
271                                         ' %s</label>',
272                                 ), $col, $html, $attr->{-label}
273                         );
274                 }
275                 else {
276                         return (
277                                 (map {
278                                         sprintf('<label for="%s">%s</label>', $col, $_)
279                                 } $attr->{-label} // ()),
280                                 sprintf('<input id="%s" name="%1$s" value="%s"%s />',
281                                         $col, PLP::Functions::EscapeHTML($val), $html
282                                 ),
283                                 (map {
284                                         sprintf '<img id="%spreview" src="/%s" alt="%s"%s />',
285                                                 $col, $_, $row->{form}, $col eq 'source' ? ' hidden' : '';
286                                 } grep { -e } $row->imagepath($col)),
287                         );
288                 }
289         }
290
291         sub imagepath {
292                 my ($row, $col) = @_;
293                 return "data/word/org/$row->{id}.jpg"   if $col eq 'source';
294                 return "data/word/en/$row->{form}.jpg"  if $col eq 'thumb';
295                 return;
296         }
297 }
298 bless $row, 'Shiar_Sheet::FormRow';
299 :>
300 <h1>Words <:= $title :></h1>
301
302 <div class="inline">
303
304 <form action="?" method="post">
305 <input id="id" name="id" value="<:= $row->{id} // '' :>" type="hidden" />
306 <ul>
307 <:
308 for my $col (@wordcols) {
309         my $info = $wordcol{$col} or next;
310         my ($attr, @span) = ref $info eq 'ARRAY' ? @{$info} : $info;
311         my $title = ref $attr ? delete $attr->{-label} : $attr;
312         printf '<li><label for="%s">%s</label><p>', $col, $title;
313                 printf '<span class=inline>';
314                 print $row->input($col => $attr);
315                 print $row->input($_ => delete $wordcol{$_}) for @span;
316                 print '</span>';
317         say '</p></li>';
318 }
319
320 if ($row->{id} and not $row->{ref}) {
321         printf '<li><label for="%s">%s</label><div><ul class="inline" id="%1$s">',
322                 'trans', 'Translations';
323         my @children = $db->select(word => '*', {ref => $row->{id}}, 'lang, id')->hashes;
324         while (my ($lang, $val) = each %fields) {
325                 $lang =~ s/^trans-// or next;
326                 push @children, { lang => $lang, form => $val };
327         }
328         for my $ref (@children) {
329                 printf(
330                         '<li><label for="%s" title="%3$s">%s </label>',
331                         "trans-$ref->{lang}", @{$lang{ $ref->{lang} }}, # flag, name
332                 );
333                 printf(
334                         $ref->{id} ? '<a id="%s" href="%s">%s</a></li>' :
335                         '<input id="%s" name="%1$s" value="%3$s" />',
336                         "trans-$ref->{lang}", "/writer/$ref->{id}", Entity($ref->{form}),
337                 );
338         }
339         say '</ul></div></li>';
340 }
341 :>
342 </ul>
343 <p>
344         <input type="submit" value="Save" />
345         <input type="submit" value="New" formaction="/writer?copy=cat" />
346 </p>
347 </form>
348
349 <:
350 if ($row->{id}) {
351 :>
352 <section id="nav">
353 <h2>Hierarchy</h2>
354
355 <:
356 say '<ul>';
357 my $parents = $db->select(word => '*', [{id => $row->{cat}}, {id => $row->{ref}}]);
358 while (my $ref = $parents->hash) {
359         printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
360 }
361 say "<li><strong>$row->{form}</strong></li>";
362 my $children = $db->select(word => '*', {cat => $row->{id}, ref => undef}, 'grade, id');
363 while (my $ref = $children->hash) {
364         printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
365 }
366 :>
367 <li><form action="/writer">
368         <input type="hidden" name="cat" value="<:= $row->{id} :>" />
369         <input type="hidden" name="lang" value="<:= $row->{lang} :>" />
370         <input type="submit" value="Add" />
371 </form></li>
372 </ul>
373 </section>
374 <:
375 }
376 :>
377 </div>