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 ...@@ -15,6 +15,7 @@ from django.core.files.storage import get_storage_class
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
from django.conf import settings from django.conf import settings
from mitxmako.shortcuts import render_to_response, render_to_string
from django_comment_client.utils import JsonResponse, JsonError, extract from django_comment_client.utils import JsonResponse, JsonError, extract
def thread_author_only(fn): def thread_author_only(fn):
...@@ -58,7 +59,15 @@ def create_thread(request, course_id, commentable_id): ...@@ -58,7 +59,15 @@ def create_thread(request, course_id, commentable_id):
if request.POST.get('autowatch', 'false').lower() == 'true': if request.POST.get('autowatch', 'false').lower() == 'true':
attributes['auto_subscribe'] = True attributes['auto_subscribe'] = True
response = comment_client.create_thread(commentable_id, attributes) 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 @thread_author_only
@login_required @login_required
...@@ -68,9 +77,7 @@ def update_thread(request, course_id, thread_id): ...@@ -68,9 +77,7 @@ def update_thread(request, course_id, thread_id):
response = comment_client.update_thread(thread_id, attributes) response = comment_client.update_thread(thread_id, attributes)
return JsonResponse(response) return JsonResponse(response)
@login_required def _create_comment(request, course_id, _response_from_attributes):
@require_POST
def create_comment(request, course_id, thread_id):
attributes = extract(request.POST, ['body']) attributes = extract(request.POST, ['body'])
attributes['user_id'] = request.user.id attributes['user_id'] = request.user.id
attributes['course_id'] = course_id attributes['course_id'] = course_id
...@@ -78,8 +85,24 @@ def create_comment(request, course_id, thread_id): ...@@ -78,8 +85,24 @@ def create_comment(request, course_id, thread_id):
attributes['anonymous'] = True attributes['anonymous'] = True
if request.POST.get('autowatch', 'false').lower() == 'true': if request.POST.get('autowatch', 'false').lower() == 'true':
attributes['auto_subscribe'] = True attributes['auto_subscribe'] = True
response = comment_client.create_comment(thread_id, attributes) response = _response_from_attributes(attributes)
return JsonResponse(response) 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 @thread_author_only
@login_required @login_required
...@@ -107,15 +130,9 @@ def endorse_comment(request, course_id, comment_id): ...@@ -107,15 +130,9 @@ def endorse_comment(request, course_id, comment_id):
@login_required @login_required
@require_POST @require_POST
def create_sub_comment(request, course_id, comment_id): def create_sub_comment(request, course_id, comment_id):
attributes = extract(request.POST, ['body']) def _response_from_attributes(attributes):
attributes['user_id'] = request.user.id return comment_client.create_sub_comment(comment_id, attributes)
attributes['course_id'] = course_id return _create_comment(request, course_id, _response_from_attributes)
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)
@comment_author_only @comment_author_only
@login_required @login_required
......
...@@ -11,9 +11,7 @@ from courseware.courses import check_course ...@@ -11,9 +11,7 @@ from courseware.courses import check_course
from dateutil.tz import tzlocal from dateutil.tz import tzlocal
from datehelper import time_ago_in_words from datehelper import time_ago_in_words
from django_comment_client.utils import get_categorized_discussion_info, \ import django_comment_client.utils as utils
extract, strip_none, \
JsonResponse
from urllib import urlencode from urllib import urlencode
import json import json
...@@ -24,13 +22,9 @@ import dateutil ...@@ -24,13 +22,9 @@ import dateutil
THREADS_PER_PAGE = 20 THREADS_PER_PAGE = 20
PAGES_NEARBY_DELTA = 2 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): 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 = { context = {
'course': course, 'course': course,
...@@ -63,7 +57,7 @@ def render_discussion(request, course_id, threads, discussion_id=None, \ ...@@ -63,7 +57,7 @@ def render_discussion(request, course_id, threads, discussion_id=None, \
'pages_nearby_delta': PAGES_NEARBY_DELTA, 'pages_nearby_delta': PAGES_NEARBY_DELTA,
'discussion_type': discussion_type, 'discussion_type': discussion_type,
'base_url': base_url, '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()) context = dict(context.items() + query_params.items())
return render_to_string(template, context) return render_to_string(template, context)
...@@ -86,9 +80,9 @@ def get_threads(request, course_id, discussion_id): ...@@ -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 if query_params['text'] or query_params['tags']: #TODO do tags search without sunspot
query_params['commentable_id'] = discussion_id 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: 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['page'] = page
query_params['num_pages'] = num_pages query_params['num_pages'] = num_pages
...@@ -162,7 +156,7 @@ def single_thread(request, course_id, discussion_id, thread_id): ...@@ -162,7 +156,7 @@ def single_thread(request, course_id, discussion_id, thread_id):
context = {'thread': thread} context = {'thread': thread}
html = render_to_string('discussion/_ajax_single_thread.html', context) html = render_to_string('discussion/_ajax_single_thread.html', context)
return JsonResponse({ return utils.JsonResponse({
'html': html, 'html': html,
'annotated_content_info': annotated_content_info, 'annotated_content_info': annotated_content_info,
}) })
......
...@@ -116,3 +116,7 @@ class JsonError(HttpResponse): ...@@ -116,3 +116,7 @@ class JsonError(HttpResponse):
ensure_ascii=False) ensure_ascii=False)
super(JsonError, self).__init__(content, super(JsonError, self).__init__(content,
mimetype='application/json; charset=utf8') 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 @@ $ -> ...@@ -108,7 +108,7 @@ $ ->
(text) -> _this.replaceMath(text) (text) -> _this.replaceMath(text)
if Markdown? if Markdown?
Markdown.getMathCompatibleConverter = -> Markdown.getMathCompatibleConverter = ->
converter = Markdown.getSanitizingConverter() converter = Markdown.getSanitizingConverter()
processor = new MathJaxProcessor() processor = new MathJaxProcessor()
...@@ -174,3 +174,4 @@ $ -> ...@@ -174,3 +174,4 @@ $ ->
text: text text: text
previewSetter: previewSet previewSetter: previewSet
editor.run() editor.run()
editor
...@@ -35,7 +35,7 @@ Discussion = @Discussion ...@@ -35,7 +35,7 @@ Discussion = @Discussion
showWatchCheckbox: not Discussion.isSubscribed(thread_id, "thread") showWatchCheckbox: not Discussion.isSubscribed(thread_id, "thread")
} }
$discussionContent.append Mustache.render Discussion.replyTemplate, view $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-submit-post").click -> handleSubmitReply(this)
$local(".discussion-cancel-post").click -> handleCancelReply(this) $local(".discussion-cancel-post").click -> handleCancelReply(this)
$local(".discussion-link").hide() $local(".discussion-link").hide()
...@@ -57,7 +57,7 @@ Discussion = @Discussion ...@@ -57,7 +57,7 @@ Discussion = @Discussion
else else
return return
body = $local("#wmd-input-reply-body-#{id}").val() body = Discussion.getWmdContent $content, $local, "reply-body"
anonymous = false || $local(".discussion-post-anonymously").is(":checked") anonymous = false || $local(".discussion-post-anonymously").is(":checked")
autowatch = false || $local(".discussion-auto-watch").is(":checked") autowatch = false || $local(".discussion-auto-watch").is(":checked")
...@@ -70,8 +70,16 @@ Discussion = @Discussion ...@@ -70,8 +70,16 @@ Discussion = @Discussion
body: body body: body
anonymous: anonymous anonymous: anonymous
autowatch: autowatch autowatch: autowatch
success: Discussion.formErrorHandler $local(".discussion-errors"), (response, textStatus) -> success: Discussion.formErrorHandler($local(".discussion-errors"), (response, textStatus) ->
Discussion.handleAnchorAndReload(response) 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' dataType: 'json'
handleVote = (elem, value) -> handleVote = (elem, value) ->
...@@ -99,7 +107,7 @@ Discussion = @Discussion ...@@ -99,7 +107,7 @@ Discussion = @Discussion
tags: $local(".thread-raw-tags").html() tags: $local(".thread-raw-tags").html()
} }
$discussionContent.append Mustache.render Discussion.editThreadTemplate, view $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 $local(".thread-tags-edit").tagsInput
autocomplete_url: Discussion.urlFor('tags_autocomplete') autocomplete_url: Discussion.urlFor('tags_autocomplete')
autocomplete: autocomplete:
...@@ -115,7 +123,7 @@ Discussion = @Discussion ...@@ -115,7 +123,7 @@ Discussion = @Discussion
handleSubmitEditThread = (elem) -> handleSubmitEditThread = (elem) ->
url = Discussion.urlFor('update_thread', id) url = Discussion.urlFor('update_thread', id)
title = $local(".thread-title-edit").val() 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() tags = $local(".thread-tags-edit").val()
$.ajax $.ajax
url: url url: url
...@@ -133,13 +141,13 @@ Discussion = @Discussion ...@@ -133,13 +141,13 @@ Discussion = @Discussion
else else
view = { id: id, body: $local(".comment-raw-body").html() } view = { id: id, body: $local(".comment-raw-body").html() }
$discussionContent.append Mustache.render Discussion.editCommentTemplate, view $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-submit-update").unbind("click").click -> handleSubmitEditComment(this)
$local(".discussion-cancel-update").unbind("click").click -> handleCancelEdit(this) $local(".discussion-cancel-update").unbind("click").click -> handleCancelEdit(this)
handleSubmitEditComment= (elem) -> handleSubmitEditComment= (elem) ->
url = Discussion.urlFor('update_comment', id) url = Discussion.urlFor('update_comment', id)
body = $local("#wmd-input-comment-body-edit-#{id}").val() body = Discussion.getWmdContent $content, $local, "comment-body-edit"
$.ajax $.ajax
url: url url: url
data: {body: body} data: {body: body}
...@@ -169,6 +177,9 @@ Discussion = @Discussion ...@@ -169,6 +177,9 @@ Discussion = @Discussion
$threadTitle = $local(".thread-title") $threadTitle = $local(".thread-title")
$showComments = $local(".discussion-show-comments") $showComments = $local(".discussion-show-comments")
if not $showComments.length or not $threadTitle.length
return
rebindHideEvents = -> rebindHideEvents = ->
$threadTitle.unbind('click').click handleHideSingleThread $threadTitle.unbind('click').click handleHideSingleThread
$showComments.unbind('click').click handleHideSingleThread $showComments.unbind('click').click handleHideSingleThread
......
...@@ -91,7 +91,7 @@ initializeFollowThread = (index, thread) -> ...@@ -91,7 +91,7 @@ initializeFollowThread = (index, thread) ->
handleSubmitNewPost = (elem) -> handleSubmitNewPost = (elem) ->
title = $local(".new-post-title").val() 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() tags = $local(".new-post-tags").val()
url = Discussion.urlFor('create_thread', $local(".new-post-form").attr("_id")) url = Discussion.urlFor('create_thread', $local(".new-post-form").attr("_id"))
$.post url, {title: title, body: body, tags: tags}, (response, textStatus) -> $.post url, {title: title, body: body, tags: tags}, (response, textStatus) ->
...@@ -115,9 +115,9 @@ initializeFollowThread = (index, thread) -> ...@@ -115,9 +115,9 @@ initializeFollowThread = (index, thread) ->
else else
view = { discussion_id: id } view = { discussion_id: id }
$discussionNonContent.append Mustache.render Discussion.newPostTemplate, view $discussionNonContent.append Mustache.render Discussion.newPostTemplate, view
newPostBody = $(discussion).find(".new-post-body") newPostBody = $discussion.find(".new-post-body")
if newPostBody.length 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() $local(".new-post-tags").tagsInput Discussion.tagsInputOptions()
......
...@@ -4,82 +4,8 @@ if not @Discussion? ...@@ -4,82 +4,8 @@ if not @Discussion?
Discussion = @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, @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: """ newPostTemplate: """
<form class="new-post-form" _id="{{discussion_id}}"> <form class="new-post-form" _id="{{discussion_id}}">
<ul class="discussion-errors"></ul> <ul class="discussion-errors"></ul>
......
...@@ -3,6 +3,8 @@ if not @Discussion? ...@@ -3,6 +3,8 @@ if not @Discussion?
Discussion = @Discussion Discussion = @Discussion
wmdEditors = {}
@Discussion = $.extend @Discussion, @Discussion = $.extend @Discussion,
generateLocal: (elem) -> generateLocal: (elem) ->
...@@ -82,3 +84,28 @@ Discussion = @Discussion ...@@ -82,3 +84,28 @@ Discussion = @Discussion
errorsField.append($("<li>").addClass("new-post-form-error").html(error)) errorsField.append($("<li>").addClass("new-post-form-error").html(error))
else else
success(response, textStatus, xhr) 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 @@ ...@@ -7,24 +7,28 @@
<div class="thread" _id="${thread['id']}"> <div class="thread" _id="${thread['id']}">
${render_content(thread, "thread", edit_thread=edit_thread, show_comments=show_comments)} ${render_content(thread, "thread", edit_thread=edit_thread, show_comments=show_comments)}
% if show_comments: % if show_comments:
${render_comments(thread['children'])} ${render_comments(thread.get('children', []))}
% endif % endif
</div> </div>
</%def> </%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)"> <%def name="render_comments(comments)">
<div class="comments"> <div class="comments">
% for comment in comments: % for comment in comments:
% if comment['endorsed']: ${render_comment(comment)}
<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>
% endfor % endfor
</div> </div>
</%def> </%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