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