Commit 0b96d009 by Rocky Duan

ajax reply & why am I on discussion2..

parent 89c28115
......@@ -15,6 +15,7 @@ from django.core.files.storage import get_storage_class
from django.utils.translation import ugettext as _
from django.conf import settings
from mitxmako.shortcuts import render_to_response, render_to_string
from django_comment_client.utils import JsonResponse, JsonError, extract
def thread_author_only(fn):
......@@ -58,7 +59,15 @@ def create_thread(request, course_id, commentable_id):
if request.POST.get('autowatch', 'false').lower() == 'true':
attributes['auto_subscribe'] = True
response = comment_client.create_thread(commentable_id, attributes)
return JsonResponse(response)
if request.is_ajax():
context = {
'course_id': course_id,
'thread': response,
}
html = render_to_string('discussion/ajax_thread_only.html', context)
return HtmlResponse(html)
else:
return JsonResponse(response)
@thread_author_only
@login_required
......@@ -68,9 +77,7 @@ def update_thread(request, course_id, thread_id):
response = comment_client.update_thread(thread_id, attributes)
return JsonResponse(response)
@login_required
@require_POST
def create_comment(request, course_id, thread_id):
def _create_comment(request, course_id, _response_from_attributes):
attributes = extract(request.POST, ['body'])
attributes['user_id'] = request.user.id
attributes['course_id'] = course_id
......@@ -78,8 +85,24 @@ def create_comment(request, course_id, thread_id):
attributes['anonymous'] = True
if request.POST.get('autowatch', 'false').lower() == 'true':
attributes['auto_subscribe'] = True
response = comment_client.create_comment(thread_id, attributes)
return JsonResponse(response)
response = _response_from_attributes(attributes)
if request.is_ajax():
context = {
'comment': response,
}
html = render_to_string('discussion/ajax_comment_only.html', context)
return JsonResponse({
'html': html,
})
else:
return JsonResponse(response)
@login_required
@require_POST
def create_comment(request, course_id, thread_id):
def _response_from_attributes(attributes):
return comment_client.create_comment(thread_id, attributes)
return _create_comment(request, course_id, _response_from_attributes)
@thread_author_only
@login_required
......@@ -107,15 +130,9 @@ def endorse_comment(request, course_id, comment_id):
@login_required
@require_POST
def create_sub_comment(request, course_id, comment_id):
attributes = extract(request.POST, ['body'])
attributes['user_id'] = request.user.id
attributes['course_id'] = course_id
if request.POST.get('anonymous', 'false').lower() == 'true':
attributes['anonymous'] = True
if request.POST.get('autowatch', 'false').lower() == 'true':
attributes['auto_subscribe'] = True
response = comment_client.create_sub_comment(comment_id, attributes)
return JsonResponse(response)
def _response_from_attributes(attributes):
return comment_client.create_sub_comment(comment_id, attributes)
return _create_comment(request, course_id, _response_from_attributes)
@comment_author_only
@login_required
......
......@@ -11,9 +11,7 @@ from courseware.courses import check_course
from dateutil.tz import tzlocal
from datehelper import time_ago_in_words
from django_comment_client.utils import get_categorized_discussion_info, \
extract, strip_none, \
JsonResponse
import django_comment_client.utils as utils
from urllib import urlencode
import json
......@@ -24,13 +22,9 @@ import dateutil
THREADS_PER_PAGE = 20
PAGES_NEARBY_DELTA = 2
class HtmlResponse(HttpResponse):
def __init__(self, html=''):
super(HtmlResponse, self).__init__(html, content_type='text/plain')
def render_accordion(request, course, discussion_id):
discussion_info = get_categorized_discussion_info(request, course)
discussion_info = utils.get_categorized_discussion_info(request, course)
context = {
'course': course,
......@@ -63,7 +57,7 @@ def render_discussion(request, course_id, threads, discussion_id=None, \
'pages_nearby_delta': PAGES_NEARBY_DELTA,
'discussion_type': discussion_type,
'base_url': base_url,
'query_params': strip_none(extract(query_params, ['page', 'sort_key', 'sort_order', 'tags', 'text'])),
'query_params': utils.strip_none(utils.extract(query_params, ['page', 'sort_key', 'sort_order', 'tags', 'text'])),
}
context = dict(context.items() + query_params.items())
return render_to_string(template, context)
......@@ -86,9 +80,9 @@ def get_threads(request, course_id, discussion_id):
if query_params['text'] or query_params['tags']: #TODO do tags search without sunspot
query_params['commentable_id'] = discussion_id
threads, page, num_pages = comment_client.search_threads(course_id, recursive=False, query_params=strip_none(query_params))
threads, page, num_pages = comment_client.search_threads(course_id, recursive=False, query_params=utils.strip_none(query_params))
else:
threads, page, num_pages = comment_client.get_threads(discussion_id, recursive=False, query_params=strip_none(query_params))
threads, page, num_pages = comment_client.get_threads(discussion_id, recursive=False, query_params=utils.strip_none(query_params))
query_params['page'] = page
query_params['num_pages'] = num_pages
......@@ -162,7 +156,7 @@ def single_thread(request, course_id, discussion_id, thread_id):
context = {'thread': thread}
html = render_to_string('discussion/_ajax_single_thread.html', context)
return JsonResponse({
return utils.JsonResponse({
'html': html,
'annotated_content_info': annotated_content_info,
})
......
......@@ -116,3 +116,7 @@ class JsonError(HttpResponse):
ensure_ascii=False)
super(JsonError, self).__init__(content,
mimetype='application/json; charset=utf8')
class HtmlResponse(HttpResponse):
def __init__(self, html=''):
super(HtmlResponse, self).__init__(html, content_type='text/plain')
......@@ -108,7 +108,7 @@ $ ->
(text) -> _this.replaceMath(text)
if Markdown?
Markdown.getMathCompatibleConverter = ->
converter = Markdown.getSanitizingConverter()
processor = new MathJaxProcessor()
......@@ -174,3 +174,4 @@ $ ->
text: text
previewSetter: previewSet
editor.run()
editor
......@@ -35,7 +35,7 @@ Discussion = @Discussion
showWatchCheckbox: not Discussion.isSubscribed(thread_id, "thread")
}
$discussionContent.append Mustache.render Discussion.replyTemplate, view
Markdown.makeWmdEditor $local(".reply-body"), "-reply-body-#{id}", Discussion.urlFor('upload')
Discussion.makeWmdEditor $content, $local, "reply-body"
$local(".discussion-submit-post").click -> handleSubmitReply(this)
$local(".discussion-cancel-post").click -> handleCancelReply(this)
$local(".discussion-link").hide()
......@@ -57,7 +57,7 @@ Discussion = @Discussion
else
return
body = $local("#wmd-input-reply-body-#{id}").val()
body = Discussion.getWmdContent $content, $local, "reply-body"
anonymous = false || $local(".discussion-post-anonymously").is(":checked")
autowatch = false || $local(".discussion-auto-watch").is(":checked")
......@@ -70,8 +70,16 @@ Discussion = @Discussion
body: body
anonymous: anonymous
autowatch: autowatch
success: Discussion.formErrorHandler $local(".discussion-errors"), (response, textStatus) ->
Discussion.handleAnchorAndReload(response)
success: Discussion.formErrorHandler($local(".discussion-errors"), (response, textStatus) ->
console.log response
$comment = $(response.html)
$content.children(".comments").prepend($comment)
Discussion.setWmdContent $content, $local, "reply-body", ""
Discussion.initializeContent($comment)
Discussion.bindContentEvents($comment)
$local(".discussion-reply-new").hide()
$discussionContent.attr("status", "normal")
)
dataType: 'json'
handleVote = (elem, value) ->
......@@ -99,7 +107,7 @@ Discussion = @Discussion
tags: $local(".thread-raw-tags").html()
}
$discussionContent.append Mustache.render Discussion.editThreadTemplate, view
Markdown.makeWmdEditor $local(".thread-body-edit"), "-thread-body-edit-#{id}", Discussion.urlFor('update_thread', id)
Discussion.makeWmdEditor $content, $local, "thread-body-edit"
$local(".thread-tags-edit").tagsInput
autocomplete_url: Discussion.urlFor('tags_autocomplete')
autocomplete:
......@@ -115,7 +123,7 @@ Discussion = @Discussion
handleSubmitEditThread = (elem) ->
url = Discussion.urlFor('update_thread', id)
title = $local(".thread-title-edit").val()
body = $local("#wmd-input-thread-body-edit-#{id}").val()
body = Discussion.getWmdContent $content, $local, "thread-body-edit"
tags = $local(".thread-tags-edit").val()
$.ajax
url: url
......@@ -133,13 +141,13 @@ Discussion = @Discussion
else
view = { id: id, body: $local(".comment-raw-body").html() }
$discussionContent.append Mustache.render Discussion.editCommentTemplate, view
Markdown.makeWmdEditor $local(".comment-body-edit"), "-comment-body-edit-#{id}", Discussion.urlFor('update_comment', id)
Discussion.makeWmdEditor $content, $local, "comment-body-edit"
$local(".discussion-submit-update").unbind("click").click -> handleSubmitEditComment(this)
$local(".discussion-cancel-update").unbind("click").click -> handleCancelEdit(this)
handleSubmitEditComment= (elem) ->
url = Discussion.urlFor('update_comment', id)
body = $local("#wmd-input-comment-body-edit-#{id}").val()
body = Discussion.getWmdContent $content, $local, "comment-body-edit"
$.ajax
url: url
data: {body: body}
......@@ -169,6 +177,9 @@ Discussion = @Discussion
$threadTitle = $local(".thread-title")
$showComments = $local(".discussion-show-comments")
if not $showComments.length or not $threadTitle.length
return
rebindHideEvents = ->
$threadTitle.unbind('click').click handleHideSingleThread
$showComments.unbind('click').click handleHideSingleThread
......
......@@ -91,7 +91,7 @@ initializeFollowThread = (index, thread) ->
handleSubmitNewPost = (elem) ->
title = $local(".new-post-title").val()
body = $local("#wmd-input-new-post-body-#{id}").val()
body = Discussion.getWmdContent $discussion, $local, "new-post-body"
tags = $local(".new-post-tags").val()
url = Discussion.urlFor('create_thread', $local(".new-post-form").attr("_id"))
$.post url, {title: title, body: body, tags: tags}, (response, textStatus) ->
......@@ -115,9 +115,9 @@ initializeFollowThread = (index, thread) ->
else
view = { discussion_id: id }
$discussionNonContent.append Mustache.render Discussion.newPostTemplate, view
newPostBody = $(discussion).find(".new-post-body")
newPostBody = $discussion.find(".new-post-body")
if newPostBody.length
Markdown.makeWmdEditor newPostBody, "-new-post-body-#{$(discussion).attr('_id')}", Discussion.urlFor('upload')
Discussion.makeWmdEditor $discussion, $local, "new-post-body"
$local(".new-post-tags").tagsInput Discussion.tagsInputOptions()
......
......@@ -4,82 +4,8 @@ if not @Discussion?
Discussion = @Discussion
###
titleTemplate = """
<a class="thread-title" name="{{id}}" href="javascript:void(0)">{{title}}</a>
"""
threadTemplate: """
<div class="thread" _id="{{id}}">
{{content}}
<div class="comments">
</div>
</div>
"""
commentTemplate: """
<div class="comment" _id="{{id}}">
{{content}}
<div class="comments">
</div>
</div>
"""
contentTemplate: """
<div class="discussion-content">
<div class="discussion-content-wrapper clearfix">
{{vote}}
<div class="discussion-right-wrapper clearfix">
{{title}}
<div class="discussion-content-view">
<div class="content-body {{type}}-body" id="content-body-{{id}}">{{body}}</div>
<div class="content-raw-body {{type}}-raw-body" style="display: none">{{body}}</div>
{{tags}}
{{bottom_bar}}
</div>
</div>
</div>
</div>
"""
tagsTemplate = """
<div class="thread-tags">
</div>
<div class="thread-raw-tags" style="display: none">
"""
###
@Discussion = $.extend @Discussion,
###
renderThread: (thread) ->
rendered_title = Mustache.render titleTemplate, thread
content_view =
tags: rendered_tags
rendered_bottom_bar: rendered_bottom_bar
rendered_title: rendered_title
rendered_vote: rendered_vote
rendered_content = Mustache.render contentTemplate, $.extend(thread, contentView)
Mustache.render threadTemplate, {rendered_content: rendered_content}
renderComment: (comment) ->
commentTemplate: """
"""
###
newPostTemplate: """
<form class="new-post-form" _id="{{discussion_id}}">
<ul class="discussion-errors"></ul>
......
......@@ -3,6 +3,8 @@ if not @Discussion?
Discussion = @Discussion
wmdEditors = {}
@Discussion = $.extend @Discussion,
generateLocal: (elem) ->
......@@ -82,3 +84,28 @@ Discussion = @Discussion
errorsField.append($("<li>").addClass("new-post-form-error").html(error))
else
success(response, textStatus, xhr)
makeWmdEditor: ($content, $local, cls_identifier) ->
elem = $local(".#{cls_identifier}")
id = $content.attr("_id")
appended_id = "-#{cls_identifier}-#{id}"
imageUploadUrl = Discussion.urlFor('upload')
editor = Markdown.makeWmdEditor elem, appended_id, imageUploadUrl
wmdEditors["#{cls_identifier}-#{id}"] = editor
console.log wmdEditors
editor
getWmdEditor: ($content, $local, cls_identifier) ->
id = $content.attr("_id")
wmdEditors["#{cls_identifier}-#{id}"]
getWmdContent: ($content, $local, cls_identifier) ->
id = $content.attr("_id")
$local("#wmd-input-#{cls_identifier}-#{id}").val()
setWmdContent: ($content, $local, cls_identifier, text) ->
id = $content.attr("_id")
$local("#wmd-input-#{cls_identifier}-#{id}").val(text)
console.log wmdEditors
console.log "#{cls_identifier}-#{id}"
wmdEditors["#{cls_identifier}-#{id}"].refreshPreview()
......@@ -7,24 +7,28 @@
<div class="thread" _id="${thread['id']}">
${render_content(thread, "thread", edit_thread=edit_thread, show_comments=show_comments)}
% if show_comments:
${render_comments(thread['children'])}
${render_comments(thread.get('children', []))}
% endif
</div>
</%def>
<%def name="render_comment(comment)">
% if comment['endorsed']:
<div class="comment endorsed" _id="${comment['id']}">
% else:
<div class="comment" _id="${comment['id']}">
% endif
${render_content(comment, "comment")}
<div class="comments">
${render_comments(comment.get('children', []))}
</div>
</div>
</%def>
<%def name="render_comments(comments)">
<div class="comments">
% for comment in comments:
% if comment['endorsed']:
<div class="comment endorsed" _id="${comment['id']}">
% else:
<div class="comment" _id="${comment['id']}">
% endif
${render_content(comment, "comment")}
<div class="comments">
${render_comments(comment['children'])}
</div>
</div>
${render_comment(comment)}
% endfor
</div>
</%def>
......
<%namespace name="renderer" file="_thread.html"/>
${renderer.render_comment(comment)}
<%namespace name="renderer" file="_thread.html"/>
${renderer.render_thread(course_id, thread, edit_thread=True, show_comments=False)}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment