Commit 26536902 by David Ormsbee

Merge pull request #520 from MITx/feature/rocky/discussion

add user profile and fixed edit
parents 22cbc1bd 6de05997
...@@ -21,7 +21,6 @@ from django.contrib.auth.models import User ...@@ -21,7 +21,6 @@ from django.contrib.auth.models import User
from mitxmako.shortcuts import render_to_response, render_to_string from mitxmako.shortcuts import render_to_response, render_to_string
from courseware.courses import get_course_with_access from courseware.courses import get_course_with_access
from django_comment_client.utils import JsonResponse, JsonError, extract from django_comment_client.utils import JsonResponse, JsonError, extract
from django_comment_client.permissions import check_permissions_by_view from django_comment_client.permissions import check_permissions_by_view
...@@ -282,7 +281,7 @@ def update_moderator_status(request, course_id, user_id): ...@@ -282,7 +281,7 @@ def update_moderator_status(request, course_id, user_id):
'course_id': course_id, 'course_id': course_id,
'user': request.user, 'user': request.user,
'django_user': user, 'django_user': user,
'discussion_user': discussion_user.to_dict(), 'profiled_user': discussion_user.to_dict(),
} }
return JsonResponse({ return JsonResponse({
'html': render_to_string('discussion/ajax_user_profile.html', context) 'html': render_to_string('discussion/ajax_user_profile.html', context)
...@@ -298,10 +297,13 @@ def search_similar_threads(request, course_id, commentable_id): ...@@ -298,10 +297,13 @@ def search_similar_threads(request, course_id, commentable_id):
'text': text, 'text': text,
'commentable_id': commentable_id, 'commentable_id': commentable_id,
} }
result = cc.search_similar_threads(course_id, recursive=False, query_params=query_params) threads = cc.search_similar_threads(course_id, recursive=False, query_params=query_params)
return JsonResponse(result)
else: else:
return JsonResponse([]) theads = []
context = { 'threads': map(utils.extend_content, threads) }
return JsonResponse({
'html': render_to_string('discussion/_similar_posts.html', context)
})
@require_GET @require_GET
def tags_autocomplete(request, course_id): def tags_autocomplete(request, course_id):
...@@ -334,8 +336,8 @@ def upload(request, course_id):#ajax upload file to a question or answer ...@@ -334,8 +336,8 @@ def upload(request, course_id):#ajax upload file to a question or answer
# check file type # check file type
f = request.FILES['file-upload'] f = request.FILES['file-upload']
file_extension = os.path.splitext(f.name)[1].lower() file_extension = os.path.splitext(f.name)[1].lower()
if not file_extension in settings.DISCUSSION_ALLOWED_UPLOAD_FILE_TYPES: if not file_extension in cc_settings.ALLOWED_UPLOAD_FILE_TYPES:
file_types = "', '".join(settings.DISCUSSION_ALLOWED_UPLOAD_FILE_TYPES) file_types = "', '".join(cc_settings.ALLOWED_UPLOAD_FILE_TYPES)
msg = _("allowed file types are '%(file_types)s'") % \ msg = _("allowed file types are '%(file_types)s'") % \
{'file_types': file_types} {'file_types': file_types}
raise exceptions.PermissionDenied(msg) raise exceptions.PermissionDenied(msg)
...@@ -354,15 +356,16 @@ def upload(request, course_id):#ajax upload file to a question or answer ...@@ -354,15 +356,16 @@ def upload(request, course_id):#ajax upload file to a question or answer
# check file size # check file size
# byte # byte
size = file_storage.size(new_file_name) size = file_storage.size(new_file_name)
if size > settings.ASKBOT_MAX_UPLOAD_FILE_SIZE: if size > cc_settings.MAX_UPLOAD_FILE_SIZE:
file_storage.delete(new_file_name) file_storage.delete(new_file_name)
msg = _("maximum upload file size is %(file_size)sK") % \ msg = _("maximum upload file size is %(file_size)sK") % \
{'file_size': settings.ASKBOT_MAX_UPLOAD_FILE_SIZE} {'file_size': cc_settings.MAX_UPLOAD_FILE_SIZE}
raise exceptions.PermissionDenied(msg) raise exceptions.PermissionDenied(msg)
except exceptions.PermissionDenied, e: except exceptions.PermissionDenied, e:
error = unicode(e) error = unicode(e)
except Exception, e: except Exception, e:
print e
logging.critical(unicode(e)) logging.critical(unicode(e))
error = _('Error uploading file. Please contact the site administrator. Thank you.') error = _('Error uploading file. Please contact the site administrator. Thank you.')
......
...@@ -83,7 +83,7 @@ def render_discussion(request, course_id, threads, *args, **kwargs): ...@@ -83,7 +83,7 @@ def render_discussion(request, course_id, threads, *args, **kwargs):
'base_url': base_url, 'base_url': base_url,
'query_params': strip_blank(strip_none(extract(query_params, ['page', 'sort_key', 'sort_order', 'tags', 'text']))), 'query_params': strip_blank(strip_none(extract(query_params, ['page', 'sort_key', 'sort_order', 'tags', 'text']))),
'annotated_content_info': json.dumps(annotated_content_info), 'annotated_content_info': json.dumps(annotated_content_info),
'discussion_data': json.dumps({ discussion_id: threads }), 'discussion_data': json.dumps({ (discussion_id or user_id): threads })
} }
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)
...@@ -250,7 +250,10 @@ def user_profile(request, course_id, user_id): ...@@ -250,7 +250,10 @@ def user_profile(request, course_id, user_id):
content = render_user_discussion(request, course_id, threads, user_id=user_id, query_params=query_params) content = render_user_discussion(request, course_id, threads, user_id=user_id, query_params=query_params)
if request.is_ajax(): if request.is_ajax():
return utils.HtmlResponse(content) return utils.JsonResponse({
'html': content,
'discussionData': threads,
})
else: else:
context = { context = {
'course': course, 'course': course,
......
...@@ -12,7 +12,7 @@ import urllib ...@@ -12,7 +12,7 @@ import urllib
import os import os
def pluralize(singular_term, count): def pluralize(singular_term, count):
if int(count) >= 2: if int(count) >= 2 or int(count) == 0:
return singular_term + 's' return singular_term + 's'
return singular_term return singular_term
...@@ -33,24 +33,10 @@ def include_mustache_templates(): ...@@ -33,24 +33,10 @@ def include_mustache_templates():
file_contents = map(read_file, filter(valid_file_name, os.listdir(mustache_dir))) file_contents = map(read_file, filter(valid_file_name, os.listdir(mustache_dir)))
return '\n'.join(map(wrap_in_tag, map(strip_file_name, file_contents))) return '\n'.join(map(wrap_in_tag, map(strip_file_name, file_contents)))
def permalink(content):
if content['type'] == 'thread':
return reverse('django_comment_client.forum.views.single_thread',
args=[content['course_id'], content['commentable_id'], content['id']])
else:
return reverse('django_comment_client.forum.views.single_thread',
args=[content['course_id'], content['commentable_id'], content['thread_id']]) + '#' + content['id']
def render_content(content, additional_context={}): def render_content(content, additional_context={}):
content_info = {
'displayed_title': content.get('highlighted_title') or content.get('title', ''),
'displayed_body': content.get('highlighted_body') or content.get('body', ''),
'raw_tags': ','.join(content.get('tags', [])),
'permalink': permalink(content),
}
context = { context = {
'content': merge_dict(content, content_info), 'content': extend_content(content),
content['type']: True, content['type']: True,
} }
context = merge_dict(context, additional_context) context = merge_dict(context, additional_context)
......
...@@ -7,7 +7,8 @@ import inspect ...@@ -7,7 +7,8 @@ import inspect
def pluralize(content, text): def pluralize(content, text):
num, word = text.split(' ') num, word = text.split(' ')
if int(num or '0') >= 2: num = int(num or '0')
if num >= 2 or num == 0:
return word + 's' return word + 's'
else: else:
return word return word
......
from django.conf import settings
MAX_COMMENT_DEPTH = None
MAX_UPLOAD_FILE_SIZE = 1024 * 1024 #result in bytes
ALLOWED_UPLOAD_FILE_TYPES = ('.jpg', '.jpeg', '.gif', '.bmp', '.png', '.tiff')
if hasattr(settings, 'DISCUSSION_SETTINGS'):
MAX_COMMENT_DEPTH = settings.DISCUSSION_SETTINGS.get('MAX_COMMENT_DEPTH')
MAX_UPLOAD_FILE_SIZE = settings.DISCUSSION_SETTINGS.get('MAX_UPLOAD_FILE_SIZE') or MAX_UPLOAD_FILE_SIZE
ALLOWED_UPLOAD_FILE_TYPES = settings.DISCUSSION_SETTINGS.get('ALLOWED_UPLOAD_FILE_TYPES') or ALLOWED_UPLOAD_FILE_TYPES
...@@ -197,3 +197,20 @@ def url_for_tags(course_id, tags): ...@@ -197,3 +197,20 @@ def url_for_tags(course_id, tags):
def render_mustache(template_name, dictionary, *args, **kwargs): def render_mustache(template_name, dictionary, *args, **kwargs):
template = middleware.lookup['main'].get_template(template_name).source template = middleware.lookup['main'].get_template(template_name).source
return pystache.render(template, dictionary) return pystache.render(template, dictionary)
def permalink(content):
if content['type'] == 'thread':
return reverse('django_comment_client.forum.views.single_thread',
args=[content['course_id'], content['commentable_id'], content['id']])
else:
return reverse('django_comment_client.forum.views.single_thread',
args=[content['course_id'], content['commentable_id'], content['thread_id']]) + '#' + content['id']
def extend_content(content):
content_info = {
'displayed_title': content.get('highlighted_title') or content.get('title', ''),
'displayed_body': content.get('highlighted_body') or content.get('body', ''),
'raw_tags': ','.join(content.get('tags', [])),
'permalink': permalink(content),
}
return merge_dict(content, content_info)
class @Content extends Backbone.Model if Backbone?
class @Content extends Backbone.Model
template: -> DiscussionUtil.getTemplate('_content') template: -> DiscussionUtil.getTemplate('_content')
actions: actions:
editable: '.admin-edit' editable: '.admin-edit'
can_reply: '.discussion-reply' can_reply: '.discussion-reply'
can_endorse: '.admin-endorse' can_endorse: '.admin-endorse'
can_delete: '.admin-delete' can_delete: '.admin-delete'
can_openclose: '.admin-openclose' can_openclose: '.admin-openclose'
urlMappers: {} urlMappers: {}
urlFor: (name) -> urlFor: (name) ->
@urlMappers[name].apply(@) @urlMappers[name].apply(@)
can: (action) -> can: (action) ->
DiscussionUtil.getContentInfo @id, action DiscussionUtil.getContentInfo @id, action
updateInfo: (info) -> updateInfo: (info) ->
@set('ability', info.ability) @set('ability', info.ability)
@set('voted', info.voted) @set('voted', info.voted)
@set('subscribed', info.subscribed) @set('subscribed', info.subscribed)
addComment: (comment, options) -> addComment: (comment, options) ->
options ||= {} options ||= {}
if not options.silent if not options.silent
thread = @get('thread')
comments_count = parseInt(thread.get('comments_count'))
thread.set('comments_count', comments_count + 1)
@get('children').push comment
model = new Comment $.extend {}, comment, { thread: @get('thread') }
@get('comments').add model
model
removeComment: (comment) ->
thread = @get('thread') thread = @get('thread')
comments_count = parseInt(thread.get('comments_count')) comments_count = parseInt(thread.get('comments_count'))
thread.set('comments_count', comments_count + 1) thread.set('comments_count', comments_count - 1 - comment.getCommentsCount())
@get('children').push comment
model = new Comment $.extend {}, comment, { thread: @get('thread') }
@get('comments').add model
model
removeComment: (comment) ->
thread = @get('thread')
comments_count = parseInt(thread.get('comments_count'))
thread.set('comments_count', comments_count - 1 - comment.getCommentsCount())
resetComments: (children) ->
@set 'children', []
@set 'comments', new Comments()
for comment in (children || [])
@addComment comment, { silent: true }
initialize: ->
DiscussionUtil.addContent @id, @
@resetComments(@get('children'))
class @ContentView extends Backbone.View
$: (selector) ->
@$local.find(selector)
partial:
endorsed: (endorsed) ->
if endorsed
@$el.addClass("endorsed")
else
@$el.removeClass("endorsed")
closed: (closed) -> # we should just re-render the whole thread, or update according to new abilities
if closed
@$el.addClass("closed")
@$(".admin-openclose").text "Re-open Thread"
else
@$el.removeClass("closed")
@$(".admin-openclose").text "Close Thread"
voted: (voted) -> resetComments: (children) ->
@$(".discussion-vote-up").removeClass("voted") if voted != "up" @set 'children', []
@$(".discussion-vote-down").removeClass("voted") if voted != "down" @set 'comments', new Comments()
@$(".discussion-vote-#{voted}").addClass("voted") if voted in ["up", "down"] for comment in (children || [])
@addComment comment, { silent: true }
votes_point: (votes_point) -> initialize: ->
@$(".discussion-votes-point").html(votes_point) DiscussionUtil.addContent @id, @
@resetComments(@get('children'))
comments_count: (comments_count) ->
@$(".comments-count").html(comments_count)
subscribed: (subscribed) ->
if subscribed
@$(".discussion-follow-thread").addClass("discussion-unfollow-thread").html("Unfollow")
else
@$(".discussion-follow-thread").removeClass("discussion-unfollow-thread").html("Follow")
ability: (ability) ->
for action, elemSelector of @model.actions
if not ability[action]
@$(elemSelector).parent().remove()
$discussionContent: ->
@_discussionContent ||= @$el.children(".discussion-content")
$showComments: ->
@_showComments ||= @$(".discussion-show-comments")
updateShowComments: ->
if @showed
@$showComments().html @$showComments().html().replace "Show", "Hide"
else
@$showComments().html @$showComments().html().replace "Hide", "Show"
retrieved: -> class @ContentView extends Backbone.View
@$showComments().hasClass("retrieved")
$: (selector) ->
hideSingleThread: (event) -> @$local.find(selector)
@$el.children(".comments").hide()
@showed = false partial:
@updateShowComments() endorsed: (endorsed) ->
if endorsed
showSingleThread: (event) -> @$el.addClass("endorsed")
if @retrieved() else
@$el.children(".comments").show() @$el.removeClass("endorsed")
@showed = true
closed: (closed) -> # we should just re-render the whole thread, or update according to new abilities
if closed
@$el.addClass("closed")
@$(".admin-openclose").text "Re-open Thread"
else
@$el.removeClass("closed")
@$(".admin-openclose").text "Close Thread"
voted: (voted) ->
@$(".discussion-vote-up").removeClass("voted") if voted != "up"
@$(".discussion-vote-down").removeClass("voted") if voted != "down"
@$(".discussion-vote-#{voted}").addClass("voted") if voted in ["up", "down"]
votes_point: (votes_point) ->
@$(".discussion-votes-point").html(votes_point)
comments_count: (comments_count) ->
@$(".comments-count").html(comments_count)
subscribed: (subscribed) ->
if subscribed
@$(".discussion-follow-thread").addClass("discussion-unfollow-thread").html("Unfollow")
else
@$(".discussion-follow-thread").removeClass("discussion-unfollow-thread").html("Follow")
ability: (ability) ->
for action, elemSelector of @model.actions
if not ability[action]
@$(elemSelector).parent().remove()
$discussionContent: ->
@_discussionContent ||= @$el.children(".discussion-content")
$showComments: ->
@_showComments ||= @$(".discussion-show-comments")
updateShowComments: ->
if @showed
@$showComments().html @$showComments().html().replace "Show", "Hide"
else
@$showComments().html @$showComments().html().replace "Hide", "Show"
retrieved: ->
@$showComments().hasClass("retrieved")
hideSingleThread: (event) ->
@$el.children(".comments").hide()
@showed = false
@updateShowComments() @updateShowComments()
else
$elem = $.merge @$(".thread-title"), @$showComments() showSingleThread: (event) ->
url = @model.urlFor('retrieve') if @retrieved()
DiscussionUtil.get $elem, url, {}, (response, textStatus) => @$el.children(".comments").show()
@showed = true @showed = true
@updateShowComments() @updateShowComments()
@$showComments().addClass("retrieved") else
@$el.children(".comments").replaceWith response.html $elem = $.merge @$(".thread-title"), @$showComments()
@model.resetComments response.content.children url = @model.urlFor('retrieve')
@initCommentViews() DiscussionUtil.get $elem, url, {}, (response, textStatus) =>
DiscussionUtil.bulkUpdateContentInfo response.annotated_content_info @showed = true
@updateShowComments()
toggleSingleThread: (event) -> @$showComments().addClass("retrieved")
if @showed @$el.children(".comments").replaceWith response.html
@hideSingleThread(event) @model.resetComments response.content.children
else @initCommentViews()
@showSingleThread(event) DiscussionUtil.bulkUpdateContentInfo response.annotated_content_info
initCommentViews: -> toggleSingleThread: (event) ->
@$el.children(".comments").children(".comment").each (index, elem) => if @showed
model = @model.get('comments').find $(elem).attr("_id") @hideSingleThread(event)
if not model.view else
commentView = new CommentView el: elem, model: model @showSingleThread(event)
reply: -> initCommentViews: ->
if @model.get('type') == 'thread' @$el.children(".comments").children(".comment").each (index, elem) =>
@showSingleThread() model = @model.get('comments').find $(elem).attr("_id")
$replyView = @$(".discussion-reply-new") if not model.view
if $replyView.length commentView = new CommentView el: elem, model: model
$replyView.show()
else reply: ->
view = {} if @model.get('type') == 'thread'
view.id = @model.id @showSingleThread()
view.showWatchCheckbox = not @model.get('thread').get('subscribed') $replyView = @$(".discussion-reply-new")
html = Mustache.render DiscussionUtil.getTemplate('_reply'), view if $replyView.length
@$discussionContent().append html $replyView.show()
DiscussionUtil.makeWmdEditor @$el, $.proxy(@$, @), "reply-body" else
@$(".discussion-submit-post").click $.proxy(@submitReply, @) view = {}
@$(".discussion-cancel-post").click $.proxy(@cancelReply, @) view.id = @model.id
@$(".discussion-reply").hide() view.showWatchCheckbox = not @model.get('thread').get('subscribed')
@$(".discussion-edit").hide() html = Mustache.render DiscussionUtil.getTemplate('_reply'), view
@$discussionContent().append html
submitReply: (event) -> DiscussionUtil.makeWmdEditor @$el, $.proxy(@$, @), "reply-body"
url = @model.urlFor('reply') @$(".discussion-submit-post").click $.proxy(@submitReply, @)
@$(".discussion-cancel-post").click $.proxy(@cancelReply, @)
body = DiscussionUtil.getWmdContent @$el, $.proxy(@$, @), "reply-body" @$(".discussion-reply").hide()
@$(".discussion-edit").hide()
anonymous = false || @$(".discussion-post-anonymously").is(":checked")
autowatch = false || @$(".discussion-auto-watch").is(":checked") submitReply: (event) ->
url = @model.urlFor('reply')
DiscussionUtil.safeAjax
$elem: $(event.target) body = DiscussionUtil.getWmdContent @$el, $.proxy(@$, @), "reply-body"
url: url
type: "POST" anonymous = false || @$(".discussion-post-anonymously").is(":checked")
dataType: 'json' autowatch = false || @$(".discussion-auto-watch").is(":checked")
data:
body: body DiscussionUtil.safeAjax
anonymous: anonymous $elem: $(event.target)
auto_subscribe: autowatch url: url
error: DiscussionUtil.formErrorHandler @$(".discussion-errors") type: "POST"
success: (response, textStatus) => dataType: 'json'
DiscussionUtil.clearFormErrors @$(".discussion-errors") data:
$comment = $(response.html) body: body
@$el.children(".comments").prepend $comment anonymous: anonymous
DiscussionUtil.setWmdContent @$el, $.proxy(@$, @), "reply-body", "" auto_subscribe: autowatch
comment = @model.addComment response.content error: DiscussionUtil.formErrorHandler @$(".discussion-errors")
commentView = new CommentView el: $comment[0], model: comment success: (response, textStatus) =>
comment.updateInfo response.annotated_content_info DiscussionUtil.clearFormErrors @$(".discussion-errors")
@cancelReply() $comment = $(response.html)
@$el.children(".comments").prepend $comment
cancelReply: -> DiscussionUtil.setWmdContent @$el, $.proxy(@$, @), "reply-body", ""
$replyView = @$(".discussion-reply-new") comment = @model.addComment response.content
if $replyView.length commentView = new CommentView el: $comment[0], model: comment
$replyView.hide() comment.updateInfo response.annotated_content_info
@$(".discussion-reply").show() @cancelReply()
@$(".discussion-edit").show()
cancelReply: ->
unvote: (event) -> $replyView = @$(".discussion-reply-new")
url = @model.urlFor('unvote') if $replyView.length
$elem = @$(".discussion-vote") $replyView.hide()
DiscussionUtil.post $elem, url, {}, (response, textStatus) => @$(".discussion-reply").show()
@model.set('voted', '') @$(".discussion-edit").show()
@model.set('votes_point', response.votes.point)
unvote: (event) ->
vote: (event, value) -> url = @model.urlFor('unvote')
url = @model.urlFor("#{value}vote") $elem = @$(".discussion-vote")
$elem = @$(".discussion-vote") DiscussionUtil.post $elem, url, {}, (response, textStatus) =>
DiscussionUtil.post $elem, url, {}, (response, textStatus) => @model.set('voted', '')
@model.set('voted', value) @model.set('votes_point', response.votes.point)
@model.set('votes_point', response.votes.point)
vote: (event, value) ->
toggleVote: (event) -> url = @model.urlFor("#{value}vote")
$elem = $(event.target) $elem = @$(".discussion-vote")
value = $elem.attr("value") DiscussionUtil.post $elem, url, {}, (response, textStatus) =>
if @model.get("voted") == value @model.set('voted', value)
@unvote(event) @model.set('votes_point', response.votes.point)
else
@vote(event, value) toggleVote: (event) ->
$elem = $(event.target)
toggleEndorse: (event) -> value = $elem.attr("value")
$elem = $(event.target) if @model.get("voted") == value
url = @model.urlFor('endorse') @unvote(event)
endorsed = @model.get('endorsed') else
data = { endorsed: not endorsed } @vote(event, value)
DiscussionUtil.post $elem, url, data, (response, textStatus) =>
@model.set('endorsed', not endorsed) toggleEndorse: (event) ->
$elem = $(event.target)
toggleFollow: (event) -> url = @model.urlFor('endorse')
$elem = $(event.target) endorsed = @model.get('endorsed')
subscribed = @model.get('subscribed') data = { endorsed: not endorsed }
if subscribed DiscussionUtil.post $elem, url, data, (response, textStatus) =>
url = @model.urlFor('unfollow') @model.set('endorsed', not endorsed)
else
url = @model.urlFor('follow') toggleFollow: (event) ->
DiscussionUtil.post $elem, url, {}, (response, textStatus) => $elem = $(event.target)
@model.set('subscribed', not subscribed) subscribed = @model.get('subscribed')
if subscribed
toggleClosed: (event) -> url = @model.urlFor('unfollow')
$elem = $(event.target) else
url = @model.urlFor('close') url = @model.urlFor('follow')
closed = @model.get('closed') DiscussionUtil.post $elem, url, {}, (response, textStatus) =>
data = { closed: not closed } @model.set('subscribed', not subscribed)
DiscussionUtil.post $elem, url, data, (response, textStatus) =>
@model.set('closed', not closed) toggleClosed: (event) ->
$elem = $(event.target)
edit: (event) -> url = @model.urlFor('close')
@$(".discussion-content-wrapper").hide() closed = @model.get('closed')
$editView = @$(".discussion-content-edit") data = { closed: not closed }
if $editView.length DiscussionUtil.post $elem, url, data, (response, textStatus) =>
$editView.show() @model.set('closed', not closed)
else
view = {} edit: (event) ->
view.id = @model.id @$(".discussion-content-wrapper").hide()
$editView = @$(".discussion-content-edit")
if $editView.length
$editView.show()
else
view = {}
view.id = @model.id
if @model.get('type') == 'thread'
view.title = @$(".thread-raw-title").html()
view.body = @$(".thread-raw-body").html()
view.tags = @$(".thread-raw-tags").html()
else
view.body = @$(".comment-raw-body").html()
@$discussionContent().append Mustache.render DiscussionUtil.getTemplate("_edit_#{@model.get('type')}"), view
DiscussionUtil.makeWmdEditor @$el, $.proxy(@$, @), "#{@model.get('type')}-body-edit"
@$(".thread-tags-edit").tagsInput DiscussionUtil.tagsInputOptions()
@$(".discussion-submit-update").unbind("click").click $.proxy(@submitEdit, @)
@$(".discussion-cancel-update").unbind("click").click $.proxy(@cancelEdit, @)
submitEdit: (event) ->
url = @model.urlFor('update')
data = {}
if @model.get('type') == 'thread'
data.title = @$(".thread-title-edit").val()
data.body = DiscussionUtil.getWmdContent @$el, $.proxy(@$, @), "thread-body-edit"
data.tags = @$(".thread-tags-edit").val()
else
data.body = DiscussionUtil.getWmdContent @$el, $.proxy(@$, @), "comment-body-edit"
DiscussionUtil.safeAjax
$elem: $(event.target)
url: url
type: "POST"
dataType: 'json'
data: data
error: DiscussionUtil.formErrorHandler @$(".discussion-update-errors")
success: (response, textStatus) =>
DiscussionUtil.clearFormErrors @$(".discussion-update-errors")
@$discussionContent().replaceWith(response.html)
@model.set response.content
@model.updateInfo response.annotated_content_info
cancelEdit: (event) ->
@$(".discussion-content-edit").hide()
@$(".discussion-content-wrapper").show()
delete: (event) ->
url = @model.urlFor('delete')
if @model.get('type') == 'thread' if @model.get('type') == 'thread'
view.title = @$(".thread-raw-title").html() c = confirm "Are you sure to delete thread \"#{@model.get('title')}\"?"
view.body = @$(".thread-raw-body").html()
view.tags = @$(".thread-raw-tags").html()
else else
view.body = @$(".comment-raw-body").html() c = confirm "Are you sure to delete this comment? "
@$discussionContent().append Mustache.render DiscussionUtil.getTemplate("_edit_#{@model.get('type')}"), view if not c
Discussion.makeWmdEditor @$el, $.proxy(@$, @), "#{@model.get('type')}-body-edit" return
@$(".thread-tags-edit").tagsInput DiscussionUtil.tagsInputOptions() $elem = $(event.target)
@$(".discussion-submit-update").unbind("click").click $.proxy(@submitEdit, @) DiscussionUtil.post $elem, url, {}, (response, textStatus) =>
@$(".discussion-cancel-update").unbind("click").click $.proxy(@cancelEdit, @) @$el.remove()
@model.get('thread').removeComment(@model)
submitEdit: (event) ->
events:
url = @model.urlFor('update') "click .discussion-follow-thread": "toggleFollow"
data = {} "click .thread-title": "toggleSingleThread"
if @model.get('type') == 'thread' "click .discussion-show-comments": "toggleSingleThread"
data.title = @$(".thread-title-edit").val() "click .discussion-reply-thread": "reply"
data.body = DiscussionUtil.getWmdContent @$el, $.proxy(@$, @), "thread-body-edit" "click .discussion-reply-comment": "reply"
data.tags = @$(".thread-tags-edit").val() "click .discussion-cancel-reply": "cancelReply"
else "click .discussion-vote-up": "toggleVote"
data.body = DiscussionUtil.getWmdContent @$el, $.proxy(@$, @), "comment-body-edit" "click .discussion-vote-down": "toggleVote"
DiscussionUtil.safeAjax "click .admin-endorse": "toggleEndorse"
$elem: $(event.target) "click .admin-openclose": "toggleClosed"
url: url "click .admin-edit": "edit"
type: "POST" "click .admin-delete": "delete"
dataType: 'json'
data: data initLocal: ->
error: DiscussionUtil.formErrorHandler @$(".discussion-update-errors") @$local = @$el.children(".local")
success: (response, textStatus) => @$delegateElement = @$local
DiscussionUtil.clearFormErrors @$(".discussion-update-errors")
@$discussionContent().replaceWith(response.html) initTitle: ->
@model.set response.content $contentTitle = @$(".thread-title")
@model.updateInfo response.annotated_content_info if $contentTitle.length
$contentTitle.html DiscussionUtil.unescapeHighlightTag DiscussionUtil.stripLatexHighlight $contentTitle.html()
cancelEdit: (event) ->
@$(".discussion-content-edit").hide() initBody: ->
@$(".discussion-content-wrapper").show() $contentBody = @$(".content-body")
$contentBody.html DiscussionUtil.postMathJaxProcessor DiscussionUtil.markdownWithHighlight $contentBody.html()
delete: (event) -> MathJax.Hub.Queue ["Typeset", MathJax.Hub, $contentBody.attr("id")]
url = @model.urlFor('delete')
if @model.get('type') == 'thread' initTimeago: ->
c = confirm "Are you sure to delete thread \"#{@model.get('title')}\"?" @$("span.timeago").timeago()
else
c = confirm "Are you sure to delete this comment? " renderPartial: ->
if not c for attr, value of @model.changedAttributes()
return if @partial[attr]
$elem = $(event.target) @partial[attr].apply(@, [value])
DiscussionUtil.post $elem, url, {}, (response, textStatus) =>
@$el.remove() initBindings: ->
@model.get('thread').removeComment(@model) @model.view = @
@model.bind('change', @renderPartial, @)
initialize: ->
@initBindings()
@initLocal()
@initTimeago()
@initTitle()
@initBody()
@initCommentViews()
events: class @Thread extends @Content
"click .discussion-follow-thread": "toggleFollow" urlMappers:
"click .thread-title": "toggleSingleThread" 'retrieve' : -> DiscussionUtil.urlFor('retrieve_single_thread', @discussion.id, @id)
"click .discussion-show-comments": "toggleSingleThread" 'reply' : -> DiscussionUtil.urlFor('create_comment', @id)
"click .discussion-reply-thread": "reply" 'unvote' : -> DiscussionUtil.urlFor("undo_vote_for_#{@get('type')}", @id)
"click .discussion-reply-comment": "reply" 'upvote' : -> DiscussionUtil.urlFor("upvote_#{@get('type')}", @id)
"click .discussion-cancel-reply": "cancelReply" 'downvote' : -> DiscussionUtil.urlFor("downvote_#{@get('type')}", @id)
"click .discussion-vote-up": "toggleVote" 'close' : -> DiscussionUtil.urlFor('openclose_thread', @id)
"click .discussion-vote-down": "toggleVote" 'update' : -> DiscussionUtil.urlFor('update_thread', @id)
"click .admin-endorse": "toggleEndorse" 'delete' : -> DiscussionUtil.urlFor('delete_thread', @id)
"click .admin-openclose": "toggleClosed" 'follow' : -> DiscussionUtil.urlFor('follow_thread', @id)
"click .admin-edit": "edit" 'unfollow' : -> DiscussionUtil.urlFor('unfollow_thread', @id)
"click .admin-delete": "delete"
initialize: ->
initLocal: -> @set('thread', @)
@$local = @$el.children(".local") super()
@$delegateElement = @$local
class @ThreadView extends @ContentView
initTitle: ->
$contentTitle = @$(".thread-title") class @Comment extends @Content
if $contentTitle.length urlMappers:
$contentTitle.html DiscussionUtil.unescapeHighlightTag DiscussionUtil.stripLatexHighlight $contentTitle.html() 'reply': -> DiscussionUtil.urlFor('create_sub_comment', @id)
'unvote': -> DiscussionUtil.urlFor("undo_vote_for_#{@get('type')}", @id)
initBody: -> 'upvote': -> DiscussionUtil.urlFor("upvote_#{@get('type')}", @id)
$contentBody = @$(".content-body") 'downvote': -> DiscussionUtil.urlFor("downvote_#{@get('type')}", @id)
$contentBody.html DiscussionUtil.postMathJaxProcessor DiscussionUtil.markdownWithHighlight $contentBody.html() 'endorse': -> DiscussionUtil.urlFor('endorse_comment', @id)
MathJax.Hub.Queue ["Typeset", MathJax.Hub, $contentBody.attr("id")] 'update': -> DiscussionUtil.urlFor('update_comment', @id)
'delete': -> DiscussionUtil.urlFor('delete_comment', @id)
initTimeago: ->
@$("span.timeago").timeago() getCommentsCount: ->
count = 0
initPermalink: -> @get('comments').each (comment) ->
@$(".discussion-permanent-link").attr "href", @model.permalink() count += comment.getCommentsCount() + 1
count
renderPartial: ->
for attr, value of @model.changedAttributes() class @CommentView extends @ContentView
if @partial[attr]
@partial[attr].apply(@, [value]) class @Comments extends Backbone.Collection
initBindings: -> model: Comment
@model.view = @
@model.bind('change', @renderPartial, @) initialize: ->
@bind "add", (item) =>
initialize: -> item.collection = @
@initBindings()
@initLocal() find: (id) ->
@initTimeago() _.first @where(id: id)
@initTitle()
@initBody()
@initCommentViews()
class @Thread extends @Content
urlMappers:
'retrieve' : -> DiscussionUtil.urlFor('retrieve_single_thread', @discussion.id, @id)
'reply' : -> DiscussionUtil.urlFor('create_comment', @id)
'unvote' : -> DiscussionUtil.urlFor("undo_vote_for_#{@get('type')}", @id)
'upvote' : -> DiscussionUtil.urlFor("upvote_#{@get('type')}", @id)
'downvote' : -> DiscussionUtil.urlFor("downvote_#{@get('type')}", @id)
'close' : -> DiscussionUtil.urlFor('openclose_thread', @id)
'update' : -> DiscussionUtil.urlFor('update_thread', @id)
'delete' : -> DiscussionUtil.urlFor('delete_thread', @id)
'follow' : -> DiscussionUtil.urlFor('follow_thread', @id)
'unfollow' : -> DiscussionUtil.urlFor('unfollow_thread', @id)
initialize: ->
@set('thread', @)
super()
permalink: ->
discussion_id = @get('commentable_id')
return Discussion.urlFor("permanent_link_thread", discussion_id, @id)
class @ThreadView extends @ContentView
class @Comment extends @Content
urlMappers:
'reply': -> DiscussionUtil.urlFor('create_sub_comment', @id)
'unvote': -> DiscussionUtil.urlFor("undo_vote_for_#{@get('type')}", @id)
'upvote': -> DiscussionUtil.urlFor("upvote_#{@get('type')}", @id)
'downvote': -> DiscussionUtil.urlFor("downvote_#{@get('type')}", @id)
'endorse': -> DiscussionUtil.urlFor('endorse_comment', @id)
'update': -> DiscussionUtil.urlFor('update_comment', @id)
'delete': -> DiscussionUtil.urlFor('delete_comment', @id)
permalink: ->
thread_id = @get('thread').id
discussion_id = @get('thread').get('commentable_id')
return Discussion.urlFor("permanent_link_comment", discussion_id, thread_id, @id)
getCommentsCount: ->
count = 0
@get('comments').each (comment) ->
count += comment.getCommentsCount() + 1
count
class @CommentView extends @ContentView
class @Comments extends Backbone.Collection
model: Comment
initialize: ->
@bind "add", (item) =>
item.collection = @
find: (id) ->
_.first @where(id: id)
class @Discussion extends Backbone.Collection if Backbone?
model: Thread class @Discussion extends Backbone.Collection
model: Thread
initialize: ->
DiscussionUtil.addDiscussion @id, @ initialize: ->
@bind "add", (item) => DiscussionUtil.addDiscussion @id, @
item.discussion = @ @bind "add", (item) =>
item.discussion = @
find: (id) ->
_.first @where(id: id) find: (id) ->
_.first @where(id: id)
addThread: (thread, options) ->
options ||= {} addThread: (thread, options) ->
model = new Thread thread options ||= {}
@add model model = new Thread thread
model @add model
model
class @DiscussionView extends Backbone.View
class @DiscussionView extends Backbone.View
$: (selector) ->
@$local.find(selector) $: (selector) ->
@$local.find(selector)
initLocal: ->
@$local = @$el.children(".local") initLocal: ->
@$delegateElement = @$local @$local = @$el.children(".local")
@$delegateElement = @$local
initialize: ->
@initLocal() initialize: ->
@model.id = @$el.attr("_id") @initLocal()
@model.view = @ @model.id = @$el.attr("_id")
@$el.children(".threads").children(".thread").each (index, elem) => @model.view = @
threadView = new ThreadView el: elem, model: @model.find $(elem).attr("_id") @$el.children(".threads").children(".thread").each (index, elem) =>
if @$el.hasClass("forum-discussion") threadView = new ThreadView el: elem, model: @model.find $(elem).attr("_id")
$(".discussion-sidebar").find(".sidebar-new-post-button") if @$el.hasClass("forum-discussion")
.unbind('click').click $.proxy @newPost, @ $(".discussion-sidebar").find(".sidebar-new-post-button")
else if @$el.hasClass("inline-discussion") .unbind('click').click $.proxy @newPost, @
@newPost() else if @$el.hasClass("inline-discussion")
@newPost()
reload: ($elem, url) ->
if not url then return reload: ($elem, url) ->
DiscussionUtil.get $elem, url, {}, (response, textStatus) => if not url then return
$parent = @$el.parent() DiscussionUtil.get $elem, url, {}, (response, textStatus) =>
@$el.replaceWith(response.html) $parent = @$el.parent()
$discussion = $parent.find("section.discussion") @$el.replaceWith(response.html)
@model.reset(response.discussionData, { silent: false }) $discussion = $parent.find("section.discussion")
view = new DiscussionView el: $discussion[0], model: @model @model.reset(response.discussionData, { silent: false })
DiscussionUtil.bulkUpdateContentInfo(window.$$annotated_content_info) view = new DiscussionView el: $discussion[0], model: @model
DiscussionUtil.bulkUpdateContentInfo(window.$$annotated_content_info)
loadSimilarPost: (event) -> $("html, body").animate({ scrollTop: 0 }, 0)
$title = @$(".new-post-title")
$wrapper = @$(".new-post-similar-posts-wrapper") loadSimilarPost: (event) ->
$similarPosts = @$(".new-post-similar-posts") console.log "loading similar"
prevText = $title.attr("prev-text") $title = @$(".new-post-title")
text = $title.val() $wrapper = @$(".new-post-similar-posts-wrapper")
if text == prevText $similarPosts = @$(".new-post-similar-posts")
if @$(".similar-post").length prevText = $title.attr("prev-text")
$wrapper.show() text = $title.val()
else if $.trim(text).length if text == prevText
$elem = $(event.target) if @$(".similar-post").length
url = DiscussionUtil.urlFor 'search_similar_threads', @model.id
data = { text: @$(".new-post-title").val() }
DiscussionUtil.get $elem, url, data, (response, textStatus) =>
$similarPosts.empty()
if $.type(response) == "array" and response.length
$wrapper.show() $wrapper.show()
for thread in response else if $.trim(text).length
$similarPost = $("<a>").addClass("similar-post") $elem = $(event.target)
.html(thread["title"]) url = DiscussionUtil.urlFor 'search_similar_threads', @model.id
.attr("href", "javascript:void(0)") #TODO data = { text: @$(".new-post-title").val() }
.appendTo($similarPosts) DiscussionUtil.safeAjax
else $elem: $elem
$wrapper.hide() url: url
else data: data
$wrapper.hide() dataType: 'json'
$title.attr("prev-text", text) success: (response, textStatus) =>
$wrapper.html(response.html)
if $wrapper.find(".similar-post").length
newPost: -> $wrapper.show()
if not @$(".wmd-panel").length $wrapper.find(".hide-similar-posts").click =>
view = { discussion_id: @model.id } $wrapper.hide()
@$el.children(".discussion-non-content").append Mustache.render DiscussionUtil.getTemplate("_new_post"), view else
$newPostBody = @$(".new-post-body") $wrapper.hide()
DiscussionUtil.makeWmdEditor @$el, $.proxy(@$, @), "new-post-body" $title.attr("prev-text", text)
$input = DiscussionUtil.getWmdInput @$el, $.proxy(@$, @), "new-post-body"
$input.attr("placeholder", "post a new topic...") newPost: ->
if @$el.hasClass("inline-discussion") if not @$(".wmd-panel").length
$input.bind 'focus', (e) => view = { discussion_id: @model.id }
@$el.children(".discussion-non-content").append Mustache.render DiscussionUtil.getTemplate("_new_post"), view
$newPostBody = @$(".new-post-body")
DiscussionUtil.makeWmdEditor @$el, $.proxy(@$, @), "new-post-body"
$input = DiscussionUtil.getWmdInput @$el, $.proxy(@$, @), "new-post-body"
$input.attr("placeholder", "post a new topic...")
if @$el.hasClass("inline-discussion")
$input.bind 'focus', (e) =>
@$(".new-post-form").removeClass('collapsed')
else if @$el.hasClass("forum-discussion")
@$(".new-post-form").removeClass('collapsed') @$(".new-post-form").removeClass('collapsed')
else if @$el.hasClass("forum-discussion")
@$(".new-post-form").removeClass('collapsed') @$(".new-post-tags").tagsInput DiscussionUtil.tagsInputOptions()
@$(".new-post-tags").tagsInput DiscussionUtil.tagsInputOptions() @$(".new-post-title").blur $.proxy(@loadSimilarPost, @)
@$(".new-post-title").blur $.proxy(@loadSimilarPost, @) @$(".hide-similar-posts").click =>
@$(".new-post-similar-posts-wrapper").hide()
@$(".hide-similar-posts").click =>
@$(".new-post-similar-posts-wrapper").hide() @$(".discussion-submit-post").click $.proxy(@submitNewPost, @)
@$(".discussion-cancel-post").click $.proxy(@cancelNewPost, @)
@$(".discussion-submit-post").click $.proxy(@submitNewPost, @)
@$(".discussion-cancel-post").click $.proxy(@cancelNewPost, @)
@$(".new-post-form").show()
submitNewPost: (event) ->
title = @$(".new-post-title").val()
body = DiscussionUtil.getWmdContent @$el, $.proxy(@$, @), "new-post-body"
tags = @$(".new-post-tags").val()
anonymous = false || @$(".discussion-post-anonymously").is(":checked")
autowatch = false || @$(".discussion-auto-watch").is(":checked")
url = DiscussionUtil.urlFor('create_thread', @model.id)
DiscussionUtil.safeAjax
$elem: $(event.target)
url: url
type: "POST"
dataType: 'json'
data:
title: title
body: body
tags: tags
anonymous: anonymous
auto_subscribe: autowatch
error: DiscussionUtil.formErrorHandler(@$(".new-post-form-errors"))
success: (response, textStatus) =>
DiscussionUtil.clearFormErrors(@$(".new-post-form-errors"))
$thread = $(response.html)
@$el.children(".threads").prepend($thread)
@$(".new-post-title").val("")
DiscussionUtil.setWmdContent @$el, $.proxy(@$, @), "new-post-body", ""
@$(".new-post-tags").val("")
@$(".new-post-tags").importTags("")
thread = @model.addThread response.content
threadView = new ThreadView el: $thread[0], model: thread
thread.updateInfo response.annotated_content_info
@cancelNewPost()
cancelNewPost: (event) -> @$(".new-post-form").show()
if @$el.hasClass("inline-discussion")
@$(".new-post-form").addClass("collapsed") submitNewPost: (event) ->
else if @$el.hasClass("forum-discussion") title = @$(".new-post-title").val()
@$(".new-post-form").hide() body = DiscussionUtil.getWmdContent @$el, $.proxy(@$, @), "new-post-body"
tags = @$(".new-post-tags").val()
search: (event) -> anonymous = false || @$(".discussion-post-anonymously").is(":checked")
event.preventDefault() autowatch = false || @$(".discussion-auto-watch").is(":checked")
$elem = $(event.target) url = DiscussionUtil.urlFor('create_thread', @model.id)
url = URI($elem.attr("action")).addSearch({text: @$(".search-input").val()}) DiscussionUtil.safeAjax
@reload($elem, url) $elem: $(event.target)
url: url
sort: -> type: "POST"
$elem = $(event.target) dataType: 'json'
url = $elem.attr("sort-url") data:
@reload($elem, url) title: title
body: body
page: (event) -> tags: tags
$elem = $(event.target) anonymous: anonymous
url = $elem.attr("page-url") auto_subscribe: autowatch
@reload($elem, url) error: DiscussionUtil.formErrorHandler(@$(".new-post-form-errors"))
success: (response, textStatus) =>
events: DiscussionUtil.clearFormErrors(@$(".new-post-form-errors"))
"submit .search-wrapper>.discussion-search-form": "search" $thread = $(response.html)
"click .discussion-search-link": "search" @$el.children(".threads").prepend($thread)
"click .discussion-sort-link": "sort"
"click .discussion-page-link": "page" @$(".new-post-similar-posts").empty()
@$(".new-post-similar-posts-wrapper").hide()
@$(".new-post-title").val("").attr("prev-text", "")
DiscussionUtil.setWmdContent @$el, $.proxy(@$, @), "new-post-body", ""
@$(".new-post-tags").val("")
@$(".new-post-tags").importTags("")
thread = @model.addThread response.content
threadView = new ThreadView el: $thread[0], model: thread
thread.updateInfo response.annotated_content_info
@cancelNewPost()
cancelNewPost: (event) ->
if @$el.hasClass("inline-discussion")
@$(".new-post-form").addClass("collapsed")
else if @$el.hasClass("forum-discussion")
@$(".new-post-form").hide()
search: (event) ->
event.preventDefault()
$elem = $(event.target)
url = URI($elem.attr("action")).addSearch({text: @$(".search-input").val()})
@reload($elem, url)
sort: ->
$elem = $(event.target)
url = $elem.attr("sort-url")
@reload($elem, url)
page: (event) ->
$elem = $(event.target)
url = $elem.attr("page-url")
@reload($elem, url)
events:
"submit .search-wrapper>.discussion-search-form": "search"
"click .discussion-search-link": "search"
"click .discussion-sort-link": "sort"
"click .discussion-page-link": "page"
class @DiscussionModuleView extends Backbone.View if Backbone?
events: class @DiscussionModuleView extends Backbone.View
"click .discussion-show": "toggleDiscussion" events:
toggleDiscussion: (event) -> "click .discussion-show": "toggleDiscussion"
if @showed toggleDiscussion: (event) ->
@$("section.discussion").hide() if @showed
$(event.target).html("Show Discussion") @$("section.discussion").hide()
@showed = false $(event.target).html("Show Discussion")
else @showed = false
if @retrieved
@$("section.discussion").show()
$(event.target).html("Hide Discussion")
@showed = true
else else
$elem = $(event.target) if @retrieved
discussion_id = $elem.attr("discussion_id") @$("section.discussion").show()
url = DiscussionUtil.urlFor 'retrieve_discussion', discussion_id $(event.target).html("Hide Discussion")
Discussion.safeAjax @showed = true
$elem: $elem else
url: url $elem = $(event.target)
type: "GET" discussion_id = $elem.attr("discussion_id")
dataType: 'json' url = DiscussionUtil.urlFor 'retrieve_discussion', discussion_id
success: (response, textStatus) => DiscussionUtil.safeAjax
@$el.append(response.html) $elem: $elem
$discussion = @$el.find("section.discussion") url: url
$(event.target).html("Hide Discussion") type: "GET"
discussion = new Discussion() dataType: 'json'
discussion.reset(response.discussionData, {silent: false}) success: (response, textStatus) =>
view = new DiscussionView(el: $discussion[0], model: discussion) @$el.append(response.html)
DiscussionUtil.bulkUpdateContentInfo(window.$$annotated_content_info) $discussion = @$el.find("section.discussion")
@retrieved = true $(event.target).html("Hide Discussion")
@showed = true discussion = new Discussion()
discussion.reset(response.discussionData, {silent: false})
view = new DiscussionView(el: $discussion[0], model: discussion)
DiscussionUtil.bulkUpdateContentInfo(window.$$annotated_content_info)
@retrieved = true
@showed = true
...@@ -12,4 +12,10 @@ $ -> ...@@ -12,4 +12,10 @@ $ ->
discussion.reset(discussionData, {silent: false}) discussion.reset(discussionData, {silent: false})
view = new DiscussionView(el: elem, model: discussion) view = new DiscussionView(el: elem, model: discussion)
DiscussionUtil.bulkUpdateContentInfo(window.$$annotated_content_info) if window.$$annotated_content_info?
DiscussionUtil.bulkUpdateContentInfo(window.$$annotated_content_info)
$userProfile = $(".discussion-sidebar>.user-profile")
if $userProfile.length
console.log "initialize user profile"
view = new DiscussionUserProfileView(el: $userProfile[0])
if not @Discussion? class @DiscussionUserProfileView extends Backbone.View
@Discussion = {} toggleModeratorStatus: (event) ->
confirmValue = confirm("Are you sure?")
if not confirmValue then return
$elem = $(event.target)
if $elem.hasClass("sidebar-promote-moderator-button")
isModerator = true
else if $elem.hasClass("sidebar-revoke-moderator-button")
isModerator = false
else
console.error "unrecognized moderator status"
return
url = DiscussionUtil.urlFor('update_moderator_status', $$profiled_user_id)
DiscussionUtil.safeAjax
$elem: $elem
url: url
type: "POST"
dataType: 'json'
data:
is_moderator: isModerator
error: (response, textStatus, e) ->
console.log e
success: (response, textStatus) =>
parent = @$el.parent()
@$el.replaceWith(response.html)
view = new DiscussionUserProfileView el: parent.children(".user-profile")
Discussion = @Discussion events:
"click .sidebar-toggle-moderator-button": "toggleModeratorStatus"
@Discussion = $.extend @Discussion,
initializeUserProfile: ($userProfile) ->
$local = Discussion.generateLocal $userProfile
handleUpdateModeratorStatus = (elem, isModerator) ->
confirmValue = confirm("Are you sure?")
if not confirmValue then return
url = Discussion.urlFor('update_moderator_status', $$profiled_user_id)
Discussion.safeAjax
$elem: $(elem)
url: url
type: "POST"
dataType: 'json'
data:
is_moderator: isModerator
error: (response, textStatus, e) ->
console.log e
success: (response, textStatus) ->
parent = $userProfile.parent()
$userProfile.replaceWith(response.html)
Discussion.initializeUserProfile parent.children(".user-profile")
Discussion.bindLocalEvents $local,
"click .sidebar-revoke-moderator-button": (event) ->
handleUpdateModeratorStatus(this, false)
"click .sidebar-promote-moderator-button": (event) ->
handleUpdateModeratorStatus(this, true)
initializeUserActiveDiscussion: ($discussion) ->
...@@ -22,6 +22,7 @@ ...@@ -22,6 +22,7 @@
## <script type="text/javascript" src="${static.url('js/vendor/CodeMirror-2.25/mode/python/python.js')}"></script> ## <script type="text/javascript" src="${static.url('js/vendor/CodeMirror-2.25/mode/python/python.js')}"></script>
<%static:js group='courseware'/> <%static:js group='courseware'/>
<%static:js group='discussion'/>
<%include file="../discussion/_js_body_dependencies.html" /> <%include file="../discussion/_js_body_dependencies.html" />
......
<%! import django_comment_client.helpers as helpers %> <%! import django_comment_client.helpers as helpers %>
<%def name="render_content(content)"> <%def name="render_content(content, *args, **kwargs)">
${helpers.render_content(content)} ${helpers.render_content(content, *args, **kwargs)}
</%def> </%def>
<%def name="render_content_with_comments(content)"> <%def name="render_content_with_comments(content, *args, **kwargs)">
<div class="${content['type']}${helpers.show_if(' endorsed', content.get('endorsed'))}" _id="${content['id']}" _discussion_id="${content.get('commentable_id', '')}" _author_id="${helpers.show_if(content['user_id'], not content.get('anonymous'))}"> <div class="${content['type']}${helpers.show_if(' endorsed', content.get('endorsed'))}" _id="${content['id']}" _discussion_id="${content.get('commentable_id', '')}" _author_id="${helpers.show_if(content['user_id'], not content.get('anonymous'))}">
${render_content(content)} ${render_content(content, *args, **kwargs)}
${render_comments(content.get('children', []))} ${render_comments(content.get('children', []), *args, **kwargs)}
</div> </div>
</%def> </%def>
<%def name="render_comments(comments)"> <%def name="render_comments(comments, *args, **kwargs)">
<div class="comments"> <div class="comments">
% for comment in comments: % for comment in comments:
${render_content_with_comments(comment)} ${render_content_with_comments(comment, *args, **kwargs)}
% endfor % endfor
</div> </div>
</%def> </%def>
% if len(threads) > 0:
Similar Posts:
<a class="hide-similar-posts" href="javascript:void(0)">Hide</a>
<div class="new-post-similar-posts">
% for thread in threads:
<a class="similar-post" href="${thread['permalink']}">${thread['title']}</a>
% endfor
</div>
% endif
<%namespace name="renderer" file="_thread.html"/> <%namespace name="renderer" file="_content_renderer.html"/>
<section class="discussion user-active-discussion"> <section class="discussion user-active-discussion" _id="${user_id}">
<div class="discussion-non-content discussion-local"></div> <div class="discussion-non-content local"></div>
<div class="threads"> <div class="threads">
% for thread in threads: % for thread in threads:
${renderer.render_thread(course_id, thread, show_comments=True)} ${renderer.render_content_with_comments(thread, {'partial_comments': True})}
% endfor % endfor
</div> </div>
......
<%! from django_comment_client.utils import pluralize %> <%! from django_comment_client.helpers import pluralize %>
<%! from django_comment_client.permissions import has_permission, check_permissions_by_view %> <%! from django_comment_client.permissions import has_permission, check_permissions_by_view %>
<%! from operator import attrgetter %> <%! from operator import attrgetter %>
...@@ -15,9 +15,9 @@ ...@@ -15,9 +15,9 @@
<div class="sidebar-comments-count"><span>${profiled_user['comments_count']}</span> ${pluralize('comment', profiled_user['comments_count'])}</div> <div class="sidebar-comments-count"><span>${profiled_user['comments_count']}</span> ${pluralize('comment', profiled_user['comments_count'])}</div>
% if check_permissions_by_view(user, course.id, content=None, name='update_moderator_status'): % if check_permissions_by_view(user, course.id, content=None, name='update_moderator_status'):
% if "Moderator" in role_names: % if "Moderator" in role_names:
<a href="javascript:void(0)" class="sidebar-revoke-moderator-button">Revoke Moderator provileges</a> <a href="javascript:void(0)" class="sidebar-toggle-moderator-button sidebar-revoke-moderator-button">Revoke Moderator provileges</a>
% else: % else:
<a href="javascript:void(0)" class="sidebar-promote-moderator-button">Promote to Moderator</a> <a href="javascript:void(0)" class="sidebar-toggle-moderator-button sidebar-promote-moderator-button">Promote to Moderator</a>
% endif % endif
% endif % endif
</div> </div>
<%inherit file="../main.html" /> <%inherit file="../main.html" />
<%namespace name='static' file='../static_content.html'/> <%namespace name='static' file='../static_content.html'/>
<%block name="bodyclass">discussion</%block> <%block name="bodyclass">discussion</%block>
<%block name="title"><title>Discussion – MITx 6.002x</title></%block> <%block name="title"><title>Discussion – ${course.number}</title></%block>
<%block name="headextra"> <%block name="headextra">
<%static:css group='course'/> <%static:css group='course'/>
......
...@@ -37,7 +37,7 @@ ...@@ -37,7 +37,7 @@
anonymous anonymous
{{/content.anonymous}} {{/content.anonymous}}
{{^content.anonymous}} {{^content.anonymous}}
{{content.username}} <a href="{{##url_for_user}}{{content.user_id}}{{/url_for_user}}">{{content.username}}</a>
{{/content.anonymous}} {{/content.anonymous}}
</div> </div>
<div class="show-comments-wrapper"> <div class="show-comments-wrapper">
......
<form class="new-post-form collapsed" id="new-post-form" style="display: block; "> <form class="new-post-form collapsed" id="new-post-form" style="display: block; ">
<ul class="new-post-form-errors discussion-errors"></ul> <ul class="new-post-form-errors discussion-errors"></ul>
<input type="text" class="new-post-title title-input" placeholder="Title" /> <input type="text" class="new-post-title title-input" placeholder="Title" />
<div class="new-post-similar-posts-wrapper" style="display: none"> <div class="new-post-similar-posts-wrapper" style="display: none"></div>
Similar Posts:
<a class="hide-similar-posts" href="javascript:void(0)">Hide</a>
<div class="new-post-similar-posts"></div>
</div>
<div class="new-post-body reply-body"></div> <div class="new-post-body reply-body"></div>
<input class="new-post-tags" placeholder="Tags" /> <input class="new-post-tags" placeholder="Tags" />
<div class="post-options"> <div class="post-options">
......
<%inherit file="../main.html" /> <%inherit file="../main.html" />
<%namespace name='static' file='../static_content.html'/> <%namespace name='static' file='../static_content.html'/>
<%block name="bodyclass">discussion</%block> <%block name="bodyclass">discussion</%block>
<%block name="title"><title>Discussion – MITx 6.002x</title></%block> <%block name="title"><title>Discussion – ${course.number}</title></%block>
<%block name="headextra"> <%block name="headextra">
<%static:css group='course'/> <%static:css group='course'/>
......
<%! from django.template.defaultfilters import escapejs %> <%! from django.template.defaultfilters import escapejs %>
<%namespace name="renderer" file="_thread.html"/>
<%inherit file="../main.html" /> <%inherit file="../main.html" />
<%namespace name='static' file='../static_content.html'/> <%namespace name='static' file='../static_content.html'/>
<%block name="bodyclass">discussion</%block> <%block name="bodyclass">discussion</%block>
<%block name="title"><title>Discussion – MITx 6.002x</title></%block> <%block name="title"><title>Discussion – ${course.number}</title></%block>
<%block name="headextra"> <%block name="headextra">
<%static:css group='course'/> <%static:css group='course'/>
<%include file="_js_head_dependencies.html" />
</%block> </%block>
<%block name="js_extra"> <%block name="js_extra">
<%include file="_js_dependencies.html" /> <%include file="_js_body_dependencies.html" />
<%static:js group='discussion'/>
</%block> </%block>
<%include file="/courseware/course_navigation.html" args="active_page='discussion'" /> <%include file="../courseware/course_navigation.html" args="active_page='discussion'" />
<section class="container"> <section class="container">
<div class="course-wrapper"> <div class="course-wrapper">
......
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