word edit: cover option changes thumbnail
[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:not([type]) {
35         box-sizing: border-box;
36         width: 100%;
37         padding: .4rem;
38         font-family: monospace;
39 }
40 select {
41         padding: .3rem .2rem; /* TODO: input */
42 }
43 form > ul li img {
44         max-width: 300px;
45 }
46
47 ul.popup {
48         display: flex;
49         flex-wrap: wrap;
50         align-items: end;
51         position: fixed;
52         left: 0;
53         top: 0;
54         margin: auto;
55         max-height: 90%;
56         max-width: 90%;
57         overflow: auto;
58         background: rgba(0, 0, 0, .8);
59         border: 1px solid #CCC;
60 }
61
62 h1 {
63         margin-bottom: 1ex;
64 }
65 .inline {
66         display: inline-flex;
67         align-items: start;
68         margin: 0 -1ex; /* inner gap */
69 }
70 .inline > * {
71         margin: 0 1ex;
72 }
73 .inline .inline {
74         display: flex;
75 }
76
77 #nav {
78         -margin-left: 1em; /* flex gap */
79 }
80 #nav > ul,
81 #nav > ul strong,
82 #nav form {
83         margin: 1ex 0;
84         display: inline-block;
85 }
86 </style>
87
88 <script>
89 document.addEventListener('DOMContentLoaded', () => {
90         var wpinput = document.getElementById('wptitle');
91         var wpbutton = wpinput.parentNode.appendChild(document.createElement('button'));
92         wpbutton.type = 'button';
93         wpbutton.append('Copy');
94         wpbutton.onclick = () => {
95                 let wptitle = wpinput.value || document.getElementById('form').value;
96                 let wplang = document.getElementById('lang').value.substr(0, 2); // crude iso-639-3→2
97                 let wpapi = `https://${wplang}.wikipedia.org/w/api.php`;
98                 let wppage = wpapi+'?action=parse&format=json&origin=*&prop=text&page='+wptitle;
99                 fetch(wppage).then(res => res.json()).then(json => {
100                         if (json.error) throw `error returned: ${json.error.info}`;
101                         wpinput.value = json.parse.title;
102                         let imginput = document.getElementById('source');
103                         if (imginput.value) return;
104                         let wpimages = json.parse.text['*'].match(/<img\s[^>]+>/g);
105                         let wpselect = wpinput.parentNode.appendChild(document.createElement('ul'));
106                         wpselect.className = 'popup';
107                         wpimages.forEach(img => {
108                                 let selectitem = wpselect.appendChild(document.createElement('li'));
109                                 selectitem.insertAdjacentHTML('beforeend', img);
110                                 selectitem.onclick = e => {
111                                         let imgsrc = e.target.src
112                                                 .replace(/^(?=\/\/)/, 'https:')
113                                                 .replace(/\/thumb(\/.+)\/[^\/]+$/, '$1');
114                                         imginput.value = imgsrc;
115                                         wpselect.remove();
116                                         return false;
117                                 };
118                         });
119                 }).catch(error => alert(error));
120                 return false;
121         };
122 });
123 </script>
124 EOT
125 });
126
127 use List::Util qw( pairs pairkeys );
128
129 my $db = eval {
130         my @dbinfo = (
131                 'DBI:Pg:dbname=sheet;host=localhost', 'sheetadmin', 'fairuse',
132         ) or die "database not configured\n";
133         require DBIx::Simple;
134         DBIx::Simple->new(@dbinfo[0..2], {
135                 RaiseError => 1,
136                 pg_enable_utf8 => 1,
137         });
138 } or Abort('Database error', 501, $@);
139
140 my @wordcols = (
141         lang    => 'Language',
142         cat     => 'Category',
143         form    => 'Translation',
144         alt     => 'Synonyms',
145         wptitle => 'Wikipedia',
146         source  => 'Image URL',
147         thumb   => 'Convert options',
148         prio    => 'Level',
149         cover   => undef, # included with prio
150         ref     => 'Reference',
151 );
152 my @prioenum = qw( essential basic common distinctive rare invisible );
153 my ($find) = map {{id => $_}} $fields{id} || $Request || ();
154
155 my $row;
156 if ($find) {
157         $row = $db->select(word => '*', $find)->hash
158                 or Abort("Word not found", 404);
159 }
160
161 if (exists $get{copy}) {
162         $row = {%{$row}{ qw(prio lang cat) }};
163 }
164 elsif ($ENV{REQUEST_METHOD} eq 'POST') {{
165         my $replace = $row;
166         $row = {%post{ pairkeys @wordcols }};
167         $_ = length ? $_ : undef for values %{$row};
168
169         eval {
170                 my %res = (returning => '*');
171                 my $query = $find ? $db->update(word => $row, $find, \%res) :
172                         $db->insert(word => $row, \%res);
173                 $row = $query->hash;
174         } or do {
175                 Alert("Entry could not be saved", $@);
176                 next;
177         };
178
179         my $imgpath = "data/word/org/$row->{id}.jpg";
180         my $reimage = eval {
181                 ($row->{source} // '') ne ($replace->{source} // '') or return;
182                 # copy changed remote url to local file
183                 unlink $imgpath if -e $imgpath;
184                 my $download = $row->{source} or return 1;
185                 require LWP::UserAgent;
186                 my $ua = LWP::UserAgent->new;
187                 $ua->agent('/');
188                 my $status = $ua->mirror($download, $imgpath);
189                 $status->is_success
190                         or die "Download from <q>$download</q> failed: ".$status->status_line."\n";
191         };
192         !$@ or Alert(["Source image not found", $@]);
193
194         $reimage ||= $row->{thumb} ~~ $replace->{thumb};  # different convert
195         $reimage ||= $row->{cover} ~~ $replace->{cover};  # resize
196         $reimage++ if $fields{rethumb};  # force refresh
197
198         my $thumbpath = "data/word/eng/$row->{form}.jpg";
199         if ($reimage) {
200                 if (-e $imgpath) {
201                         my $xyres = $row->{cover} ? '600x400' : '300x200';
202                         my @cmds = @{ $row->{thumb} // [] };
203                         @cmds = (
204                                 'convert',
205                                 -delete => '1--1', -background => 'white',
206                                 -gravity => @cmds ? 'northwest' : 'center',
207                                 @cmds,
208                                 -resize => "$xyres^", -extent => $xyres,
209                                 '-strip', -quality => '60%', -interlace => 'plane',
210                                 $imgpath => $thumbpath
211                         );
212                         eval {
213                                 require IPC::Run;
214                                 my $output;
215                                 IPC::Run::run(\@cmds, '<' => \undef, '>&' => \$output)
216                                         or die $output ||
217                                                 ($? & 127 ? "signal $?" : "error code ".($? >> 8))."\n";
218                         } or Alert([
219                                 "Thumbnail image not generated",
220                                 "Failed to convert source image.",
221                         ], "@cmds\n$@");
222                 }
223                 else {
224                         unlink $thumbpath;
225                 }
226         }
227 }}
228 else {
229         $row->{prio} //= 1;
230         $row->{$_} = $get{$_} for keys %get;
231 }
232
233 my $title = $row->{id} ? "entry <small>#$row->{id}</small>" : 'new entry';
234 :>
235 <h1>Words <:= $title :></h1>
236
237 <div class="inline">
238
239 <form action="?" method="post">
240 <input id="id" name="id" value="<:= $row->{id} // '' :>" type="hidden" />
241 <ul>
242 <:
243
244 for my $colinfo (pairs @wordcols) {
245         my ($col, $title) = @{$colinfo};
246         defined $title or next;
247         my $val = $row->{$col} // '';
248         $val = '{'.join(',', map {s/,/\\,/gr} @{$val}).'}' if ref $val eq 'ARRAY';
249         printf '<li><label for="%s">%s</label><p>', $col, $title;
250                 printf '<span class=inline>';
251         if ($col eq 'prio') {
252                 printf '<select id="%s" name="%1$s">', $col;
253                 printf('<option value="%s"%s>%s</option>',
254                         $_, $row->{$col} eq $_ && ' selected', $prioenum[$_]
255                 ) for 0 .. $#prioenum;
256                 print '</select>';
257                 printf(
258                         join('',
259                                 '<label>',
260                                 '<input id="%1$s" name="%1$s" value="0" type="hidden" />',
261                                 '<input id="%s" name="%1$s" value="1" type="checkbox"%s>',
262                                 ' %s</label>',
263                         ),
264                         'cover', !!$row->{cover} && ' checked', 'Highlighted'
265                 );
266         }
267         else {
268                 printf '<input id="%s" name="%1$s" value="%s" />', $col, Entity($val);
269                 -e and printf '<img src="/%s" alt="%s" />', $_, $row->{form} for
270                         $col eq 'source' ? "data/word/org/$row->{id}.jpg" :
271                         $col eq 'thumb'  ? "data/word/eng/$row->{form}.jpg" :
272                         ();
273         }
274                 print '</span>';
275         say '</p></li>';
276 }
277 :>
278 </ul>
279 <p>
280         <input type="submit" value="Save" />
281         <input type="submit" value="New" formaction="/writer?copy=cat" />
282 </p>
283 </form>
284
285 <:
286 if ($row->{id}) {
287 :>
288 <section id="nav">
289 <h2>Hierarchy</h2>
290
291 <:
292 say '<ul>';
293 my $parents = $db->select(word => '*', {id => $row->{cat}});
294 while (my $ref = $parents->hash) {
295         printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
296 }
297 say "<li><strong>$row->{form}</strong></li>";
298 my $children = $db->select(word => '*', {cat => $row->{id}});
299 while (my $ref = $children->hash) {
300         printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
301 }
302 :>
303 <li><form action="/writer">
304         <input type="hidden" name="cat" value="<:= $row->{id} :>" />
305         <input type="hidden" name="lang" value="<:= $row->{lang} :>" />
306         <input type="submit" value="Add" />
307 </form></li>
308 </ul>
309 </section>
310 <:
311 }
312 :>
313 </div>