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