latin: hardcoded tetromino block cascades
[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 <link rel="stylesheet" type="text/css" media="all" href="/editor.css" />
9 <script src="/writer.js"></script>
10 EOT
11 });
12
13 use List::Util qw( pairs pairkeys );
14 use Shiar_Sheet::FormRow;
15
16 my $db = eval {
17         require Shiar_Sheet::DB;
18         Shiar_Sheet::DB->connect;
19 } or Abort('Database error', 501, $@);
20
21 my $user = eval {
22         my $rootpath = ($ENV{REQUEST_URI} // '/writer') =~ s{(?<!^)/.+}{}r;
23         if (defined $post{username}) {
24                 $cookie{login} = EncodeURI(join ':', @post{qw( username pass )});
25         }
26         elsif (exists $fields{logout}) {
27                 require CGI::Cookie;
28                 if (AddCookie(CGI::Cookie->new(
29                         -name    => 'login',
30                         -value   => '',
31                         -path    => $rootpath,
32                         -expires => 'now',
33                 )->as_string)) {
34                         delete $cookie{login};
35                         die "Logged out as requested\n";
36                 }
37                 Alert("Failed to log out", "Login cookie could not be removed.");
38         }
39
40         my $cookiedata = $cookie{login} or return;
41         my ($name, $key) = split /[:\v]/, DecodeURI($cookiedata);
42         my %rowmatch = (username => $name, pass => $key);
43         my $found = $db->select(login => '*', \%rowmatch)->hash
44                 or die "Invalid user or password\n";
45
46         eval {
47                 require CGI::Cookie;
48                 my $httpcookie = CGI::Cookie->new(
49                         -name    => 'login',
50                         -value   => join(':', @{$found}{qw( username pass )}),
51                         -path    => $rootpath,
52                 ) or die "prepared object is empty\n";
53                 AddCookie($httpcookie->as_string);
54         } or Abort(["Unable to create login cookie", $@], 403);
55
56         return $found;
57 } or do {
58         say '<h1>Login to edit words</h1>';
59         Alert('Access denied', $@) if $@;
60         say '<form action="?" method="post" class="inline"><ul>';
61         my $loginform = bless {%post}, 'Shiar_Sheet::FormRow';
62         say '<li>', $loginform->input(@{$_}), '</li>' for pairs (
63                 username => {-label => 'User name'},
64                 pass     => {-label => 'Password', type => 'password'},
65         );
66         say '<li><input type="submit" value="Login" /></li>';
67         say '</ul></form>';
68         exit;
69 };
70
71 my %lang = (
72         nl => ["\N{REGIONAL INDICATOR SYMBOL LETTER N}\N{REGIONAL INDICATOR SYMBOL LETTER L}", 'nederlands'],
73         en => ["\N{REGIONAL INDICATOR SYMBOL LETTER G}\N{REGIONAL INDICATOR SYMBOL LETTER B}", 'english'],
74         eo => ['<span style="color:green">★</span>', 'esperanto'],
75         ru => ["\N{REGIONAL INDICATOR SYMBOL LETTER R}\N{REGIONAL INDICATOR SYMBOL LETTER U}", 'русский'],
76         zh => ["\N{REGIONAL INDICATOR SYMBOL LETTER C}\N{REGIONAL INDICATOR SYMBOL LETTER N}", '中文'],
77         la => ["\N{PUSHPIN}", 'latin'],
78 );
79 my @wordcols = pairkeys
80 my %wordcol = (
81         lang    => {-label => 'Language', -select => {
82                 map { $_ => "@{$lang{$_}}" } keys %lang
83         }},
84         cat     => [{-label => 'Category'}, 'ref'],
85         ref     => {-label => 'Reference'},
86         prio    => [
87                 {-label => 'Level', -select => sub {
88                         my ($row) = @_;
89                         my @enum = qw[ essential basic common distinctive optional invisible ];
90                         return {
91                                 ('' => 'parent') x (defined $row->{ref}),
92                                 map { $_ => $enum[$_] } 0 .. $#enum
93                         };
94                 }},
95                 'cover', 'grade',
96         ],
97         cover   => {-label => 'Highlighted', type => 'checkbox'},
98         grade   => {-label => 'Order', type => 'number'},
99         form    => {-label => 'Title'},
100         alt     => {-label => 'Synonyms', -multiple => 1},
101         wptitle => {-label => 'Wikipedia'},
102         source  => {-label => 'Image', -src => sub {
103                 return "data/word/org/$_[0]->{id}.jpg";
104         }},
105         thumb   => {-label => 'Convert options', -multiple => 1, -src => sub {
106                 return "data/word/en/$_[0]->{id}.jpg";
107         }},
108         story   => {-label => 'Story', type => 'textarea', hidden => 'hidden'},
109 );
110
111 if (my $search = $fields{q}) {
112         my %filter = (form => {ilike => '%'.$search.'%'});
113         my $results = $db->select(word => '*', \%filter);
114         say '<h1>Search</h1><ul>';
115         printf("<li><small>%s</small> %s %s</li>\n",
116                 $_->{id}, showlink($_->{form}, "/writer/$_->{id}"),
117                 sprintf('<img src="/%s" style="height:3ex; width:auto" />', $wordcol{thumb}->{-src}->($_)) x defined $_->{thumb}
118         ) for $results->hashes;
119         say "</ul>\n";
120         exit;
121 }
122
123 my ($find) = map {{id => $_}} $fields{id} || $Request || ();
124 my $row;
125 if ($find) {
126         $row = $db->select(word => '*', $find)->hash
127                 or Abort("Word not found", 404);
128 }
129
130 if (exists $get{copy}) {
131         $row = {%{$row}{ qw(prio lang cat) }};
132 }
133 elsif (defined $post{form}) {{
134         sub parseinput {
135                 return if not length $_[0];
136                 require Encode;
137                 return Encode::decode_utf8($_[0]);
138         }
139
140         my $replace = $row;
141         $row = {map { $_ =>
142                 ref $wordcol{$_} eq 'HASH' && $wordcol{$_}->{-multiple} ?
143                         [ map { parseinput($_) } $post{'@'.$_}->@* ] :
144                 scalar parseinput($post{$_})
145         } keys %wordcol};
146
147         if (!$row->{form}) {
148                 if ($row->{ref} ne 'delete') {
149                         Alert("Empty title",
150                                 "Confirm removal by setting <em>Reference</em> to <q>delete</q>."
151                         );
152                 }
153                 else {
154                         $db->delete(word => $find);
155                         Alert("Entry removed");
156                 }
157                 next;
158         }
159
160         eval {
161                 my %res = (returning => '*');
162                 $row->{creator} = $user->{id} unless $find;
163                 $row->{updated} = ['now()'];
164                 my $query = $find ? $db->update(word => $row, $find, \%res) :
165                         $db->insert(word => $row, \%res);
166                 $row = $query->hash;
167         } or do {
168                 Alert("Entry could not be saved", $@);
169                 next;
170         };
171
172         eval {
173                 while (my ($lang, $val) = each %post) {
174                         my $field = $lang;
175                         $lang =~ s/^trans-// or next;
176                         $val = parseinput($val) or next;
177                         my %subrow = (
178                                 ref   => $row->{id},
179                                 lang  => $lang,
180                                 form  => $val,
181                                 prio  => undef,
182                         );
183                         $subrow{wptitle} = $1 if $subrow{form} =~ s/\h*\[(.*)\]$//; # [Link] shorthand
184                         $subrow{alt} = [split m{/}, $1] if $subrow{form} =~ s{/(\S.*)}{}; # /alternates shorthand
185                         $db->insert(word => \%subrow);
186                         delete $fields{$field};
187                 }
188                 return 1;
189         } or Alert('Error creating translation entries', $@);
190
191         require Shiar_Sheet::ImagePrep;
192         my $image = Shiar_Sheet::ImagePrep->new($wordcol{source}->{-src}->($row));
193         my $reimage = eval {
194                 ($row->{source} // '') ne ($replace->{source} // '') or return;
195                 $image->download($row->{source});
196         };
197         !$@ or Alert(["Source image not found", $@]);
198
199         $reimage ||= $row->{thumb} ~~ $replace->{thumb};  # different convert
200         $reimage ||= $row->{cover} ~~ $replace->{cover};  # resize
201         $reimage++ if $fields{rethumb};  # force refresh
202         if ($reimage) {
203                 eval {
204                         $image->convert($wordcol{thumb}->{-src}->($row), $row->{thumb});
205                 } or do {
206                         my ($warn, @details) = ref $@ ? @{$@} : $@;
207                         Alert([ "Thumbnail image not generated", $warn ], @details);
208                 };
209         }
210 }}
211 else {
212         $row->{lang} //= $user->{editlang}->[0];
213         $row->{$_} = $get{$_} for keys %get;
214         $row->{prio} = defined $row->{ref} ? undef : 1 unless exists $row->{prio};
215 }
216
217 my $title = $row->{id} ? "entry <small>#$row->{id}</small>" : 'new entry';
218 bless $row, 'Shiar_Sheet::FormRow';
219 :>
220 <h1>Words <:= $title :></h1>
221
222 <div class="inline">
223
224 <form action="?" method="post">
225 <input id="id" name="id" value="<:= $row->{id} // '' :>" type="hidden" />
226 <ul>
227 <:
228 for my $col (@wordcols) {
229         my $info = $wordcol{$col} or next;
230         my ($attr, @span) = ref $info eq 'ARRAY' ? @{$info} : $info;
231         next if delete $attr->{hidden} and not $row->{$col};
232         my $title = ref $attr ? delete $attr->{-label} : $attr;
233         printf '<li><label for="%s">%s</label><p>', $col, $title;
234                 printf '<span class=inline>';
235                 print $row->input($col => $attr);
236                 if (my $imgsrc = $attr->{-src}) {
237                         printf('<img id="%spreview" src="/%s" alt="%s"%s />',
238                                 $col, $_, $row->{form}, $col eq 'source' && ' hidden'
239                         ) for grep { -e } $imgsrc->($row);
240                 }
241                 print $row->input($_ => delete $wordcol{$_}) for @span;
242                 print '</span>';
243         say '</p></li>';
244 }
245
246 if (not $row->{ref}) {
247         printf '<li><label for="%s">%s</label><div><ul class="inline" id="%1$s">',
248                 'trans', 'Translations';
249         my @children = !$row->{id} ? () :
250                 $db->select(word => '*', {ref => $row->{id}}, 'lang, id')->hashes;
251         while (my ($lang, $val) = each %fields) {
252                 $lang =~ s/^trans-// or next;
253                 push @children, { lang => $lang, form => $val };
254         }
255         my %existing = map { $_->{lang} => 1 } $row, @children;
256         $existing{$_} or push @children, { lang => $_ } for @{$user->{editlang}};
257
258         for my $ref (@children) {
259                 printf(
260                         '<li><label for="%s" title="%3$s">%s </label>',
261                         "trans-$ref->{lang}", @{$lang{ $ref->{lang} }}, # flag, name
262                 );
263                 printf(
264                         $ref->{id} ? '<a id="%s" href="%s">%s</a></li>' :
265                         '<input id="%s" name="%1$s" value="%3$s" />',
266                         "trans-$ref->{lang}", "/writer/$ref->{id}", Entity($ref->{form} // ''),
267                 );
268         }
269         say '</ul></div></li>';
270 }
271 :>
272 </ul>
273 <p>
274         <input type="submit" value="Save" />
275         <input type="submit" value="New" formaction="/writer?copy=cat" />
276 </p>
277 </form>
278
279 <:
280 if ($row->{id}) {
281 :>
282 <section id="nav">
283 <h2>Hierarchy</h2>
284
285 <:
286 say '<ul>';
287 my $parents = $db->select(word => '*', [{id => $row->{cat}}, {id => $row->{ref}}]);
288 while (my $ref = $parents->hash) {
289         printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
290 }
291 say "<li><strong>$_</strong></li>" for Entity($row->{form});
292 my $children = $db->select(word => '*', {cat => $row->{id}, ref => undef}, 'grade, id');
293 while (my $ref = $children->hash) {
294         printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
295 }
296 :>
297 <li><form action="/writer">
298         <input type="hidden" name="cat" value="<:= $row->{id} :>" />
299         <input type="hidden" name="lang" value="<:= $row->{lang} :>" />
300         <input type="submit" value="Add" />
301 </form></li>
302 </ul>
303 </section>
304 <:
305 }
306 :>
307 </div>