word edit: select wikipedia images from overlay
[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 dd > input {
10         width: 32em;
11         max-width: 100%;
12         padding: 1ex;
13         font-family: monospace;
14 }
15 dl > dt, dl > dd {
16         float: none;
17         display: inline-block;
18         box-sizing: border-box;
19         width: 50%;
20         margin: 0;
21         line-height: 4ex;
22         vertical-align: text-top;
23 }
24 dd > img {
25         max-width: 300px;
26         display: block;
27 }
28 dd input ~ button {
29         margin-left: -5em;
30 }
31
32 ul.popup {
33         display: flex;
34         flex-wrap: wrap;
35         align-items: end;
36         position: fixed;
37         left: 0;
38         top: 0;
39         margin: auto;
40         max-height: 90%;
41         max-width: 90%;
42         overflow: auto;
43         background: rgba(0, 0, 0, .8);
44         border: 1px solid #CCC;
45 }
46 </style>
47
48 <script>
49 document.addEventListener('DOMContentLoaded', () => {
50         var wpinput = document.getElementById('wptitle');
51         var wpbutton = wpinput.parentNode.appendChild(document.createElement('button'));
52         wpbutton.type = 'button';
53         wpbutton.append('Copy');
54         wpbutton.onclick = () => {
55                 let wptitle = wpinput.value || document.getElementById('form').value;
56                 let wppage = 'https://en.wikipedia.org/w/api.php?action=parse&format=json&origin=*&prop=text&page='+wptitle;
57                 fetch(wppage).then(res => res.json()).then(json => {
58                         if (json.error) throw `error returned: ${json.error.info}`;
59                         wpinput.value = json.parse.title;
60                         let imginput = document.getElementById('source');
61                         if (imginput.value) return;
62                         let wpimages = json.parse.text['*'].match(/<img\s[^>]+>/g);
63                         let wpselect = wpinput.parentNode.appendChild(document.createElement('ul'));
64                         wpselect.className = 'popup';
65                         wpimages.forEach(img => {
66                                 let selectitem = wpselect.appendChild(document.createElement('li'));
67                                 selectitem.insertAdjacentHTML('beforeend', img);
68                                 selectitem.onclick = e => {
69                                         let imgsrc = e.target.src
70                                                 .replace(/^(?=\/\/)/, 'https:')
71                                                 .replace(/\/thumb(\/.+)\/[^\/]+$/, '$1');
72                                         imginput.value = imgsrc;
73                                         wpselect.remove();
74                                         return false;
75                                 };
76                         });
77                 }).catch(error => alert(error));
78                 return false;
79         };
80 });
81 </script>
82 EOT
83 });
84
85 use List::Util qw( pairs pairkeys );
86
87 my $db = eval {
88         my @dbinfo = (
89                 'DBI:Pg:dbname=sheet;host=localhost', 'sheetadmin', 'fairuse',
90         ) or die "database not configured\n";
91         require DBIx::Simple;
92         DBIx::Simple->new(@dbinfo[0..2], {
93                 RaiseError => 1,
94                 pg_enable_utf8 => 1,
95         });
96 } or Abort('Database error', 501, $@);
97
98 my @wordcols = (
99         form    => 'Translation',
100         wptitle => 'Wikipedia',
101         ref     => 'Reference',
102         cat     => 'Category',
103         lang    => 'Language',
104         source  => 'Image URL',
105         thumb   => 'Convert options',
106 );
107 my ($find) = map {{id => $_}} $fields{id} || $Request || ();
108
109 my $row;
110 if (exists $get{copy}) {
111         $row = {%fields{ qw(lang cat) }};
112 }
113 elsif ($ENV{REQUEST_METHOD} eq 'POST') {
114         $row = {%post{ pairkeys @wordcols }};
115         $_ = length ? $_ : undef for values %{$row};
116         eval {
117                 my %res = (returning => '*');
118                 my $query = $find ? $db->update(word => $row, $find, \%res) :
119                         $db->insert(word => $row, \%res);
120                 $row = $query->hash;
121         } or Alert("Entry could not be saved", $@);
122
123         my $imgpath = "data/word/org/$row->{id}.jpg";
124         if (my $download = $row->{source} and !-e $imgpath) {
125                 require LWP::UserAgent;
126                 my $ua = LWP::UserAgent->new;
127                 $ua->agent('/');
128                 my $status = $ua->mirror($download, $imgpath);
129                 $status->is_success or Alert([
130                         "Source image not found",
131                         "Download from <q>$download</q> failed: ".$status->status_line,
132                 ]);
133         }
134
135         my $thumbpath = "data/word/eng/$row->{form}.jpg";
136         if (-e $imgpath) {
137                 my @cmds = @{ $row->{thumb} // [] };
138                 @cmds = (
139                         'convert',
140                         -delete => '1--1', -background => 'white',
141                         -gravity => @cmds ? 'northwest' : 'center',
142                         @cmds,
143                         -resize => '300x200^', -extent => '300x200',
144                         '-strip', -quality => '60%', -interlace => 'plane',
145                         $imgpath => $thumbpath
146                 );
147                 my $status = system @cmds;
148                 $status == 0 or Alert([
149                         "Thumbnail image not generated",
150                         "Failed to convert source image, error code ".($status >> 8),
151                 ], "@cmds");
152         }
153 }
154 elsif ($find) {
155         $row = $db->select(word => '*', $find)->hash
156                 or Abort("Word not found", 404);
157 }
158
159 my $title = $row->{id} ? "entry <small>#$row->{id}</small>" : 'new entry';
160 :>
161 <h1>Words <:= $title :></h1>
162
163 <form action="?" method="post">
164 <input id="id" name="id" value="<:= $row->{id} // '' :>" type="hidden" />
165 <dl>
166 <:
167
168 for my $col (pairs @wordcols) {
169         my $val = $row->{$col->key} // '';
170         $val = '{'.join(',', map {s/,/\\,/gr} @{$val}).'}' if ref $val eq 'ARRAY';
171         printf '<dt><label for="%s">%s</label></dt>'
172                 . '<dd><input id="%1$s" name="%1$s" value="%s" />',
173                 $col->key, $col->value, Entity($val);
174         -e and printf ' <img src="/%s" alt="%s" />', $_, $row->{form} for
175                 $col->key eq 'source' ? "data/word/org/$row->{id}.jpg" :
176                 $col->key eq 'thumb'  ? "data/word/eng/$row->{form}.jpg" :
177                 ();
178         say '</dd>';
179 }
180 :>
181 </dl>
182 <p>
183         <input type="submit" value="Save" />
184         <input type="submit" value="New" formaction="/writer?copy=cat" />
185 </p>
186 </form>