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