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