Merge branch 'feature/cas/speed-editor' of github.com:MITx/mitx into feature/cas/speed-editor

This commit is contained in:
cahrens
2013-01-10 13:50:57 -05:00
18 changed files with 403 additions and 198 deletions

View File

@@ -1,8 +1,6 @@
from cms.djangoapps.contentstore.tests.test_course_settings import CourseTestCase
from django.core.urlresolvers import reverse
import json
from cms.djangoapps.contentstore.course_info_model import update_course_updates
class CourseUpdateTest(CourseTestCase):
def test_course_update(self):
@@ -14,14 +12,17 @@ class CourseUpdateTest(CourseTestCase):
content = '<iframe width="560" height="315" src="http://www.youtube.com/embed/RocY-Jd93XU" frameborder="0"></iframe>'
payload = { 'content' : content,
'date' : 'January 8, 2013'}
# No means to post w/ provided_id missing. django doesn't handle. So, go direct for the create
payload = update_course_updates(['i4x', self.course_location.org, self.course_location.course, 'course_info', "updates"] , payload)
url = reverse('course_info', kwargs={'org' : self.course_location.org, 'course' : self.course_location.course,
'provided_id' : ''})
resp = self.client.post(url, json.dumps(payload), "application/json")
payload= json.loads(resp.content)
self.assertHTMLEqual(content, payload['content'], "single iframe")
url = reverse('course_info', kwargs={'org' : self.course_location.org, 'course' : self.course_location.course,
'provided_id' : payload['id']})
self.assertHTMLEqual(content, payload['content'], "single iframe")
content += '<div>div <p>p</p></div>'
payload['content'] = content
resp = self.client.post(url, json.dumps(payload), "application/json")

View File

@@ -975,6 +975,11 @@ def course_info_updates(request, org, course, provided_id=None):
# ??? No way to check for access permission afaik
# get current updates
location = ['i4x', org, course, 'course_info', "updates"]
# Hmmm, provided_id is coming as empty string on create whereas I believe it used to be None :-(
# Possibly due to my removing the seemingly redundant pattern in urls.py
if provided_id == '':
provided_id = None
# check that logged in user has permissions to this item
if not has_access(request.user, location):

View File

@@ -56,7 +56,7 @@ class CMS.Views.ModuleEdit extends Backbone.View
event.preventDefault()
data = @module.save()
data.metadata = _.extend(data.metadata, @metadata())
$modalCover.hide()
@hideModal()
@model.save(data).done( =>
# # showToastMessage("Your changes have been saved.", null, 3)
@module = null
@@ -70,11 +70,15 @@ class CMS.Views.ModuleEdit extends Backbone.View
event.preventDefault()
@$el.removeClass('editing')
@$component_editor().slideUp(150)
@hideModal()
hideModal: ->
$modalCover.hide()
$modalCover.removeClass('is-fixed')
clickEditButton: (event) ->
event.preventDefault()
@$el.addClass('editing')
$modalCover.show()
$modalCover.show().addClass('is-fixed')
@$component_editor().slideDown(150)
@loadEdit()

View File

@@ -29,9 +29,7 @@ $(document).ready(function() {
$('.expand-collapse-icon').bind('click', toggleSubmodules);
$('.visibility-options').bind('change', setVisibility);
$('.unit-history ol a').bind('click', showHistoryModal);
$modal.bind('click', hideModal);
$modalCover.bind('click', hideHistoryModal);
$modalCover.bind('click', hideModal);
$('.assets .upload-button').bind('click', showUploadModal);
$('.upload-modal .close-button').bind('click', hideModal);
@@ -41,7 +39,13 @@ $(document).ready(function() {
$('.unit .item-actions .delete-button').bind('click', deleteUnit);
$('.new-unit-item').bind('click', createNewUnit);
$('.collapse-all-button').bind('click', collapseAll);
// toggling overview section details
$(function(){
if($('.courseware-section').length > 0) {
$('.toggle-button-sections').addClass('is-shown');
}
});
$('.toggle-button-sections').bind('click', toggleSections);
// autosave when a field is updated on the subsection page
$body.on('keyup', '.subsection-display-name-input, .unit-subtitle, .policy-list-value', checkForNewValue);
@@ -125,9 +129,30 @@ $(document).ready(function() {
});
});
function collapseAll(e) {
$('.branch').addClass('collapsed');
$('.expand-collapse-icon').removeClass('collapse').addClass('expand');
// function collapseAll(e) {
// $('.branch').addClass('collapsed');
// $('.expand-collapse-icon').removeClass('collapse').addClass('expand');
// }
function toggleSections(e) {
e.preventDefault();
$section = $('.courseware-section');
sectionCount = $section.length;
$button = $(this);
$labelCollapsed = $('<i class="ss-icon ss-symbolicons-block">up</i> <span class="label">Collapse All Sections</span>');
$labelExpanded = $('<i class="ss-icon ss-symbolicons-block">down</i> <span class="label">Expand All Sections</span>');
var buttonLabel = $button.hasClass('is-activated') ? $labelCollapsed : $labelExpanded;
$button.toggleClass('is-activated').html(buttonLabel);
if($button.hasClass('is-activated')) {
$section.addClass('collapsed');
$section.find('.expand-collapse-icon').removeClass('collapsed').addClass('expand');
} else {
$section.removeClass('collapsed');
$section.find('.expand-collapse-icon').removeClass('expand').addClass('collapse');
}
}
function editSectionPublishDate(e) {
@@ -498,9 +523,14 @@ function hideModal(e) {
if(e) {
e.preventDefault();
}
$('.file-input').unbind('change', startUpload);
$modal.hide();
$modalCover.hide();
// Unit editors do not want the modal cover to hide when users click outside
// of the editor. Users must press Cancel or Save to exit the editor.
// module_edit adds and removes the "is-fixed" class.
if (!$modalCover.hasClass("is-fixed")) {
$('.file-input').unbind('change', startUpload);
$modal.hide();
$modalCover.hide();
}
}
function onKeyUp(e) {
@@ -530,21 +560,6 @@ function closeComponentEditor(e) {
$(this).closest('.xmodule_edit').removeClass('editing').find('.component-editor').slideUp(150);
}
function showHistoryModal(e) {
e.preventDefault();
$modal.show();
$modalCover.show();
}
function hideHistoryModal(e) {
e.preventDefault();
$modal.hide();
$modalCover.hide();
}
function showDateSetter(e) {
e.preventDefault();
var $block = $(this).closest('.due-date-input');

View File

@@ -388,6 +388,9 @@ CMS.Views.Settings.Grading = CMS.Views.ValidatingView.extend({
var graceEle = this.$el.find('#course-grading-graceperiod');
graceEle.timepicker({'timeFormat' : 'H:i'}); // init doesn't take setTime
if (this.model.has('grace_period')) graceEle.timepicker('setTime', this.model.gracePeriodToDate());
// remove any existing listeners to keep them from piling on b/c render gets called frequently
graceEle.off('change', this.setGracePeriod);
graceEle.on('change', this, this.setGracePeriod);
return this;
},
@@ -398,14 +401,16 @@ CMS.Views.Settings.Grading = CMS.Views.ValidatingView.extend({
fieldToSelectorMap : {
'grace_period' : 'course-grading-graceperiod'
},
setGracePeriod : function(event) {
event.data.clearValidationErrors();
var newVal = event.data.model.dateToGracePeriod($(event.currentTarget).timepicker('getTime'));
if (event.data.model.get('grace_period') != newVal) event.data.model.save('grace_period', newVal);
},
updateModel : function(event) {
if (!this.selectorToField[event.currentTarget.id]) return;
switch (this.selectorToField[event.currentTarget.id]) {
case 'grace_period':
this.clearValidationErrors();
var newVal = this.model.dateToGracePeriod($(event.currentTarget).timepicker('getTime'));
if (this.model.get('grace_period') != newVal) this.model.save('grace_period', newVal);
case 'grace_period': // handled above
break;
default:

View File

@@ -422,6 +422,14 @@ input.courseware-unit-search-input {
float: left;
margin: 29px 6px 16px 16px;
@include transition(none);
&.expand {
background-position: 0 0;
}
&.collapsed {
}
}
.drag-handle {
@@ -501,14 +509,31 @@ input.courseware-unit-search-input {
}
}
.collapse-all-button {
.toggle-button-sections {
display: none;
position: relative;
float: right;
margin-top: 10px;
font-size: 13px;
color: $darkGrey;
.collapse-all-icon {
margin-right: 6px;
&.is-shown {
display: block;
}
.ss-icon {
@include border-radius(20px);
position: relative;
top: -1px;
display: inline-block;
margin-right: 2px;
line-height: 5px;
font-size: 11px;
}
.label {
display: inline-block;
}
}

View File

@@ -245,8 +245,8 @@
&.editing {
border: 1px solid $lightBluishGrey2;
z-index: 9999;
z-index: auto;
.drag-handle,
.component-actions {
display: none;
@@ -284,12 +284,17 @@
overflow-x: auto;
}
.wrapper-component-editor {
z-index: 9999;
position: relative;
}
.component-editor {
@include edit-box;
@include box-shadow(none);
display: none;
padding: 20px;
border-radius: 2px 2px 0 0;
@include box-shadow(none);
.metadata_edit {
margin-bottom: 20px;

View File

@@ -1,13 +1,17 @@
<div class="component-editor">
<div class="module-editor">
${editor}
</div>
<a href="#" class="save-button">Save</a>
<a href="#" class="cancel-button">Cancel</a>
<div class="wrapper wrapper-component-editor">
<div class="component-editor">
<div class="module-editor">
${editor}
</div>
<a href="#" class="save-button">Save</a>
<a href="#" class="cancel-button">Cancel</a>
</div>
</div>
<div class="component-actions">
<a href="#" class="edit-button standard"><span class="edit-icon"></span>Edit</a>
<a href="#" class="delete-button standard"><span class="delete-icon"></span>Delete</a>
</div>
<a data-tooltip="Drag to reorder" href="#" class="drag-handle"></a>
${preview}
${preview}

View File

@@ -122,7 +122,7 @@
<div class="inner-wrapper">
<div class="page-actions">
<a href="#" class="new-button new-courseware-section-button"><span class="plus-icon white"></span> New Section</a>
<a href="#" class="collapse-all-button"><span class="collapse-all-icon"></span>Collapse All</a>
<a href="#" class="toggle-button toggle-button-sections"><i class="ss-icon ss-symbolicons-block">up</i> <span class="label">Collapse All Sections</span></a>
</div>
<article class="courseware-overview" data-course-id="${context_course.location.url()}">
% for section in sections:

View File

@@ -6,6 +6,7 @@ from xmodule.modulestore import Location
from xmodule.seq_module import SequenceDescriptor, SequenceModule
from xmodule.timeparse import parse_time, stringify_time
from xmodule.util.decorators import lazyproperty
from datetime import datetime
import json
import logging
import requests
@@ -18,6 +19,8 @@ log = logging.getLogger(__name__)
edx_xml_parser = etree.XMLParser(dtd_validation=False, load_dtd=False,
remove_comments=True, remove_blank_text=True)
_cached_toc = {}
class CourseDescriptor(SequenceDescriptor):
module_class = SequenceModule
@@ -50,6 +53,24 @@ class CourseDescriptor(SequenceDescriptor):
"""
toc_url = self.book_url + 'toc.xml'
# cdodge: I've added this caching of TOC because in Mongo-backed instances (but not Filesystem stores)
# course modules have a very short lifespan and are constantly being created and torn down.
# Since this module in the __init__() method does a synchronous call to AWS to get the TOC
# this is causing a big performance problem. So let's be a bit smarter about this and cache
# each fetch and store in-mem for 10 minutes.
# NOTE: I have to get this onto sandbox ASAP as we're having runtime failures. I'd like to swing back and
# rewrite to use the traditional Django in-memory cache.
try:
# see if we already fetched this
if toc_url in _cached_toc:
(table_of_contents, timestamp) = _cached_toc[toc_url]
age = datetime.now() - timestamp
# expire every 10 minutes
if age.seconds < 600:
return table_of_contents
except Exception as err:
pass
# Get the table of contents from S3
log.info("Retrieving textbook table of contents from %s" % toc_url)
try:
@@ -62,6 +83,7 @@ class CourseDescriptor(SequenceDescriptor):
# TOC is XML. Parse it
try:
table_of_contents = etree.fromstring(r.text)
_cached_toc[toc_url] = (table_of_contents, datetime.now())
except Exception as err:
msg = 'Error %s: Unable to parse XML for textbook table of contents at %s' % (err, toc_url)
log.error(msg)

View File

@@ -284,7 +284,7 @@ class ModuleStore(object):
"""
raise NotImplementedError
def get_items(self, location, depth=0):
def get_items(self, location, course_id=None, depth=0):
"""
Returns a list of XModuleDescriptor instances for the items
that match location. Any element of location that is None is treated

View File

@@ -262,7 +262,7 @@ class MongoModuleStore(ModuleStoreBase):
"""
return self.get_item(location)
def get_items(self, location, depth=0):
def get_items(self, location, course_id=None, depth=0):
items = self.collection.find(
location_to_query(location),
sort=[('revision', pymongo.ASCENDING)],

View File

@@ -513,16 +513,22 @@ class XMLModuleStore(ModuleStoreBase):
raise NotImplementedError("XMLModuleStores can't guarantee that definitions"
" are unique. Use get_instance.")
def get_items(self, location, depth=0):
def get_items(self, location, course_id=None, depth=0):
items = []
for _, modules in self.modules.iteritems():
for mod_loc, module in modules.iteritems():
def _add_get_items(self, location, modules):
for mod_loc, module in modules.iteritems():
# Locations match if each value in `location` is None or if the value from `location`
# matches the value from `mod_loc`
if all(goal is None or goal == value for goal, value in zip(location, mod_loc)):
items.append(module)
if course_id is None:
for _, modules in self.modules.iteritems():
_add_get_items(self, location, modules)
else:
_add_get_items(self, location, self.modules[course_id])
return items

View File

@@ -120,47 +120,16 @@ def import_from_xml(store, data_dir, course_dirs=None,
course_data_path = None
course_location = None
# Quick scan to get course Location as well as the course_data_path
# Quick scan to get course module as we need some info from there. Also we need to make sure that the
# course module is committed first into the store
for module in module_store.modules[course_id].itervalues():
if module.category == 'course':
course_data_path = path(data_dir) / module.metadata['data_dir']
course_location = module.location
if static_content_store is not None:
_namespace_rename = target_location_namespace if target_location_namespace is not None else module_store.modules[course_id].location
# first pass to find everything in /static/
import_static_content(module_store.modules[course_id], course_location, course_data_path, static_content_store,
_namespace_rename, subpath='static')
module = remap_namespace(module, target_location_namespace)
for module in module_store.modules[course_id].itervalues():
# remap module to the new namespace
if target_location_namespace is not None:
# This looks a bit wonky as we need to also change the 'name' of the imported course to be what
# the caller passed in
if module.location.category != 'course':
module.location = module.location._replace(tag=target_location_namespace.tag, org=target_location_namespace.org,
course=target_location_namespace.course)
else:
module.location = module.location._replace(tag=target_location_namespace.tag, org=target_location_namespace.org,
course=target_location_namespace.course, name=target_location_namespace.name)
# then remap children pointers since they too will be re-namespaced
children_locs = module.definition.get('children')
if children_locs is not None:
new_locs = []
for child in children_locs:
child_loc = Location(child)
new_child_loc = child_loc._replace(tag=target_location_namespace.tag, org=target_location_namespace.org,
course=target_location_namespace.course)
new_locs.append(new_child_loc.url())
module.definition['children'] = new_locs
if module.category == 'course':
# HACK: for now we don't support progress tabs. There's a special metadata configuration setting for this.
module.metadata['hide_progress_tab'] = True
@@ -174,12 +143,41 @@ def import_from_xml(store, data_dir, course_dirs=None,
{"type": "discussion", "name": "Discussion"},
{"type": "wiki", "name": "Wiki"}] # note, add 'progress' when we can support it on Edge
store.update_item(module.location, module.definition['data'])
if 'children' in module.definition:
store.update_children(module.location, module.definition['children'])
store.update_metadata(module.location, dict(module.own_metadata))
# a bit of a hack, but typically the "course image" which is shown on marketing pages is hard coded to /images/course_image.jpg
# so let's make sure we import in case there are no other references to it in the modules
verify_content_links(module, course_data_path, static_content_store, '/static/images/course_image.jpg')
course_items.append(module)
# then import all the static content
if static_content_store is not None:
_namespace_rename = target_location_namespace if target_location_namespace is not None else module_store.modules[course_id].location
# first pass to find everything in /static/
import_static_content(module_store.modules[course_id], course_location, course_data_path, static_content_store,
_namespace_rename, subpath='static')
# finally loop through all the modules
for module in module_store.modules[course_id].itervalues():
if module.category == 'course':
# we've already saved the course module up at the top of the loop
# so just skip over it in the inner loop
continue
# remap module to the new namespace
if target_location_namespace is not None:
module = remap_namespace(module, target_location_namespace)
if 'data' in module.definition:
module_data = module.definition['data']
@@ -216,6 +214,33 @@ def import_from_xml(store, data_dir, course_dirs=None,
return module_store, course_items
def remap_namespace(module, target_location_namespace):
if target_location_namespace is None:
return module
# This looks a bit wonky as we need to also change the 'name' of the imported course to be what
# the caller passed in
if module.location.category != 'course':
module.location = module.location._replace(tag=target_location_namespace.tag, org=target_location_namespace.org,
course=target_location_namespace.course)
else:
module.location = module.location._replace(tag=target_location_namespace.tag, org=target_location_namespace.org,
course=target_location_namespace.course, name=target_location_namespace.name)
# then remap children pointers since they too will be re-namespaced
children_locs = module.definition.get('children')
if children_locs is not None:
new_locs = []
for child in children_locs:
child_loc = Location(child)
new_child_loc = child_loc._replace(tag=target_location_namespace.tag, org=target_location_namespace.org,
course=target_location_namespace.course)
new_locs.append(new_child_loc.url())
module.definition['children'] = new_locs
return module
def validate_category_hierarcy(module_store, course_id, parent_category, expected_child_category):
err_cnt = 0

View File

@@ -1,18 +1,17 @@
.ui-timepicker-list {
overflow-y: auto;
height: 150px;
width: 7.5em;
width: 6.5em;
background: #fff;
border: 1px solid #8891a1;
border: 1px solid #ddd;
margin: 0;
padding: 0;
list-style: none;
-webkit-box-shadow: 0 5px 10px rgba(0,0,0,0.1);
-moz-box-shadow: 0 5px 10px rgba(0,0,0,0.1);
box-shadow: 0 5px 10px rgba(0,0,0,0.1);
-webkit-box-shadow:0 5px 10px rgba(0,0,0,0.2);
-moz-box-shadow:0 5px 10px rgba(0,0,0,0.2);
box-shadow:0 5px 10px rgba(0,0,0,0.2);
outline: none;
z-index: 100001;
font-size: 12px;
z-index: 10001;
}
.ui-timepicker-list.ui-timepicker-with-duration {

246
common/static/js/vendor/timepicker/jquery.timepicker.js vendored Executable file → Normal file
View File

@@ -2,16 +2,22 @@
jquery-timepicker
http://jonthornton.github.com/jquery-timepicker/
requires jQuery 1.6+
version: 1.2.2
requires jQuery 1.7+
************************/
!(function($)
{
var _baseDate = new Date(); _baseDate.setHours(0); _baseDate.setMinutes(0); _baseDate.setSeconds(0);
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else {
// Browser globals
factory(jQuery);
}
}(function ($) {
var _baseDate = _generateBaseDate();
var _ONE_DAY = 86400;
var _closeEvent = 'ontouchstart' in document ? 'touchstart' : 'mousedown';
var _defaults = {
className: null,
minTime: null,
@@ -22,7 +28,9 @@ version: 1.2.2
timeFormat: 'g:ia',
scrollDefaultNow: false,
scrollDefaultTime: false,
selectOnBlur: false
selectOnBlur: false,
forceRoundTime: false,
appendTo: 'body'
};
var _lang = {
decimal: '.',
@@ -30,6 +38,7 @@ version: 1.2.2
hr: 'hr',
hrs: 'hrs'
};
var globalInit = false;
var methods =
{
@@ -78,31 +87,45 @@ version: 1.2.2
self.data('timepicker-settings', settings);
self.attr('autocomplete', 'off');
self.click(methods.show).focus(methods.show).blur(_formatValue).keydown(_keyhandler);
self.on('click.timepicker focus.timepicker', methods.show);
self.on('blur.timepicker', _formatValue);
self.on('keydown.timepicker', _keyhandler);
self.addClass('ui-timepicker-input');
if (self.val()) {
var prettyTime = _int2time(_time2int(self.val()), settings.timeFormat);
self.val(prettyTime);
_formatValue.call(self.get(0));
if (!globalInit) {
// close the dropdown when container loses focus
$('body').on(_closeEvent, function(e) {
var target = $(e.target);
var input = target.closest('.ui-timepicker-input');
if (input.length === 0 && target.closest('.ui-timepicker-list').length === 0) {
methods.hide();
}
});
globalInit = true;
}
// close the dropdown when container loses focus
$("body").attr("tabindex", -1).focusin(function(e) {
if ($(e.target).closest('.ui-timepicker-input').length == 0 && $(e.target).closest('.ui-timepicker-list').length == 0) {
methods.hide();
}
});
});
},
show: function(e)
{
var self = $(this);
if ('ontouchstart' in document) {
// block the keyboard on mobile devices
self.blur();
}
var list = self.data('timepicker-list');
// check if input is readonly
if (self.attr('readonly')) {
return;
}
// check if list needs to be rendered
if (!list || list.length == 0) {
if (!list || list.length === 0) {
_render(self);
list = self.data('timepicker-list');
}
@@ -121,16 +144,12 @@ version: 1.2.2
// make sure other pickers are hidden
methods.hide();
var topMargin = parseInt(self.css('marginTop').slice(0, -2));
if (!topMargin) topMargin = 0; // correct for IE returning "auto"
if ((self.offset().top + self.outerHeight(true) + list.outerHeight()) > $(window).height() + $(window).scrollTop()) {
// position the dropdown on top
list.css({ 'left':(self.offset().left), 'top': self.offset().top + topMargin - list.outerHeight() });
list.css({ 'left':(self.offset().left), 'top': self.offset().top - list.outerHeight() });
} else {
// put it under the input
list.css({ 'left':(self.offset().left), 'top': self.offset().top + topMargin + self.outerHeight() });
list.css({ 'left':(self.offset().left), 'top': self.offset().top + self.outerHeight() });
}
list.show();
@@ -140,13 +159,13 @@ version: 1.2.2
var selected = list.find('.ui-timepicker-selected');
if (!selected.length) {
if (self.val()) {
selected = _findRow(self, list, _time2int(self.val()));
} else if (settings.minTime === null && settings.scrollDefaultNow) {
selected = _findRow(self, list, _time2int(new Date()));
} else if (settings.scrollDefaultTime !== false) {
selected = _findRow(self, list, _time2int(settings.scrollDefaultTime));
}
if (self.val()) {
selected = _findRow(self, list, _time2int(self.val()));
} else if (settings.scrollDefaultNow) {
selected = _findRow(self, list, _time2int(new Date()));
} else if (settings.scrollDefaultTime !== false) {
selected = _findRow(self, list, _time2int(settings.scrollDefaultTime));
}
}
if (selected && selected.length) {
@@ -165,7 +184,8 @@ version: 1.2.2
var list = $(this);
var self = list.data('timepicker-input');
var settings = self.data('timepicker-settings');
if (settings.selectOnBlur) {
if (settings && settings.selectOnBlur) {
_selectValue(self);
}
@@ -226,8 +246,29 @@ version: 1.2.2
var self = $(this);
var prettyTime = _int2time(_time2int(value), self.data('timepicker-settings').timeFormat);
self.val(prettyTime);
}
},
remove: function()
{
var self = $(this);
// check if this element is a timepicker
if (!self.hasClass('ui-timepicker-input')) {
return;
}
self.removeAttr('autocomplete', 'off');
self.removeClass('ui-timepicker-input');
self.removeData('timepicker-settings');
self.off('.timepicker');
// timepicker-list won't be present unless the user has interacted with this timepicker
if (self.data('timepicker-list')) {
self.data('timepicker-list').remove();
}
self.removeData('timepicker-list');
}
};
// private methods
@@ -251,7 +292,7 @@ version: 1.2.2
list.css({'display':'none', 'position': 'absolute' });
if (settings.minTime !== null && settings.showDuration) {
if ((settings.minTime !== null || settings.durationTime !== null) && settings.showDuration) {
list.addClass('ui-timepicker-with-duration');
}
@@ -267,14 +308,14 @@ version: 1.2.2
for (var i=start; i <= end; i += settings.step*60) {
var timeInt = i%_ONE_DAY;
var row = $('<li />');
row.data('time', timeInt)
row.data('time', timeInt);
row.text(_int2time(timeInt, settings.timeFormat));
if (settings.minTime !== null && settings.showDuration) {
if ((settings.minTime !== null || settings.durationTime !== null) && settings.showDuration) {
var duration = $('<span />');
duration.addClass('ui-timepicker-duration');
duration.text(' ('+_int2duration(i - durStart)+')');
row.append(duration)
row.append(duration);
}
list.append(row);
@@ -283,10 +324,16 @@ version: 1.2.2
list.data('timepicker-input', self);
self.data('timepicker-list', list);
$('body').append(list);
var appendTo = settings.appendTo;
if (typeof appendTo === 'string') {
appendTo = $(appendTo);
} else if (typeof appendTo === 'function') {
appendTo = appendTo(self);
}
appendTo.append(list);
_setSelected(self, list);
list.delegate('li', 'click', { 'timepicker': self }, function(e) {
list.on('click', 'li', function(e) {
self.addClass('ui-timepicker-hideme');
self[0].focus();
@@ -297,7 +344,17 @@ version: 1.2.2
_selectValue(self);
list.hide();
});
};
}
function _generateBaseDate()
{
var _baseDate = new Date();
var _currentTimezoneOffset = _baseDate.getTimezoneOffset()*60000;
_baseDate.setHours(0); _baseDate.setMinutes(0); _baseDate.setSeconds(0);
var _baseDateTimezoneOffset = _baseDate.getTimezoneOffset()*60000;
return new Date(_baseDate.valueOf() - _baseDateTimezoneOffset + _currentTimezoneOffset);
}
function _findRow(self, list, value)
{
@@ -307,13 +364,16 @@ version: 1.2.2
var settings = self.data('timepicker-settings');
var out = false;
var halfStep = settings.step*30;
// loop through the menu items
list.find('li').each(function(i, obj) {
var jObj = $(obj);
var offset = jObj.data('time') - value;
// check if the value is less than half a step from each row
if (Math.abs(jObj.data('time') - value) <= settings.step*30) {
if (Math.abs(offset) < halfStep || offset == halfStep) {
out = jObj;
return false;
}
@@ -333,12 +393,33 @@ version: 1.2.2
function _formatValue()
{
if (this.value == '') {
if (this.value === '') {
return;
}
var self = $(this);
var prettyTime = _int2time(_time2int(this.value), self.data('timepicker-settings').timeFormat);
var seconds = _time2int(this.value);
if (seconds === null) {
self.trigger('timeFormatError');
return;
}
var settings = self.data('timepicker-settings');
if (settings.forceRoundTime) {
var offset = seconds % (settings.step*60); // step is in minutes
if (offset >= settings.step*30) {
// if offset is larger than a half step, round up
seconds += (settings.step*60) - offset;
} else {
// round down
seconds -= offset;
}
}
var prettyTime = _int2time(seconds, settings.timeFormat);
self.val(prettyTime);
}
@@ -353,7 +434,7 @@ version: 1.2.2
} else {
return true;
}
};
}
switch (e.keyCode) {
@@ -362,13 +443,11 @@ version: 1.2.2
methods.hide.apply(this);
e.preventDefault();
return false;
break;
case 38: // up
var selected = list.find('.ui-timepicker-selected');
if (!selected.length) {
var selected;
list.children().each(function(i, obj) {
if ($(obj).position().top > 0) {
selected = $(obj);
@@ -389,10 +468,9 @@ version: 1.2.2
break;
case 40: // down
var selected = list.find('.ui-timepicker-selected');
selected = list.find('.ui-timepicker-selected');
if (selected.length == 0) {
var selected;
if (selected.length === 0) {
list.children().each(function(i, obj) {
if ($(obj).position().top > 0) {
selected = $(obj);
@@ -417,7 +495,10 @@ version: 1.2.2
list.hide();
break;
case 9:
case 9: //tab
methods.hide();
break;
case 16:
case 17:
case 18:
@@ -436,11 +517,11 @@ version: 1.2.2
list.find('li').removeClass('ui-timepicker-selected');
return;
}
};
}
function _selectValue(self)
{
var settings = self.data('timepicker-settings')
var settings = self.data('timepicker-settings');
var list = self.data('timepicker-list');
var timeValue = null;
@@ -448,12 +529,12 @@ version: 1.2.2
if (cursor.length) {
// selected value found
var timeValue = cursor.data('time');
timeValue = cursor.data('time');
} else if (self.val()) {
// no selected value; fall back on input value
var timeValue = _time2int(self.val());
timeValue = _time2int(self.val());
_setSelected(self, list);
}
@@ -464,14 +545,14 @@ version: 1.2.2
}
self.trigger('change').trigger('changeTime');
};
}
function _int2duration(seconds)
{
var minutes = Math.round(seconds/60);
var duration;
if (minutes < 60) {
if (Math.abs(minutes) < 60) {
duration = [minutes, _lang.mins];
} else if (minutes == 60) {
duration = ['1', _lang.hr];
@@ -482,16 +563,21 @@ version: 1.2.2
}
return duration.join(' ');
};
}
function _int2time(seconds, format)
{
if (seconds === null) {
return;
}
var time = new Date(_baseDate.valueOf() + (seconds*1000));
var output = '';
var hour, code;
for (var i=0; i<format.length; i++) {
var code = format.charAt(i);
code = format.charAt(i);
switch (code) {
case 'a':
@@ -503,8 +589,8 @@ version: 1.2.2
break;
case 'g':
var hour = time.getHours() % 12;
output += (hour == 0) ? '12' : hour;
hour = time.getHours() % 12;
output += (hour === 0) ? '12' : hour;
break;
case 'G':
@@ -512,17 +598,17 @@ version: 1.2.2
break;
case 'h':
var hour = time.getHours() % 12;
hour = time.getHours() % 12;
if (hour != 0 && hour < 10) {
if (hour !== 0 && hour < 10) {
hour = '0'+hour;
}
output += (hour == 0) ? '12' : hour;
output += (hour === 0) ? '12' : hour;
break;
case 'H':
var hour = time.getHours();
hour = time.getHours();
output += (hour > 9) ? hour : '0'+hour;
break;
@@ -532,7 +618,7 @@ version: 1.2.2
break;
case 's':
var seconds = time.getSeconds();
seconds = time.getSeconds();
output += (seconds > 9) ? seconds : '0'+seconds;
break;
@@ -542,40 +628,42 @@ version: 1.2.2
}
return output;
};
}
function _time2int(timeString)
{
if (timeString == '') return null;
if (timeString === '') return null;
if (timeString+0 == timeString) return timeString;
if (typeof(timeString) == 'object') {
timeString = timeString.getHours()+':'+timeString.getMinutes();
timeString = timeString.getHours()+':'+timeString.getMinutes()+':'+timeString.getSeconds();
}
var d = new Date(0);
var time = timeString.toLowerCase().match(/(\d+)(?::(\d\d))?\s*([pa]?)/);
var time = timeString.toLowerCase().match(/(\d{1,2})(?::(\d{1,2}))?(?::(\d{2}))?\s*([pa]?)/);
if (!time) {
return null;
}
var hour = parseInt(time[1]*1);
var hour = parseInt(time[1]*1, 10);
var hours;
if (time[3]) {
if (time[4]) {
if (hour == 12) {
var hours = (time[3] == 'p') ? 12 : 0;
hours = (time[4] == 'p') ? 12 : 0;
} else {
var hours = (hour + (time[3] == 'p' ? 12 : 0));
hours = (hour + (time[4] == 'p' ? 12 : 0));
}
} else {
var hours = hour;
hours = hour;
}
var minutes = ( time[2]*1 || 0 );
return hours*3600 + minutes*60;
};
var seconds = ( time[3]*1 || 0 );
return hours*3600 + minutes*60 + seconds;
}
// Plugin entry
$.fn.timepicker = function(method)
@@ -584,4 +672,4 @@ version: 1.2.2
else if(typeof method === "object" || !method) { return methods.init.apply(this, arguments); }
else { $.error("Method "+ method + " does not exist on jQuery.timepicker"); }
};
})(jQuery);
}));

File diff suppressed because one or more lines are too long

View File

@@ -127,6 +127,7 @@ def sort_map_entries(category_map):
sort_map_entries(category_map["subcategories"][title])
category_map["children"] = [x[0] for x in sorted(things, key=lambda x: x[1]["sort_key"])]
def initialize_discussion_info(course):
global _DISCUSSIONINFO
@@ -134,32 +135,32 @@ def initialize_discussion_info(course):
return
course_id = course.id
all_modules = get_full_modules()[course_id]
discussion_id_map = {}
unexpanded_category_map = defaultdict(list)
for location, module in all_modules.items():
if location.category == 'discussion':
skip_module = False
for key in ('id', 'discussion_category', 'for'):
if key not in module.metadata:
log.warning("Required key '%s' not in discussion %s, leaving out of category map" % (key, module.location))
skip_module = True
# get all discussion models within this course_id
all_modules = modulestore().get_items(['i4x', course.location.org, course.location.course, 'discussion', None], course_id=course_id)
if skip_module:
continue
for module in all_modules:
skip_module = False
for key in ('id', 'discussion_category', 'for'):
if key not in module.metadata:
log.warning("Required key '%s' not in discussion %s, leaving out of category map" % (key, module.location))
skip_module = True
id = module.metadata['id']
category = module.metadata['discussion_category']
title = module.metadata['for']
sort_key = module.metadata.get('sort_key', title)
category = " / ".join([x.strip() for x in category.split("/")])
last_category = category.split("/")[-1]
discussion_id_map[id] = {"location": location, "title": last_category + " / " + title}
unexpanded_category_map[category].append({"title": title, "id": id,
"sort_key": sort_key, "start_date": module.start})
if skip_module:
continue
id = module.metadata['id']
category = module.metadata['discussion_category']
title = module.metadata['for']
sort_key = module.metadata.get('sort_key', title)
category = " / ".join([x.strip() for x in category.split("/")])
last_category = category.split("/")[-1]
discussion_id_map[id] = {"location": module.location, "title": last_category + " / " + title}
unexpanded_category_map[category].append({"title": title, "id": id,
"sort_key": sort_key, "start_date": module.start})
category_map = {"entries": defaultdict(dict), "subcategories": defaultdict(dict)}
for category_path, entries in unexpanded_category_map.items():