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