package Newslash::Web::Controller::Story;
use Mojo::Base 'Mojolicious::Controller';
+use Data::Dumper;
sub story {
my $c = shift;
my $user = {};
if ($session->{token}) {
- $user = $c->users->get(token => $session->{token});
+ $user = $c->users->get(token => $session->{token});
}
my $story = $c->stories->select(sid => $sid);
my $discuss = $c->discussions->select(sid => $sid);
my $d_id = $discuss->{id};
my $comments = [];
if ($d_id) {
- $comments = $c->comments->select(discussion_id => $d_id);
+ $comments = $c->comments->select(discussion_id => $d_id);
}
+ my $roots = $c->_build_comment_tree($comments);
+ #$c->app->log->debug(Dumper($roots));
+ $c->render(user => $user, sid => $sid, story => $story, comments => $comments, root_comments => $roots);
+}
+
+sub _build_comment_tree {
+ my ($c, $comments) = @_;
+ my $root = [];
+ my $comment_of = {};
+
+ # prerequisite: $comments are sorted with ascendent order by cid
+ for my $comment (@$comments) {
+ my $pid = $comment->{pid};
+ my $cid = $comment->{cid};
+ $comment_of->{$cid} = $comment;
+ $comment->{children} = [];
- $c->render(user => $user, sid => $sid, story => $story, comments => $comments);
+ if ($pid == 0) {
+ push @$root, $comment;
+ next;
+ }
+
+ my $parent = $comment_of->{$pid};
+ if ($parent) {
+ push @{$parent->{children}}, $comment;
+ } else {
+ $c->app->log->warn("(Controller::Story) invalid comment order. cid: $cid, pid: $pid");
+ }
+ }
+ return $root;
}
+
1;
[% WRAPPER common/layout sidebar=1 %]
+[%- BLOCK subcomments -%]
+<li>
+ [%- INCLUDE common/comment comment=item -%]
+ <ol>
+ [%- FOREACH sub_item IN item.children -%]
+ [%- INCLUDE subcomments item=sub_item -%]
+ [%- END -%]
+ </ol>
+</li>
+[%- END -%]
+
+
<div class="main-column">
<div class="story main-contents">
[%- INCLUDE common/article hide_more_link = 1 %]
<div id="comments">
<ol>
- [%- FOREACH comment IN comments -%]
+ [%- FOREACH item IN root_comments -%]
<li>
- [% INCLUDE common/comment %]
+ [%- INCLUDE common/comment comment=item -%]
+ <ol>
+ [%- FOREACH sub_item IN item.children -%]
+ [%- INCLUDE subcomments item=sub_item -%]
+ [%- END -%]
+ </ol>
</li>
[%- END -%]
</ol>