word edit: flags in language selection
[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 %lang = (
109         nld => ["\N{REGIONAL INDICATOR SYMBOL LETTER N}\N{REGIONAL INDICATOR SYMBOL LETTER L}", 'dutch'],
110         eng => ["\N{REGIONAL INDICATOR SYMBOL LETTER G}\N{REGIONAL INDICATOR SYMBOL LETTER B}", 'english'],
111         epo => ['<span style="color:green">★</span>', 'esperanto'],
112 );
113 my @wordcols = pairkeys
114 my %wordcol = (
115         lang    => {-label => 'Language', -select => {
116                 map { $_ => "@{$lang{$_}}" } keys %lang
117         }},
118         cat     => [{-label => 'Category'}, 'ref'],
119         ref     => {-label => 'Reference'},
120         prio    => [
121                 {-label => 'Level', -select => [qw(
122                         essential basic common distinctive rare invisible
123                 )]},
124                 'cover', 'grade',
125         ],
126         cover   => {-label => 'Highlighted', type => 'checkbox'},
127         grade   => {-label => 'Order', type => 'number'},
128         form    => 'Title',
129         alt     => 'Synonyms',
130         wptitle => 'Wikipedia',
131         source  => 'Image',
132         thumb   => 'Convert options',
133 );
134 my ($find) = map {{id => $_}} $fields{id} || $Request || ();
135
136 my $row;
137 if ($find) {
138         $row = $db->select(word => '*', $find)->hash
139                 or Abort("Word not found", 404);
140 }
141
142 if (exists $get{copy}) {
143         $row = {%{$row}{ qw(prio lang cat) }};
144 }
145 elsif ($ENV{REQUEST_METHOD} eq 'POST') {{
146         my $replace = $row;
147         $row = {%post{keys %wordcol}};
148         $_ = length ? $_ : undef for values %{$row};
149
150         eval {
151                 my %res = (returning => '*');
152                 my $query = $find ? $db->update(word => $row, $find, \%res) :
153                         $db->insert(word => $row, \%res);
154                 $row = $query->hash;
155         } or do {
156                 Alert("Entry could not be saved", $@);
157                 next;
158         };
159
160         my $imgpath = Shiar_Sheet::FormRow::imagepath($row, 'source');
161         my $reimage = eval {
162                 ($row->{source} // '') ne ($replace->{source} // '') or return;
163                 # copy changed remote url to local file
164                 unlink $imgpath if -e $imgpath;
165                 my $download = $row->{source} or return 1;
166                 require LWP::UserAgent;
167                 my $ua = LWP::UserAgent->new;
168                 $ua->agent('/');
169                 my $status = $ua->mirror($download, $imgpath);
170                 $status->is_success
171                         or die "Download from <q>$download</q> failed: ".$status->status_line."\n";
172         };
173         !$@ or Alert(["Source image not found", $@]);
174
175         $reimage ||= $row->{thumb} ~~ $replace->{thumb};  # different convert
176         $reimage ||= $row->{cover} ~~ $replace->{cover};  # resize
177         $reimage++ if $fields{rethumb};  # force refresh
178
179         my $thumbpath = Shiar_Sheet::FormRow::imagepath($row => 'thumb');
180         if ($reimage) {
181                 if (-e $imgpath) {
182                         my $xyres = $row->{cover} ? '600x400' : '300x200';
183                         my @cmds = @{ $row->{thumb} // [] };
184                         @cmds = (
185                                 'convert',
186                                 -delete => '1--1', -background => 'white',
187                                 -gravity => @cmds ? 'northwest' : 'center',
188                                 @cmds,
189                                 -resize => "$xyres^", -extent => $xyres,
190                                 '-strip', -quality => '60%', -interlace => 'plane',
191                                 $imgpath => $thumbpath
192                         );
193                         eval {
194                                 require IPC::Run;
195                                 my $output;
196                                 IPC::Run::run(\@cmds, '<' => \undef, '>&' => \$output)
197                                         or die $output ||
198                                                 ($? & 127 ? "signal $?" : "error code ".($? >> 8))."\n";
199                         } or Alert([
200                                 "Thumbnail image not generated",
201                                 "Failed to convert source image.",
202                         ], "@cmds\n$@");
203                 }
204                 else {
205                         unlink $thumbpath;
206                 }
207         }
208 }}
209 else {
210         $row->{prio} //= 1;
211         $row->{$_} = $get{$_} for keys %get;
212 }
213
214 my $title = $row->{id} ? "entry <small>#$row->{id}</small>" : 'new entry';
215
216 package Shiar_Sheet::FormRow {
217         sub input {
218                 my ($row, $col, $attr) = @_;
219                 my $val = $row->{$col} // '';
220                 $val = '{'.join(',', map {s/,/\\,/gr} @{$val}).'}' if ref $val eq 'ARRAY';
221                 my $html = '';
222                 $html .= qq( $_="$attr->{$_}") for sort grep {!/^-/} keys %{$attr // {}};
223
224                 if (my $options = $attr->{-select}) {
225                         $options = { map {$_ => $options->[$_]} 0 .. $#{$options} }
226                                 if ref $options eq 'ARRAY';
227                         $options->{$val} //= "unknown ($val)";  # preserve current
228                         return (
229                                 sprintf('<select id="%s" name="%1$s">', $col),
230                                 (map { sprintf('<option value="%s"%s>%s</option>',
231                                         $_, $val eq $_ && ' selected', $options->{$_}
232                                 ) } sort keys %{$options}),
233                                 '</select>',
234                         );
235                 }
236                 elsif ($attr->{type} eq 'checkbox') {
237                         $html .= ' checked' if $val;
238                         return sprintf(
239                                 join('',
240                                         '<label>',
241                                         '<input name="%1$s" value="0" type="hidden" />',
242                                         '<input id="%s" name="%1$s" value="1"%s>',
243                                         ' %s</label>',
244                                 ), $col, $html, $attr->{-label}
245                         );
246                 }
247                 else {
248                         return (
249                                 (map {
250                                         sprintf('<label for="%s">%s</label>', $col, $_)
251                                 } $attr->{-label} // ()),
252                                 sprintf('<input id="%s" name="%1$s" value="%s"%s />',
253                                         $col, PLP::Functions::EscapeHTML($val), $html
254                                 ),
255                                 (map {
256                                         sprintf '<img id="%spreview" src="/%s" alt="%s"%s />',
257                                                 $col, $_, $row->{form}, $col eq 'source' ? ' hidden' : '';
258                                 } grep { -e } $row->imagepath($col)),
259                         );
260                 }
261         }
262
263         sub imagepath {
264                 my ($row, $col) = @_;
265                 return "data/word/org/$row->{id}.jpg"   if $col eq 'source';
266                 return "data/word/eng/$row->{form}.jpg" if $col eq 'thumb';
267                 return;
268         }
269 }
270 bless $row, 'Shiar_Sheet::FormRow';
271 :>
272 <h1>Words <:= $title :></h1>
273
274 <div class="inline">
275
276 <form action="?" method="post">
277 <input id="id" name="id" value="<:= $row->{id} // '' :>" type="hidden" />
278 <ul>
279 <:
280 for my $col (@wordcols) {
281         my $info = $wordcol{$col} or next;
282         my ($attr, @span) = ref $info eq 'ARRAY' ? @{$info} : $info;
283         my $title = ref $attr ? delete $attr->{-label} : $attr;
284         printf '<li><label for="%s">%s</label><p>', $col, $title;
285                 printf '<span class=inline>';
286                 print $row->input($col => $attr);
287                 print $row->input($_ => delete $wordcol{$_}) for @span;
288                 print '</span>';
289         say '</p></li>';
290 }
291
292 if ($row->{id}) {
293         my $children = $db->select(word => '*', {ref => $row->{id}}, 'lang, id');
294         printf '<li><label>%s</label><div><ul class="inline">', 'Translations';
295         while (my $row = $children->hash) {
296                 printf(
297                         '<li><label for="%1$s" title="%5$s">%4$s</label>' .
298                                 ' <a id="%s" href="%s">%s</a></li>',
299                         "trans-$row->{lang}", "/writer/$row->{id}", Entity($row->{form}),
300                         @{$lang{ $row->{lang} }}, # flag, name
301                 );
302         }
303         say '</ul></div></li>';
304 }
305 :>
306 </ul>
307 <p>
308         <input type="submit" value="Save" />
309         <input type="submit" value="New" formaction="/writer?copy=cat" />
310 </p>
311 </form>
312
313 <:
314 if ($row->{id}) {
315 :>
316 <section id="nav">
317 <h2>Hierarchy</h2>
318
319 <:
320 say '<ul>';
321 my $parents = $db->select(word => '*', {id => $row->{cat}});
322 while (my $ref = $parents->hash) {
323         printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
324 }
325 say "<li><strong>$row->{form}</strong></li>";
326 my $children = $db->select(word => '*', {cat => $row->{id}}, 'grade, id');
327 while (my $ref = $children->hash) {
328         printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
329 }
330 :>
331 <li><form action="/writer">
332         <input type="hidden" name="cat" value="<:= $row->{id} :>" />
333         <input type="hidden" name="lang" value="<:= $row->{lang} :>" />
334         <input type="submit" value="Add" />
335 </form></li>
336 </ul>
337 </section>
338 <:
339 }
340 :>
341 </div>