word edit: common function to format form input
[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 = "data/word/org/$row->{id}.jpg";
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 = "data/word/eng/$row->{form}.jpg";
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                         );
242                 }
243         }
244 }
245 bless $row, 'Shiar_Sheet::FormRow';
246 :>
247 <h1>Words <:= $title :></h1>
248
249 <div class="inline">
250
251 <form action="?" method="post">
252 <input id="id" name="id" value="<:= $row->{id} // '' :>" type="hidden" />
253 <ul>
254 <:
255 for my $colinfo (pairs @wordcols) {
256         my ($col, $title) = @{$colinfo};
257         defined $title or next;
258         printf '<li><label for="%s">%s</label><p>', $col, $title;
259                 printf '<span class=inline>';
260         if ($col eq 'prio') {
261                 print $row->input($col => \@prioenum);
262                 print $row->input(cover => 'checkbox', 'Highlighted');
263                 print $row->input(grade => {type => 'number'}, 'Order');
264         }
265         else {
266                 print $row->input($col);
267                 -e and printf '<img id="%spreview" src="/%s" alt="%s" />', $col, $_, $row->{form}
268                         for $col eq 'thumb'  ? "data/word/eng/$row->{form}.jpg" : ();
269                 print $row->input(ref => {}, 'Reference') if $col eq 'cat';
270         }
271                 print '</span>';
272         -e and printf('<img id="%spreview" src="/%s" alt="%s" hidden />',
273                 $col, $_, $row->{form}
274         ) for $col eq 'source' ? "data/word/org/$row->{id}.jpg" : ();
275         say '</p></li>';
276 }
277
278 if ($row->{id}) {
279         my $children = $db->select(word => '*', {ref => $row->{id}}, 'lang, id');
280         printf '<li><label>%s</label><div><ul class="inline">', 'Translations';
281         while (my $row = $children->hash) {
282                 printf '<li><label for="%s">%s</label> <a id="%1$s" href="%s">%s</a></li>',
283                         "trans-$row->{lang}", $langflag{$row->{lang}},
284                         "/writer/$row->{id}", Entity($row->{form});
285         }
286         say '</ul></div></li>';
287 }
288 :>
289 </ul>
290 <p>
291         <input type="submit" value="Save" />
292         <input type="submit" value="New" formaction="/writer?copy=cat" />
293 </p>
294 </form>
295
296 <:
297 if ($row->{id}) {
298 :>
299 <section id="nav">
300 <h2>Hierarchy</h2>
301
302 <:
303 say '<ul>';
304 my $parents = $db->select(word => '*', {id => $row->{cat}});
305 while (my $ref = $parents->hash) {
306         printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
307 }
308 say "<li><strong>$row->{form}</strong></li>";
309 my $children = $db->select(word => '*', {cat => $row->{id}}, 'grade, id');
310 while (my $ref = $children->hash) {
311         printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
312 }
313 :>
314 <li><form action="/writer">
315         <input type="hidden" name="cat" value="<:= $row->{id} :>" />
316         <input type="hidden" name="lang" value="<:= $row->{lang} :>" />
317         <input type="submit" value="Add" />
318 </form></li>
319 </ul>
320 </section>
321 <:
322 }
323 :>
324 </div>