word edit: named form input options
[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, $attr) = @_;
212                 my $val = $row->{$col} // '';
213                 $val = '{'.join(',', map {s/,/\\,/gr} @{$val}).'}' if ref $val eq 'ARRAY';
214                 my $html = '';
215                 $html .= qq( $_="$attr->{$_}") for sort grep {!/^-/} keys %{$attr // {}};
216
217                 if (my $options = $attr->{-select}) {
218                         return (
219                                 sprintf('<select id="%s" name="%1$s">', $col),
220                                 (map { sprintf('<option value="%s"%s>%s</option>',
221                                         $_, $val eq $_ && ' selected', $options->[$_]
222                                 ) } 0 .. $#{$options}),
223                                 '</select>',
224                         );
225                 }
226                 elsif ($attr->{type} eq 'checkbox') {
227                         $html .= ' checked' if $val;
228                         return sprintf(
229                                 join('',
230                                         '<label>',
231                                         '<input name="%1$s" value="0" type="hidden" />',
232                                         '<input id="%s" name="%1$s" value="1"%s>',
233                                         ' %s</label>',
234                                 ), $col, $html, $attr->{-label}
235                         );
236                 }
237                 else {
238                         return (
239                                 (map {
240                                         sprintf('<label for="%s">%s</label>', $col, $_)
241                                 } $attr->{-label} // ()),
242                                 sprintf('<input id="%s" name="%1$s" value="%s"%s />',
243                                         $col, PLP::Functions::EscapeHTML($val), $html
244                                 ),
245                                 (map {
246                                         sprintf '<img id="%spreview" src="/%s" alt="%s"%s />',
247                                                 $col, $_, $row->{form}, $col eq 'source' ? ' hidden' : '';
248                                 } grep { -e } $row->imagepath($col)),
249                         );
250                 }
251         }
252
253         sub imagepath {
254                 my ($row, $col) = @_;
255                 return "data/word/org/$row->{id}.jpg"   if $col eq 'source';
256                 return "data/word/eng/$row->{form}.jpg" if $col eq 'thumb';
257                 return;
258         }
259 }
260 bless $row, 'Shiar_Sheet::FormRow';
261 :>
262 <h1>Words <:= $title :></h1>
263
264 <div class="inline">
265
266 <form action="?" method="post">
267 <input id="id" name="id" value="<:= $row->{id} // '' :>" type="hidden" />
268 <ul>
269 <:
270 for my $colinfo (pairs @wordcols) {
271         my ($col, $title) = @{$colinfo};
272         defined $title or next;
273         printf '<li><label for="%s">%s</label><p>', $col, $title;
274                 printf '<span class=inline>';
275         if ($col eq 'prio') {
276                 print $row->input($col => {-select => \@prioenum});
277                 print $row->input(cover => {type => 'checkbox', -label => 'Highlighted'});
278                 print $row->input(grade => {type => 'number', -label => 'Order'});
279         }
280         else {
281                 print $row->input($col);
282                 print $row->input(ref => {-label => 'Reference'}) if $col eq 'cat';
283         }
284                 print '</span>';
285         say '</p></li>';
286 }
287
288 if ($row->{id}) {
289         my $children = $db->select(word => '*', {ref => $row->{id}}, 'lang, id');
290         printf '<li><label>%s</label><div><ul class="inline">', 'Translations';
291         while (my $row = $children->hash) {
292                 printf '<li><label for="%s">%s</label> <a id="%1$s" href="%s">%s</a></li>',
293                         "trans-$row->{lang}", $langflag{$row->{lang}},
294                         "/writer/$row->{id}", Entity($row->{form});
295         }
296         say '</ul></div></li>';
297 }
298 :>
299 </ul>
300 <p>
301         <input type="submit" value="Save" />
302         <input type="submit" value="New" formaction="/writer?copy=cat" />
303 </p>
304 </form>
305
306 <:
307 if ($row->{id}) {
308 :>
309 <section id="nav">
310 <h2>Hierarchy</h2>
311
312 <:
313 say '<ul>';
314 my $parents = $db->select(word => '*', {id => $row->{cat}});
315 while (my $ref = $parents->hash) {
316         printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
317 }
318 say "<li><strong>$row->{form}</strong></li>";
319 my $children = $db->select(word => '*', {cat => $row->{id}}, 'grade, id');
320 while (my $ref = $children->hash) {
321         printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
322 }
323 :>
324 <li><form action="/writer">
325         <input type="hidden" name="cat" value="<:= $row->{id} :>" />
326         <input type="hidden" name="lang" value="<:= $row->{lang} :>" />
327         <input type="submit" value="Add" />
328 </form></li>
329 </ul>
330 </section>
331 <:
332 }
333 :>
334 </div>