f4819b735e7bcf04953f461ea8a82e186376f125
[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 input[type=number] {
41         max-width: 7em;
42 }
43 select {
44         padding: .3rem .2rem; /* TODO: input */
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 src="/writer.js"></script>
89 EOT
90 });
91
92 use List::Util qw( pairs pairkeys );
93
94 my $db = eval {
95         my @dbinfo = (
96                 'DBI:Pg:dbname=sheet;host=localhost', 'sheetadmin', 'fairuse',
97         ) or die "database not configured\n";
98         require DBIx::Simple;
99         DBIx::Simple->new(@dbinfo[0..2], {
100                 RaiseError => 1,
101                 pg_enable_utf8 => 1,
102         });
103 } or Abort('Database error', 501, $@);
104
105 my @wordcols = (
106         lang    => 'Language',
107         cat     => 'Category',
108         ref     => undef, # included with cat
109         grade   => undef, # "
110         prio    => 'Level',
111         cover   => undef, # included with prio
112         form    => 'Translation',
113         alt     => 'Synonyms',
114         wptitle => 'Wikipedia',
115         source  => 'Image',
116         thumb   => 'Convert options',
117 );
118 my @prioenum = qw( essential basic common distinctive rare invisible );
119 my ($find) = map {{id => $_}} $fields{id} || $Request || ();
120
121 my $row;
122 if ($find) {
123         $row = $db->select(word => '*', $find)->hash
124                 or Abort("Word not found", 404);
125 }
126
127 if (exists $get{copy}) {
128         $row = {%{$row}{ qw(prio lang cat) }};
129 }
130 elsif ($ENV{REQUEST_METHOD} eq 'POST') {{
131         my $replace = $row;
132         $row = {%post{ pairkeys @wordcols }};
133         $_ = length ? $_ : undef for values %{$row};
134
135         eval {
136                 my %res = (returning => '*');
137                 my $query = $find ? $db->update(word => $row, $find, \%res) :
138                         $db->insert(word => $row, \%res);
139                 $row = $query->hash;
140         } or do {
141                 Alert("Entry could not be saved", $@);
142                 next;
143         };
144
145         my $imgpath = "data/word/org/$row->{id}.jpg";
146         my $reimage = eval {
147                 ($row->{source} // '') ne ($replace->{source} // '') or return;
148                 # copy changed remote url to local file
149                 unlink $imgpath if -e $imgpath;
150                 my $download = $row->{source} or return 1;
151                 require LWP::UserAgent;
152                 my $ua = LWP::UserAgent->new;
153                 $ua->agent('/');
154                 my $status = $ua->mirror($download, $imgpath);
155                 $status->is_success
156                         or die "Download from <q>$download</q> failed: ".$status->status_line."\n";
157         };
158         !$@ or Alert(["Source image not found", $@]);
159
160         $reimage ||= $row->{thumb} ~~ $replace->{thumb};  # different convert
161         $reimage ||= $row->{cover} ~~ $replace->{cover};  # resize
162         $reimage++ if $fields{rethumb};  # force refresh
163
164         my $thumbpath = "data/word/eng/$row->{form}.jpg";
165         if ($reimage) {
166                 if (-e $imgpath) {
167                         my $xyres = $row->{cover} ? '600x400' : '300x200';
168                         my @cmds = @{ $row->{thumb} // [] };
169                         @cmds = (
170                                 'convert',
171                                 -delete => '1--1', -background => 'white',
172                                 -gravity => @cmds ? 'northwest' : 'center',
173                                 @cmds,
174                                 -resize => "$xyres^", -extent => $xyres,
175                                 '-strip', -quality => '60%', -interlace => 'plane',
176                                 $imgpath => $thumbpath
177                         );
178                         eval {
179                                 require IPC::Run;
180                                 my $output;
181                                 IPC::Run::run(\@cmds, '<' => \undef, '>&' => \$output)
182                                         or die $output ||
183                                                 ($? & 127 ? "signal $?" : "error code ".($? >> 8))."\n";
184                         } or Alert([
185                                 "Thumbnail image not generated",
186                                 "Failed to convert source image.",
187                         ], "@cmds\n$@");
188                 }
189                 else {
190                         unlink $thumbpath;
191                 }
192         }
193 }}
194 else {
195         $row->{prio} //= 1;
196         $row->{$_} = $get{$_} for keys %get;
197 }
198
199 my $title = $row->{id} ? "entry <small>#$row->{id}</small>" : 'new entry';
200 :>
201 <h1>Words <:= $title :></h1>
202
203 <div class="inline">
204
205 <form action="?" method="post">
206 <input id="id" name="id" value="<:= $row->{id} // '' :>" type="hidden" />
207 <ul>
208 <:
209
210 for my $colinfo (pairs @wordcols) {
211         my ($col, $title) = @{$colinfo};
212         defined $title or next;
213         my $val = $row->{$col} // '';
214         $val = '{'.join(',', map {s/,/\\,/gr} @{$val}).'}' if ref $val eq 'ARRAY';
215         printf '<li><label for="%s">%s</label><p>', $col, $title;
216                 printf '<span class=inline>';
217         if ($col eq 'prio') {
218                 printf '<select id="%s" name="%1$s">', $col;
219                 printf('<option value="%s"%s>%s</option>',
220                         $_, $row->{$col} eq $_ && ' selected', $prioenum[$_]
221                 ) for 0 .. $#prioenum;
222                 print '</select>';
223                 printf(
224                         join('',
225                                 '<label>',
226                                 '<input id="%1$s" name="%1$s" value="0" type="hidden" />',
227                                 '<input id="%s" name="%1$s" value="1" type="checkbox"%s>',
228                                 ' %s</label>',
229                         ),
230                         'cover', !!$row->{cover} && ' checked', 'Highlighted'
231                 );
232                 printf('<label for="%s">%s</label><input id="%1$s" name="%1$s" value="%s" type="number" />',
233                         'grade', 'Order', Entity($row->{grade})
234                 );
235         }
236         else {
237                 printf '<input id="%s" name="%1$s" value="%s" />', $col, Entity($val);
238                 -e and printf '<img src="/%s" alt="%s" />', $_, $row->{form}
239                         for $col eq 'thumb'  ? "data/word/eng/$row->{form}.jpg" : ();
240                 printf('<label for="%s">%s</label><input id="%1$s" name="%1$s" value="%s" />',
241                         'ref', 'Reference', Entity($row->{ref})
242                 ) if $col eq 'cat';
243         }
244                 print '</span>';
245         -e and printf('<img id="%spreview" src="/%s" alt="%s" hidden />',
246                 $col, $_, $row->{form}
247         ) for $col eq 'source' ? "data/word/org/$row->{id}.jpg" : ();
248         say '</p></li>';
249 }
250 :>
251 </ul>
252 <p>
253         <input type="submit" value="Save" />
254         <input type="submit" value="New" formaction="/writer?copy=cat" />
255 </p>
256 </form>
257
258 <:
259 if ($row->{id}) {
260 :>
261 <section id="nav">
262 <h2>Hierarchy</h2>
263
264 <:
265 say '<ul>';
266 my $parents = $db->select(word => '*', {id => $row->{cat}});
267 while (my $ref = $parents->hash) {
268         printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
269 }
270 say "<li><strong>$row->{form}</strong></li>";
271 my $children = $db->select(word => '*', {cat => $row->{id}}, 'grade, id');
272 while (my $ref = $children->hash) {
273         printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
274 }
275 :>
276 <li><form action="/writer">
277         <input type="hidden" name="cat" value="<:= $row->{id} :>" />
278         <input type="hidden" name="lang" value="<:= $row->{lang} :>" />
279         <input type="submit" value="Add" />
280 </form></li>
281 </ul>
282 </section>
283 <:
284 }
285 :>
286 </div>