5b81a20e5f6d6df90c2e2ddb2e1a071c480e9465
[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         if (($row->{source} // '') ne ($replace->{source} // '')) {
181                 # copy changed remote url to local file
182                 unlink $imgpath if -e $imgpath;
183                 if (my $download = $row->{source}) {
184                         require LWP::UserAgent;
185                         my $ua = LWP::UserAgent->new;
186                         $ua->agent('/');
187                         my $status = $ua->mirror($download, $imgpath);
188                         $status->is_success or Alert([
189                                 "Source image not found",
190                                 "Download from <q>$download</q> failed: ".$status->status_line,
191                         ]);
192                 }
193         }
194         elsif ($row->{thumb} ~~ $replace->{thumb}) {
195                 # image and conversion unaltered
196                 $imgpath = undef;
197         }
198
199         my $thumbpath = "data/word/eng/$row->{form}.jpg";
200         if ($imgpath) {
201                 if (-e $imgpath) {
202                         my $xyres = $row->{cover} ? '600x400' : '300x200';
203                         my @cmds = @{ $row->{thumb} // [] };
204                         @cmds = (
205                                 'convert',
206                                 -delete => '1--1', -background => 'white',
207                                 -gravity => @cmds ? 'northwest' : 'center',
208                                 @cmds,
209                                 -resize => "$xyres^", -extent => $xyres,
210                                 '-strip', -quality => '60%', -interlace => 'plane',
211                                 $imgpath => $thumbpath
212                         );
213                         my $status = system @cmds;
214                         $status == 0 or Alert([
215                                 "Thumbnail image not generated",
216                                 "Failed to convert source image, error code ".($status >> 8),
217                         ], "@cmds");
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 <h1>Words <:= $title :></h1>
232
233 <div class="inline">
234
235 <form action="?" method="post">
236 <input id="id" name="id" value="<:= $row->{id} // '' :>" type="hidden" />
237 <ul>
238 <:
239
240 for my $colinfo (pairs @wordcols) {
241         my ($col, $title) = @{$colinfo};
242         defined $title or next;
243         my $val = $row->{$col} // '';
244         $val = '{'.join(',', map {s/,/\\,/gr} @{$val}).'}' if ref $val eq 'ARRAY';
245         printf '<li><label for="%s">%s</label><p>', $col, $title;
246                 printf '<span class=inline>';
247         if ($col eq 'prio') {
248                 printf '<select id="%s" name="%1$s">', $col;
249                 printf('<option value="%s"%s>%s</option>',
250                         $_, $row->{$col} eq $_ && ' selected', $prioenum[$_]
251                 ) for 0 .. $#prioenum;
252                 print '</select>';
253                 printf(
254                         join('',
255                                 '<label>',
256                                 '<input id="%1$s" name="%1$s" value="0" type="hidden" />',
257                                 '<input id="%s" name="%1$s" value="1" type="checkbox"%s>',
258                                 ' %s</label>',
259                         ),
260                         'cover', !!$row->{cover} && ' checked', 'Highlighted'
261                 );
262         }
263         else {
264                 printf '<input id="%s" name="%1$s" value="%s" />', $col, Entity($val);
265                 -e and printf '<img src="/%s" alt="%s" />', $_, $row->{form} for
266                         $col eq 'source' ? "data/word/org/$row->{id}.jpg" :
267                         $col eq 'thumb'  ? "data/word/eng/$row->{form}.jpg" :
268                         ();
269         }
270                 print '</span>';
271         say '</p></li>';
272 }
273 :>
274 </ul>
275 <p>
276         <input type="submit" value="Save" />
277         <input type="submit" value="New" formaction="/writer?copy=cat" />
278 </p>
279 </form>
280
281 <:
282 if ($row->{id}) {
283 :>
284 <section id="nav">
285 <h2>Hierarchy</h2>
286
287 <:
288 say '<ul>';
289 my $parents = $db->select(word => '*', {id => $row->{cat}});
290 while (my $ref = $parents->hash) {
291         printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
292 }
293 say "<li><strong>$row->{form}</strong></li>";
294 my $children = $db->select(word => '*', {cat => $row->{id}});
295 while (my $ref = $children->hash) {
296         printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
297 }
298 :>
299 <li><form action="/writer">
300         <input type="hidden" name="cat" value="<:= $row->{id} :>" />
301         <input type="hidden" name="lang" value="<:= $row->{lang} :>" />
302         <input type="submit" value="Add" />
303 </form></li>
304 </ul>
305 </section>
306 <:
307 }
308 :>
309 </div>