Commit 794f32b1 by Dmitry Viskov

1. New auxiliary view "grade_available_responses_view" which displays the staff grading area

2. New auxiliary view for course ORA blocks listing (based on backgrid.js)
parent 8af51c16
......@@ -145,6 +145,12 @@
"gettext",
"ngettext",
// Backgrid library
"Backgrid",
// XBlock dependencies
"XBlock",
// ORA-specific globals
"OpenAssessment"
]
......
......@@ -32,6 +32,7 @@ before_script:
- "export DISPLAY=:99.0"
- "sh -e /etc/init.d/xvfb start"
script:
- "make verify-generated-files"
- "make test"
- "python manage.py makemessages -l eo"
branches:
......
......@@ -2,9 +2,11 @@ include LICENSE
include AUTHORS
include README.rst
include openassessment/xblock/static/css/*.css
include openassessment/xblock/static/css/lib/backgrid/*.css
include openassessment/xblock/static/js/openassessment*.min.js
include openassessment/xblock/static/js/lib/backgrid/*.js
recursive-include openassessment/xblock/static/js/src *.js
recursive-include openassessment/templates *.html
recursive-include openassessment/templates *.html *.underscore
recursive-include openassessment/locale *.po
recursive-include openassessment/locale *.mo
global-exclude */test*
......
......@@ -28,15 +28,17 @@ install-nltk-data:
STATIC_JS = openassessment/xblock/static/js
STATIC_CSS = openassessment/xblock/static/css
javascript:
node_modules/.bin/uglifyjs $(STATIC_JS)/src/oa_shared.js $(STATIC_JS)/src/*.js $(STATIC_JS)/src/lms/*.js > "$(STATIC_JS)/openassessment-lms.min.js"
node_modules/.bin/uglifyjs $(STATIC_JS)/src/oa_shared.js $(STATIC_JS)/src/*.js $(STATIC_JS)/src/studio/*.js > "$(STATIC_JS)/openassessment-studio.min.js"
javascript: update-npm-requirements
node_modules/.bin/uglifyjs $(STATIC_JS)/src/oa_shared.js $(STATIC_JS)/src/*.js $(STATIC_JS)/src/lms/*.js $(STATIC_JS)/lib/backgrid/backgrid.min.js -c warnings=false > "$(STATIC_JS)/openassessment-lms.min.js"
node_modules/.bin/uglifyjs $(STATIC_JS)/src/oa_shared.js $(STATIC_JS)/src/*.js $(STATIC_JS)/src/studio/*.js $(STATIC_JS)/lib/backgrid/backgrid.min.js -c warnings=false > "$(STATIC_JS)/openassessment-studio.min.js"
sass:
python scripts/compile_sass.py
verify-generated-files: javascript sass
@git diff --quiet || (echo 'Modifications exist locally! Run `make javascript` or `make sass` to update bundled files.'; exit 1)
install-test:
pip install -q -r requirements/test.txt
......@@ -50,8 +52,8 @@ install-dev:
install: install-wheels install-python install-js install-nltk-data install-test install-dev javascript sass
quality:
jshint openassessment/xblock/static/js/src -c .jshintrc --verbose
./node_modules/jscs/bin/jscs openassessment/xblock/static/js/src --verbose
jshint $(STATIC_JS)/src -c .jshintrc --verbose
./node_modules/jscs/bin/jscs $(STATIC_JS)/src --verbose
./scripts/run-pep8.sh
./scripts/run-pylint.sh
......@@ -76,3 +78,8 @@ test-acceptance:
test-a11y:
./scripts/test-acceptance.sh accessibility
update-npm-requirements:
npm update --silent
cp ./node_modules/backgrid/lib/backgrid*.js $(STATIC_JS)/lib/backgrid/
cp ./node_modules/backgrid/lib/backgrid*.css $(STATIC_CSS)/lib/backgrid/
\ No newline at end of file
......@@ -30,6 +30,8 @@ module.exports = function(config) {
'js/lib/jquery.timepicker.min.js',
'js/lib/jquery-ui-1.10.4.min.js',
'js/lib/underscore-min.js',
'../../../node_modules/backbone/backbone.js',
'../../../node_modules/backgrid/lib/backgrid.min.js',
'../../../node_modules/requirejs/require.js',
'../../../require-config.js',
{
......
{% load i18n %}
{% spaceless %}
<div class="wrapper wrapper--xblock wrapper--openassessment theme--basic">
<div class="openassessment problem">
<div class="wrapper--grid">
{% if title %}
<h4 class="openassessment__title problem__header">{% trans title %}</h4>
{% endif %}
{% if staff_assessment_required %}
<div class="openassessment__staff-area">
<div class="openassessment__staff-grading wrapper--staff-grading">
<div class="staff-grading ui-staff">
<h5 class="staff-grading__title">
<span class="staff-info__title__copy">{% trans "Grade Available Responses" %}</span>
</h5>
<div class="staff-info__content ui-staff__content">
{% include "openassessmentblock/staff_area/oa_staff_grade_learners.html" with staff_assessment_ungraded=staff_assessment_ungraded staff_assessment_in_progress=staff_assessment_in_progress %}
</div>
</div>
</div>
</div>
{% else %}
<div class="openassessment__staff-area-unavailable">
{% trans "Grade Available Responses is unavailable. This item is not configured for Staff Assessment." %}
</div>
{% endif %}
</div>
</div>
</div>
{% endspaceless %}
{% load i18n %}
{% spaceless %}
<section class="open-response-assessment-block"
data-item-view-enabled="{{ ora_item_view_enabled|yesno:'1,0' }}"
data-rendered=0>
<div class="open-response-assessment-msg">{% trans "Please wait" %}</div>
<div class="open-response-assessment-content">
<div class="open-response-assessment-summary"></div>
<hr/>
<div class="open-response-assessment-main-table"></div>
</div>
<div class="open-response-assessment-item">
<div class="open-response-assessment-item-breadcrumbs"></div>
<div class="open-response-assessment-item-block"></div>
</div>
</section>
<script type="text/template" id="open-response-assessment-items">{{ ora_items |safe }}</script>
<script type="text/template" id="open-response-assessment-summary-tpl">
{% include "openassessmentblock/instructor_dashboard/open-response-assessment-summary.underscore" %}
</script>
{% endspaceless %}
<table class="backgrid open-response-assessment-summary">
<tbody>
<tr>
<% for (var i = 0; i < oraSummary.length; i++) {
var s = oraSummary[i];
%>
<td class="string-cell renderable <%- s.class %>">
<div class="ora-summary-title"><%- s.title %></div>
<div class="ora-summary-value"><%- s.value %></div>
</td>
<% } %>
</tr>
</tbody>
</table>
"""
The mixin with handlers for the course ora blocks listing view.
"""
import json
from webob import Response
from xblock.core import XBlock
from openassessment.data import OraAggregateData
from openassessment.xblock.staff_area_mixin import require_course_staff
class CourseItemsListingMixin(object):
"""
The mixin with handlers for the course ora blocks listing view.
"""
@XBlock.handler
@require_course_staff('STAFF_AREA')
def get_ora2_responses(self, request, suffix=''): # pylint: disable=unused-argument
"""
Get information about all ora2 blocks in the course with response count for each step.
"""
responses = OraAggregateData.collect_ora2_responses(unicode(self.course_id))
return Response(json.dumps(responses), content_type='application/json')
......@@ -37,6 +37,7 @@ from openassessment.xblock.student_training_mixin import StudentTrainingMixin
from openassessment.xblock.validation import validator
from openassessment.xblock.resolve_dates import resolve_dates, parse_date_value, DISTANT_PAST, DISTANT_FUTURE
from openassessment.xblock.data_conversion import create_prompts_list, create_rubric_dict, update_assessments_format
from openassessment.xblock.course_items_listing_mixin import CourseItemsListingMixin
logger = logging.getLogger(__name__)
......@@ -97,21 +98,20 @@ def load(path):
@XBlock.needs("i18n")
@XBlock.needs("user")
class OpenAssessmentBlock(
MessageMixin,
SubmissionMixin,
PeerAssessmentMixin,
SelfAssessmentMixin,
StaffAssessmentMixin,
StudioMixin,
GradeMixin,
LeaderboardMixin,
StaffAreaMixin,
WorkflowMixin,
StudentTrainingMixin,
LmsCompatibilityMixin,
XBlock,
):
class OpenAssessmentBlock(MessageMixin,
SubmissionMixin,
PeerAssessmentMixin,
SelfAssessmentMixin,
StaffAssessmentMixin,
StudioMixin,
GradeMixin,
LeaderboardMixin,
StaffAreaMixin,
WorkflowMixin,
StudentTrainingMixin,
LmsCompatibilityMixin,
CourseItemsListingMixin,
XBlock):
"""Displays a prompt and provides an area where students can compose a response."""
public_dir = 'static'
......@@ -361,9 +361,90 @@ class OpenAssessmentBlock(
"show_staff_area": self.is_course_staff and not self.in_studio_preview,
}
template = get_template("openassessmentblock/oa_base.html")
return self._create_fragment(template, context_dict, initialize_js_func='OpenAssessmentBlock')
def ora_blocks_listing_view(self, context=None):
"""This view is used in the Open Response Assessment tab in the LMS Instructor Dashboard
to display all available course ORA blocks.
Args:
context: contains two items:
"ora_items" - all course items with names and parents, example:
[{"parent_name": "Vertical name",
"name": "ORA Display Name",
"url_grade_available_responses": "/grade_available_responses_view",
"staff_assessment": false,
"parent_id": "vertical_block_id",
"url_base": "/student_view",
"id": "openassessment_block_id"
}, ...]
"ora_item_view_enabled" - enabled LMS API endpoint to serve XBlock view or not
Returns:
(Fragment): The HTML Fragment for this XBlock.
"""
ora_items = context.get('ora_items', []) if context else []
ora_item_view_enabled = context.get('ora_item_view_enabled', False) if context else False
context_dict = {
"ora_items": json.dumps(ora_items),
"ora_item_view_enabled": ora_item_view_enabled
}
template = get_template('openassessmentblock/instructor_dashboard/oa_listing.html')
min_postfix = '.min' if settings.DEBUG else ''
return self._create_fragment(
template,
context_dict,
initialize_js_func='CourseOpenResponsesListingBlock',
additional_css=["static/css/lib/backgrid/backgrid%s.css" % min_postfix],
additional_js=["static/js/lib/backgrid/backgrid%s.js" % min_postfix]
)
def grade_available_responses_view(self, context=None):
"""Grade Available Responses view.
Auxiliary view which displays the staff grading area
(used in the Open Response Assessment tab in the Instructor Dashboard of LMS)
Args:
context: Not used for this view.
Returns:
(Fragment): The HTML Fragment for this XBlock.
"""
student_item = self.get_student_item_dict()
staff_assessment_required = "staff-assessment" in self.assessment_steps
context_dict = {
"title": self.title,
'staff_assessment_required': staff_assessment_required
}
if staff_assessment_required:
context_dict.update(
self.get_staff_assessment_statistics_context(student_item["course_id"], student_item["item_id"])
)
template = get_template('openassessmentblock/instructor_dashboard/oa_grade_available_responses.html')
return self._create_fragment(template, context_dict, initialize_js_func='StaffAssessmentBlock')
def _create_fragment(self, template, context_dict, initialize_js_func, additional_css=None, additional_js=None):
"""
Creates a fragment for display.
"""
context = Context(context_dict)
fragment = Fragment(template.render(context))
if additional_css is None:
additional_css = []
if additional_js is None:
additional_js = []
i18n_service = self.runtime.service(self, 'i18n')
if hasattr(i18n_service, 'get_language_bidi') and i18n_service.get_language_bidi():
css_url = "static/css/openassessment-rtl.css"
......@@ -371,13 +452,22 @@ class OpenAssessmentBlock(
css_url = "static/css/openassessment-ltr.css"
if settings.DEBUG:
for css in additional_css:
fragment.add_css_url(self.runtime.local_resource_url(self, css))
fragment.add_css_url(self.runtime.local_resource_url(self, css_url))
for js in additional_js:
self.add_javascript_files(fragment, js)
self.add_javascript_files(fragment, "static/js/src/oa_shared.js")
self.add_javascript_files(fragment, "static/js/src/oa_server.js")
self.add_javascript_files(fragment, "static/js/src/lms")
else:
# TODO: load CSS and JavaScript as URLs once they can be served by the CDN
for css in additional_css:
fragment.add_css(load(css))
fragment.add_css(load(css_url))
# minified additional_js should be already included in 'make javascript'
fragment.add_javascript(load("static/js/openassessment-lms.min.js"))
js_context_dict = {
"ALLOWED_IMAGE_MIME_TYPES": self.ALLOWED_IMAGE_MIME_TYPES,
......@@ -385,7 +475,7 @@ class OpenAssessmentBlock(
"FILE_EXT_BLACK_LIST": self.FILE_EXT_BLACK_LIST,
"FILE_TYPE_WHITE_LIST": self.white_listed_file_types,
}
fragment.initialize_js('OpenAssessmentBlock', js_context_dict)
fragment.initialize_js(initialize_js_func, js_context_dict)
return fragment
@property
......
/*
backgrid
http://github.com/cloudflare/backgrid
Copyright (c) 2013-present Cloudflare, Inc. and contributors
Licensed under the MIT license.
*/
.backgrid-container {
position: relative;
display: block;
width: 100%;
height: 465px;
padding: 0;
overflow: auto;
border: 0;
}
.backgrid {
width: 100%;
max-width: 100%;
background-color: transparent;
border-collapse: collapse;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
.backgrid th,
.backgrid td {
display: none;
height: 20px;
max-width: 250px;
padding: 4px 5px;
overflow: hidden;
line-height: 20px;
text-align: left;
text-overflow: ellipsis;
white-space: nowrap;
vertical-align: middle;
border-bottom: 1px solid #DDD;
}
.backgrid th.renderable,
.backgrid td.renderable {
display: table-cell;
}
.backgrid th {
font-weight: bold;
text-align: center;
}
.backgrid th.sortable a {
text-decoration: none;
white-space: nowrap;
cursor: pointer;
}
.backgrid thead th {
vertical-align: bottom;
background-color: #f9f9f9;
}
.backgrid thead th button {
display: block;
padding: 0;
background: none;
border: none;
}
.backgrid.backgrid-striped tbody tr:nth-child(even) {
background-color: #f9f9f9;
}
.backgrid tbody tr.empty {
font-style: italic;
color: gray;
}
.backgrid tbody tr.empty td {
display: table-cell;
text-align: center;
}
.backgrid td.editor {
padding: 0;
}
.backgrid td.editor,
.backgrid tbody tr:nth-child(odd) td.editor {
background-color: rgba(82, 168, 236, 0.1);
outline: 1px solid rgba(82, 168, 236, 0.8);
outline-offset: -1px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
-webkit-transition-duration: 200ms;
-moz-transition-duration: 200ms;
-o-transition-duration: 200ms;
transition-duration: 200ms;
-webkit-transition-property: width, outline, background-color;
-moz-transition-property: width, outline, background-color;
-o-transition-property: width, outline, background-color;
transition-property: width, outline, background-color;
-webkit-transition-timing-function: ease-in-out;
-moz-transition-timing-function: ease-in-out;
-o-transition-timing-function: ease-in-out;
transition-timing-function: ease-in-out;
}
.backgrid td.editor input[type=text] {
display: block;
width: 100%;
height: 100%;
padding: 0 5px;
margin: 0;
background-color: transparent;
border: 0;
outline: 0;
-webkit-box-shadow: none;
-moz-box-shadow: none;
box-shadow: none;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
-webkit-appearance: none;
-moz-appearance: none;
}
.backgrid td.editor input[type=text]::-ms-clear {
display: none;
}
.backgrid td.error,
.backgrid tbody tr:nth-child(odd) td.error {
background-color: rgba(255, 210, 77, 0.1);
outline: 1px solid #ffd24d;
}
.backgrid td.editor :focus,
.backgrid th.editor :focus {
outline: 0;
}
.backgrid .sort-caret {
display: inline-block;
width: 0;
height: 0;
margin-left: 0.3em;
border: 0;
content: "";
}
.backgrid .ascending .sort-caret {
vertical-align: baseline;
border-top: none;
border-right: 4px solid transparent;
border-bottom: 4px solid #000000;
border-left: 4px solid transparent;
}
.backgrid .descending .sort-caret {
vertical-align: super;
border-top: 4px solid #000000;
border-right: 4px solid transparent;
border-bottom: none;
border-left: 4px solid transparent;
}
.backgrid .string-cell,
.backgrid .uri-cell,
.backgrid .email-cell,
.backgrid .string-cell.editor input[type=text],
.backgrid .uri-cell.editor input[type=text],
.backgrid .email-cell.editor input[type=text] {
text-align: left;
}
.backgrid .date-cell,
.backgrid .time-cell,
.backgrid .datetime-cell,
.backgrid .number-cell,
.backgrid .integer-cell,
.backgrid .percent-cell,
.backgrid .date-cell.editor input[type=text],
.backgrid .time-cell.editor input[type=text],
.backgrid .datetime-cell.editor input[type=text],
.backgrid .number-cell.editor input[type=text],
.backgrid .integer-cell.editor input[type=text],
.backgrid .percent-cell.editor input[type=text] {
text-align: right;
}
.backgrid .boolean-cell,
.backgrid .boolean-cell.editor input[type=checkbox] {
text-align: center;
}
.backgrid .select-cell {
text-align: center;
}
.backgrid .select-cell.editor {
padding: 0;
}
.backgrid .select-cell.editor select {
display: block;
width: 100%;
height: 28px;
padding: 4px 5px;
margin: 0;
line-height: 28px;
vertical-align: middle;
background-color: white;
border: 0;
outline: 0;
-webkit-box-shadow: none;
-moz-box-shadow: none;
box-shadow: none;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.backgrid .select-cell.editor select[multiple] {
height: auto;
}
.backgrid .select-cell.editor :focus {
border: 0;
outline: 0;
}
.backgrid .select-cell.editor select::-moz-focus-inner,
.backgrid .select-cell.editor optgroup::-moz-focus-inner,
.backgrid .select-cell.editor option::-moz-focus-inner,
.backgrid .select-cell.editor select::-o-focus-inner,
.backgrid .select-cell.editor optgroup::-o-focus-inner,
.backgrid .select-cell.editor option::-o-focus-inner {
border: 0;
}
\ No newline at end of file
.backgrid-container{position:relative;display:block;width:100%;height:465px;padding:0;overflow:auto;border:0}.backgrid{width:100%;max-width:100%;background-color:transparent;border-collapse:collapse;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.backgrid th,.backgrid td{display:none;height:20px;max-width:250px;padding:4px 5px;overflow:hidden;line-height:20px;text-align:left;text-overflow:ellipsis;white-space:nowrap;vertical-align:middle;border-bottom:1px solid #DDD}.backgrid th.renderable,.backgrid td.renderable{display:table-cell}.backgrid th{font-weight:bold;text-align:center}.backgrid th.sortable a{text-decoration:none;white-space:nowrap;cursor:pointer}.backgrid thead th{vertical-align:bottom;background-color:#f9f9f9}.backgrid thead th button{display:block;padding:0;background:0;border:0}.backgrid.backgrid-striped tbody tr:nth-child(even){background-color:#f9f9f9}.backgrid tbody tr.empty{font-style:italic;color:gray}.backgrid tbody tr.empty td{display:table-cell;text-align:center}.backgrid td.editor{padding:0}.backgrid td.editor,.backgrid tbody tr:nth-child(odd) td.editor{background-color:rgba(82,168,236,0.1);outline:1px solid rgba(82,168,236,0.8);outline-offset:-1px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;-webkit-transition-duration:200ms;-moz-transition-duration:200ms;-o-transition-duration:200ms;transition-duration:200ms;-webkit-transition-property:width,outline,background-color;-moz-transition-property:width,outline,background-color;-o-transition-property:width,outline,background-color;transition-property:width,outline,background-color;-webkit-transition-timing-function:ease-in-out;-moz-transition-timing-function:ease-in-out;-o-transition-timing-function:ease-in-out;transition-timing-function:ease-in-out}.backgrid td.editor input[type=text]{display:block;width:100%;height:100%;padding:0 5px;margin:0;background-color:transparent;border:0;outline:0;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;-webkit-appearance:none;-moz-appearance:none}.backgrid td.editor input[type=text]::-ms-clear{display:none}.backgrid td.error,.backgrid tbody tr:nth-child(odd) td.error{background-color:rgba(255,210,77,0.1);outline:1px solid #ffd24d}.backgrid td.editor :focus,.backgrid th.editor:focus{outline:0}.backgrid .sort-caret{display:inline-block;width:0;height:0;margin-left:.3em;border:0;content:""}.backgrid .ascending .sort-caret{vertical-align:baseline;border-top:0;border-right:4px solid transparent;border-bottom:4px solid #000;border-left:4px solid transparent}.backgrid .descending .sort-caret{vertical-align:super;border-top:4px solid #000;border-right:4px solid transparent;border-bottom:0;border-left:4px solid transparent}.backgrid .string-cell,.backgrid .uri-cell,.backgrid .email-cell,.backgrid .string-cell.editor input[type=text],.backgrid .uri-cell.editor input[type=text],.backgrid .email-cell.editor input[type=text]{text-align:left}.backgrid .date-cell,.backgrid .time-cell,.backgrid .datetime-cell,.backgrid .number-cell,.backgrid .integer-cell,.backgrid .percent-cell,.backgrid .date-cell.editor input[type=text],.backgrid .time-cell.editor input[type=text],.backgrid .datetime-cell.editor input[type=text],.backgrid .number-cell.editor input[type=text],.backgrid .integer-cell.editor input[type=text],.backgrid .percent-cell.editor input[type=text]{text-align:right}.backgrid .boolean-cell,.backgrid .boolean-cell.editor input[type=checkbox]{text-align:center}.backgrid .select-cell{text-align:center}.backgrid .select-cell.editor{padding:0}.backgrid .select-cell.editor select{display:block;width:100%;height:28px;padding:4px 5px;margin:0;line-height:28px;vertical-align:middle;background-color:white;border:0;outline:0;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.backgrid .select-cell.editor select[multiple]{height:auto}.backgrid .select-cell.editor :focus{border:0;outline:0}.backgrid .select-cell.editor select::-moz-focus-inner,.backgrid .select-cell.editor optgroup::-moz-focus-inner,.backgrid .select-cell.editor option::-moz-focus-inner,.backgrid .select-cell.editor select::-o-focus-inner,.backgrid .select-cell.editor optgroup::-o-focus-inner,.backgrid .select-cell.editor option::-o-focus-inner{border:0}
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -1213,5 +1213,23 @@
"submission_due": "2020-01-01T00:00"
},
"output": "oa_response_date.html"
},
{
"template": "openassessmentblock/instructor_dashboard/oa_grade_available_responses.html",
"context": {
"title": "Test ABC",
"staff_assessment_required": true,
"staff_assessment_ungraded": 9,
"staff_assessment_in_progress": 2
},
"output": "oa_grade_available_responses_separate_view.html"
},
{
"template": "openassessmentblock/instructor_dashboard/oa_listing.html",
"context": {
"ora_item_view_enabled": "1",
"ora_items": ""
},
"output": "oa_listing_view.html"
}
]
/*!
backgrid 0.3.8
http://github.com/cloudflare/backgrid
Copyright (c) 2017 Cloudflare, Inc. and contributors <jwong@cloudflare.com>
Licensed under the MIT license.
*/
(function (root, factory) {
if (typeof define === "function" && define.amd) {
// AMD (+ global for extensions)
define(["underscore", "backbone"], function (_, Backbone) {
return (root.Backgrid = factory(_, Backbone));
});
} else if (typeof exports === "object") {
// CommonJS
module.exports = factory(require("underscore"), require("backbone"));
} else {
// Browser
root.Backgrid = factory(root._, root.Backbone);
}}(this, function (_, Backbone) {
"use strict";
/*
backgrid
http://github.com/cloudflare/backgrid
Copyright (c) 2013-present Cloudflare, Inc. and contributors
Licensed under the MIT license.
*/
// Copyright 2009, 2010 Kristopher Michael Kowal
// https://github.com/kriskowal/es5-shim
// ES5 15.5.4.20
// http://es5.github.com/#x15.5.4.20
var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" +
"\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" +
"\u2029\uFEFF";
if (!String.prototype.trim || ws.trim()) {
// http://blog.stevenlevithan.com/archives/faster-trim-javascript
// http://perfectionkills.com/whitespace-deviations/
ws = "[" + ws + "]";
var trimBeginRegexp = new RegExp("^" + ws + ws + "*"),
trimEndRegexp = new RegExp(ws + ws + "*$");
String.prototype.trim = function trim() {
if (this === undefined || this === null) {
throw new TypeError("can't convert " + this + " to object");
}
return String(this)
.replace(trimBeginRegexp, "")
.replace(trimEndRegexp, "");
};
}
function lpad(str, length, padstr) {
var paddingLen = length - (str + '').length;
paddingLen = paddingLen < 0 ? 0 : paddingLen;
var padding = '';
for (var i = 0; i < paddingLen; i++) {
padding = padding + padstr;
}
return padding + str;
}
var $ = Backbone.$;
var Backgrid = {
Extension: {},
resolveNameToClass: function (name, suffix) {
if (_.isString(name)) {
var key = _.map(name.split('-'), function (e) {
return e.slice(0, 1).toUpperCase() + e.slice(1);
}).join('') + suffix;
var klass = Backgrid[key] || Backgrid.Extension[key];
if (_.isUndefined(klass)) {
throw new ReferenceError("Class '" + key + "' not found");
}
return klass;
}
return name;
},
callByNeed: function () {
var value = arguments[0];
if (!_.isFunction(value)) return value;
var context = arguments[1];
var args = [].slice.call(arguments, 2);
return value.apply(context, !!(args + '') ? args : []);
}
};
_.extend(Backgrid, Backbone.Events);
/**
Command translates a DOM Event into commands that Backgrid
recognizes. Interested parties can listen on selected Backgrid events that
come with an instance of this class and act on the commands.
It is also possible to globally rebind the keyboard shortcuts by replacing
the methods in this class' prototype.
@class Backgrid.Command
@constructor
*/
var Command = Backgrid.Command = function (evt) {
_.extend(this, {
altKey: !!evt.altKey,
"char": evt["char"],
charCode: evt.charCode,
ctrlKey: !!evt.ctrlKey,
key: evt.key,
keyCode: evt.keyCode,
locale: evt.locale,
location: evt.location,
metaKey: !!evt.metaKey,
repeat: !!evt.repeat,
shiftKey: !!evt.shiftKey,
which: evt.which
});
};
_.extend(Command.prototype, {
/**
Up Arrow
@member Backgrid.Command
*/
moveUp: function () { return this.keyCode == 38; },
/**
Down Arrow
@member Backgrid.Command
*/
moveDown: function () { return this.keyCode === 40; },
/**
Shift Tab
@member Backgrid.Command
*/
moveLeft: function () { return this.shiftKey && this.keyCode === 9; },
/**
Tab
@member Backgrid.Command
*/
moveRight: function () { return !this.shiftKey && this.keyCode === 9; },
/**
Enter
@member Backgrid.Command
*/
save: function () { return this.keyCode === 13; },
/**
Esc
@member Backgrid.Command
*/
cancel: function () { return this.keyCode === 27; },
/**
None of the above.
@member Backgrid.Command
*/
passThru: function () {
return !(this.moveUp() || this.moveDown() || this.moveLeft() ||
this.moveRight() || this.save() || this.cancel());
}
});
/*
backgrid
http://github.com/cloudflare/backgrid
Copyright (c) 2013-present Cloudflare, Inc. and contributors
Licensed under the MIT license.
*/
/**
Just a convenient class for interested parties to subclass.
The default Cell classes don't require the formatter to be a subclass of
Formatter as long as the fromRaw(rawData) and toRaw(formattedData) methods
are defined.
@abstract
@class Backgrid.CellFormatter
@constructor
*/
var CellFormatter = Backgrid.CellFormatter = function () {};
_.extend(CellFormatter.prototype, {
/**
Takes a raw value from a model and returns an optionally formatted string
for display. The default implementation simply returns the supplied value
as is without any type conversion.
@member Backgrid.CellFormatter
@param {*} rawData
@param {Backbone.Model} model Used for more complicated formatting
@return {*}
*/
fromRaw: function (rawData, model) {
return rawData;
},
/**
Takes a formatted string, usually from user input, and returns a
appropriately typed value for persistence in the model.
If the user input is invalid or unable to be converted to a raw value
suitable for persistence in the model, toRaw must return `undefined`.
@member Backgrid.CellFormatter
@param {string} formattedData
@param {Backbone.Model} model Used for more complicated formatting
@return {*|undefined}
*/
toRaw: function (formattedData, model) {
return formattedData;
}
});
/**
A floating point number formatter. Doesn't understand scientific notation at
the moment.
@class Backgrid.NumberFormatter
@extends Backgrid.CellFormatter
@constructor
@throws {RangeError} If decimals < 0 or > 20.
*/
var NumberFormatter = Backgrid.NumberFormatter = function (options) {
_.extend(this, this.defaults, options || {});
if (this.decimals < 0 || this.decimals > 20) {
throw new RangeError("decimals must be between 0 and 20");
}
};
NumberFormatter.prototype = new CellFormatter();
_.extend(NumberFormatter.prototype, {
/**
@member Backgrid.NumberFormatter
@cfg {Object} options
@cfg {number} [options.decimals=2] Number of decimals to display. Must be an integer.
@cfg {string} [options.decimalSeparator='.'] The separator to use when
displaying decimals.
@cfg {string} [options.orderSeparator=','] The separator to use to
separator thousands. May be an empty string.
*/
defaults: {
decimals: 2,
decimalSeparator: '.',
orderSeparator: ','
},
HUMANIZED_NUM_RE: /(\d)(?=(?:\d{3})+$)/g,
/**
Takes a floating point number and convert it to a formatted string where
every thousand is separated by `orderSeparator`, with a `decimal` number of
decimals separated by `decimalSeparator`. The number returned is rounded
the usual way.
@member Backgrid.NumberFormatter
@param {number} number
@param {Backbone.Model} model Used for more complicated formatting
@return {string}
*/
fromRaw: function (number, model) {
if (_.isNull(number) || _.isUndefined(number)) return '';
number = parseFloat(number).toFixed(~~this.decimals);
var parts = number.split('.');
var integerPart = parts[0];
var decimalPart = parts[1] ? (this.decimalSeparator || '.') + parts[1] : '';
return integerPart.replace(this.HUMANIZED_NUM_RE, '$1' + this.orderSeparator) + decimalPart;
},
/**
Takes a string, possibly formatted with `orderSeparator` and/or
`decimalSeparator`, and convert it back to a number.
@member Backgrid.NumberFormatter
@param {string} formattedData
@param {Backbone.Model} model Used for more complicated formatting
@return {number|undefined} Undefined if the string cannot be converted to
a number.
*/
toRaw: function (formattedData, model) {
formattedData = formattedData.trim();
if (formattedData === '') return null;
var rawData = '';
var thousands = formattedData.split(this.orderSeparator);
for (var i = 0; i < thousands.length; i++) {
rawData += thousands[i];
}
var decimalParts = rawData.split(this.decimalSeparator);
rawData = '';
for (var i = 0; i < decimalParts.length; i++) {
rawData = rawData + decimalParts[i] + '.';
}
if (rawData[rawData.length - 1] === '.') {
rawData = rawData.slice(0, rawData.length - 1);
}
var result = (rawData * 1).toFixed(~~this.decimals) * 1;
if (_.isNumber(result) && !_.isNaN(result)) return result;
}
});
/**
A number formatter that converts a floating point number, optionally
multiplied by a multiplier, to a percentage string and vice versa.
@class Backgrid.PercentFormatter
@extends Backgrid.NumberFormatter
@constructor
@throws {RangeError} If decimals < 0 or > 20.
*/
var PercentFormatter = Backgrid.PercentFormatter = function () {
Backgrid.NumberFormatter.apply(this, arguments);
};
PercentFormatter.prototype = new Backgrid.NumberFormatter(),
_.extend(PercentFormatter.prototype, {
/**
@member Backgrid.PercentFormatter
@cfg {Object} options
@cfg {number} [options.multiplier=1] The number used to multiply the model
value for display.
@cfg {string} [options.symbol='%'] The symbol to append to the percentage
string.
*/
defaults: _.extend({}, NumberFormatter.prototype.defaults, {
multiplier: 1,
symbol: "%"
}),
/**
Takes a floating point number, where the number is first multiplied by
`multiplier`, then converted to a formatted string like
NumberFormatter#fromRaw, then finally append `symbol` to the end.
@member Backgrid.PercentFormatter
@param {number} rawValue
@param {Backbone.Model} model Used for more complicated formatting
@return {string}
*/
fromRaw: function (number, model) {
var args = [].slice.call(arguments, 1);
args.unshift(number * this.multiplier);
return (NumberFormatter.prototype.fromRaw.apply(this, args) || "0") + this.symbol;
},
/**
Takes a string, possibly appended with `symbol` and/or `decimalSeparator`,
and convert it back to a number for the model like NumberFormatter#toRaw,
and then dividing it by `multiplier`.
@member Backgrid.PercentFormatter
@param {string} formattedData
@param {Backbone.Model} model Used for more complicated formatting
@return {number|undefined} Undefined if the string cannot be converted to
a number.
*/
toRaw: function (formattedValue, model) {
var tokens = formattedValue.split(this.symbol);
if (tokens && tokens[0] && tokens[1] === "" || tokens[1] == null) {
var rawValue = NumberFormatter.prototype.toRaw.call(this, tokens[0]);
if (_.isUndefined(rawValue)) return rawValue;
return rawValue / this.multiplier;
}
}
});
/**
Formatter to converts between various datetime formats.
This class only understands ISO-8601 formatted datetime strings and UNIX
offset (number of milliseconds since UNIX Epoch). See
Backgrid.Extension.MomentFormatter if you need a much more flexible datetime
formatter.
@class Backgrid.DatetimeFormatter
@extends Backgrid.CellFormatter
@constructor
@throws {Error} If both `includeDate` and `includeTime` are false.
*/
var DatetimeFormatter = Backgrid.DatetimeFormatter = function (options) {
_.extend(this, this.defaults, options || {});
if (!this.includeDate && !this.includeTime) {
throw new Error("Either includeDate or includeTime must be true");
}
};
DatetimeFormatter.prototype = new CellFormatter();
_.extend(DatetimeFormatter.prototype, {
/**
@member Backgrid.DatetimeFormatter
@cfg {Object} options
@cfg {boolean} [options.includeDate=true] Whether the values include the
date part.
@cfg {boolean} [options.includeTime=true] Whether the values include the
time part.
@cfg {boolean} [options.includeMilli=false] If `includeTime` is true,
whether to include the millisecond part, if it exists.
*/
defaults: {
includeDate: true,
includeTime: true,
includeMilli: false
},
DATE_RE: /^([+\-]?\d{4})-(\d{2})-(\d{2})$/,
TIME_RE: /^(\d{2}):(\d{2}):(\d{2})(\.(\d{3}))?$/,
ISO_SPLITTER_RE: /T|Z| +/,
_convert: function (data, validate) {
if ((data + '').trim() === '') return null;
var date, time = null;
if (_.isNumber(data)) {
var jsDate = new Date(data);
date = lpad(jsDate.getUTCFullYear(), 4, 0) + '-' + lpad(jsDate.getUTCMonth() + 1, 2, 0) + '-' + lpad(jsDate.getUTCDate(), 2, 0);
time = lpad(jsDate.getUTCHours(), 2, 0) + ':' + lpad(jsDate.getUTCMinutes(), 2, 0) + ':' + lpad(jsDate.getUTCSeconds(), 2, 0);
}
else {
data = data.trim();
var parts = data.split(this.ISO_SPLITTER_RE) || [];
date = this.DATE_RE.test(parts[0]) ? parts[0] : '';
time = date && parts[1] ? parts[1] : this.TIME_RE.test(parts[0]) ? parts[0] : '';
}
var YYYYMMDD = this.DATE_RE.exec(date) || [];
var HHmmssSSS = this.TIME_RE.exec(time) || [];
if (validate) {
if (this.includeDate && _.isUndefined(YYYYMMDD[0])) return;
if (this.includeTime && _.isUndefined(HHmmssSSS[0])) return;
if (!this.includeDate && date) return;
if (!this.includeTime && time) return;
}
var jsDate = new Date(Date.UTC(YYYYMMDD[1] * 1 || 0,
YYYYMMDD[2] * 1 - 1 || 0,
YYYYMMDD[3] * 1 || 0,
HHmmssSSS[1] * 1 || null,
HHmmssSSS[2] * 1 || null,
HHmmssSSS[3] * 1 || null,
HHmmssSSS[5] * 1 || null));
var result = '';
if (this.includeDate) {
result = lpad(jsDate.getUTCFullYear(), 4, 0) + '-' + lpad(jsDate.getUTCMonth() + 1, 2, 0) + '-' + lpad(jsDate.getUTCDate(), 2, 0);
}
if (this.includeTime) {
result = result + (this.includeDate ? 'T' : '') + lpad(jsDate.getUTCHours(), 2, 0) + ':' + lpad(jsDate.getUTCMinutes(), 2, 0) + ':' + lpad(jsDate.getUTCSeconds(), 2, 0);
if (this.includeMilli) {
result = result + '.' + lpad(jsDate.getUTCMilliseconds(), 3, 0);
}
}
if (this.includeDate && this.includeTime) {
result += "Z";
}
return result;
},
/**
Converts an ISO-8601 formatted datetime string to a datetime string, date
string or a time string. The timezone is ignored if supplied.
@member Backgrid.DatetimeFormatter
@param {string} rawData
@param {Backbone.Model} model Used for more complicated formatting
@return {string|null|undefined} ISO-8601 string in UTC. Null and undefined
values are returned as is.
*/
fromRaw: function (rawData, model) {
if (_.isNull(rawData) || _.isUndefined(rawData)) return '';
return this._convert(rawData);
},
/**
Converts an ISO-8601 formatted datetime string to a datetime string, date
string or a time string. The timezone is ignored if supplied. This method
parses the input values exactly the same way as
Backgrid.Extension.MomentFormatter#fromRaw(), in addition to doing some
sanity checks.
@member Backgrid.DatetimeFormatter
@param {string} formattedData
@param {Backbone.Model} model Used for more complicated formatting
@return {string|undefined} ISO-8601 string in UTC. Undefined if a date is
found when `includeDate` is false, or a time is found when `includeTime` is
false, or if `includeDate` is true and a date is not found, or if
`includeTime` is true and a time is not found.
*/
toRaw: function (formattedData, model) {
return this._convert(formattedData, true);
}
});
/**
Formatter to convert any value to string.
@class Backgrid.StringFormatter
@extends Backgrid.CellFormatter
@constructor
*/
var StringFormatter = Backgrid.StringFormatter = function () {};
StringFormatter.prototype = new CellFormatter();
_.extend(StringFormatter.prototype, {
/**
Converts any value to a string using Ecmascript's implicit type
conversion. If the given value is `null` or `undefined`, an empty string is
returned instead.
@member Backgrid.StringFormatter
@param {*} rawValue
@param {Backbone.Model} model Used for more complicated formatting
@return {string}
*/
fromRaw: function (rawValue, model) {
if (_.isUndefined(rawValue) || _.isNull(rawValue)) return '';
return rawValue + '';
}
});
/**
Simple email validation formatter.
@class Backgrid.EmailFormatter
@extends Backgrid.CellFormatter
@constructor
*/
var EmailFormatter = Backgrid.EmailFormatter = function () {};
EmailFormatter.prototype = new CellFormatter();
_.extend(EmailFormatter.prototype, {
/**
Return the input if it is a string that contains an '@' character and if
the strings before and after '@' are non-empty. If the input does not
validate, `undefined` is returned.
@member Backgrid.EmailFormatter
@param {*} formattedData
@param {Backbone.Model} model Used for more complicated formatting
@return {string|undefined}
*/
toRaw: function (formattedData, model) {
var parts = formattedData.trim().split("@");
if (parts.length === 2 && _.all(parts)) {
return formattedData;
}
}
});
/**
Formatter for SelectCell.
If the type of a model value is not a string, it is expected that a subclass
of this formatter is provided to the SelectCell, with #toRaw overridden to
convert the string value returned from the DOM back to whatever value is
expected in the model.
@class Backgrid.SelectFormatter
@extends Backgrid.CellFormatter
@constructor
*/
var SelectFormatter = Backgrid.SelectFormatter = function () {};
SelectFormatter.prototype = new CellFormatter();
_.extend(SelectFormatter.prototype, {
/**
Normalizes raw scalar or array values to an array.
@member Backgrid.SelectFormatter
@param {*} rawValue
@param {Backbone.Model} model Used for more complicated formatting
@return {Array.<*>}
*/
fromRaw: function (rawValue, model) {
return _.isArray(rawValue) ? rawValue : rawValue != null ? [rawValue] : [];
}
});
/*
backgrid
http://github.com/cloudflare/backgrid
Copyright (c) 2013-present Cloudflare, Inc. and contributors
Licensed under the MIT license.
*/
/**
Generic cell editor base class. Only defines an initializer for a number of
required parameters.
@abstract
@class Backgrid.CellEditor
@extends Backbone.View
*/
var CellEditor = Backgrid.CellEditor = Backbone.View.extend({
/**
Initializer.
@param {Object} options
@param {Backgrid.CellFormatter} options.formatter
@param {Backgrid.Column} options.column
@param {Backbone.Model} options.model
@throws {TypeError} If `formatter` is not a formatter instance, or when
`model` or `column` are undefined.
*/
initialize: function (options) {
this.formatter = options.formatter;
this.column = options.column;
if (!(this.column instanceof Column)) {
this.column = new Column(this.column);
}
this.listenTo(this.model, "backgrid:editing", this.postRender);
},
/**
Post-rendering setup and initialization. Focuses the cell editor's `el` in
this default implementation. **Should** be called by Cell classes after
calling Backgrid.CellEditor#render.
*/
postRender: function (model, column) {
if (column == null || column.get("name") == this.column.get("name")) {
this.$el.focus();
}
return this;
}
});
/**
InputCellEditor the cell editor type used by most core cell types. This cell
editor renders a text input box as its editor. The input will render a
placeholder if the value is empty on supported browsers.
@class Backgrid.InputCellEditor
@extends Backgrid.CellEditor
*/
var InputCellEditor = Backgrid.InputCellEditor = CellEditor.extend({
/** @property */
tagName: "input",
/** @property */
attributes: {
type: "text"
},
/** @property */
events: {
"blur": "saveOrCancel",
"keydown": "saveOrCancel"
},
/**
Initializer. Removes this `el` from the DOM when a `done` event is
triggered.
@param {Object} options
@param {Backgrid.CellFormatter} options.formatter
@param {Backgrid.Column} options.column
@param {Backbone.Model} options.model
@param {string} [options.placeholder]
*/
initialize: function (options) {
InputCellEditor.__super__.initialize.apply(this, arguments);
if (options.placeholder) {
this.$el.attr("placeholder", options.placeholder);
}
},
/**
Renders a text input with the cell value formatted for display, if it
exists.
*/
render: function () {
var model = this.model;
this.$el.val(this.formatter.fromRaw(model.get(this.column.get("name")), model));
return this;
},
/**
If the key pressed is `enter`, `tab`, `up`, or `down`, converts the value
in the editor to a raw value for saving into the model using the formatter.
If the key pressed is `esc` the changes are undone.
If the editor goes out of focus (`blur`) but the value is invalid, the
event is intercepted and cancelled so the cell remains in focus pending for
further action. The changes are saved otherwise.
Triggers a Backbone `backgrid:edited` event from the model when successful,
and `backgrid:error` if the value cannot be converted. Classes listening to
the `error` event, usually the Cell classes, should respond appropriately,
usually by rendering some kind of error feedback.
@param {Event} e
*/
saveOrCancel: function (e) {
var formatter = this.formatter;
var model = this.model;
var column = this.column;
var command = new Command(e);
var blurred = e.type === "blur";
if (command.moveUp() || command.moveDown() || command.moveLeft() || command.moveRight() ||
command.save() || blurred) {
e.preventDefault();
e.stopPropagation();
var val = this.$el.val();
var newValue = formatter.toRaw(val, model);
if (_.isUndefined(newValue)) {
model.trigger("backgrid:error", model, column, val);
}
else {
model.set(column.get("name"), newValue);
model.trigger("backgrid:edited", model, column, command);
}
}
// esc
else if (command.cancel()) {
// undo
e.stopPropagation();
model.trigger("backgrid:edited", model, column, command);
}
},
postRender: function (model, column) {
if (column == null || column.get("name") == this.column.get("name")) {
// move the cursor to the end on firefox if text is right aligned
if (this.$el.css("text-align") === "right") {
var val = this.$el.val();
this.$el.focus().val(null).val(val);
}
else this.$el.focus();
}
return this;
}
});
/**
The super-class for all Cell types. By default, this class renders a plain
table cell with the model value converted to a string using the
formatter. The table cell is clickable, upon which the cell will go into
editor mode, which is rendered by a Backgrid.InputCellEditor instance by
default. Upon encountering any formatting errors, this class will add an
`error` CSS class to the table cell.
@abstract
@class Backgrid.Cell
@extends Backbone.View
*/
var Cell = Backgrid.Cell = Backbone.View.extend({
/** @property */
tagName: "td",
/**
@property {Backgrid.CellFormatter|Object|string} [formatter=CellFormatter]
*/
formatter: CellFormatter,
/**
@property {Backgrid.CellEditor} [editor=Backgrid.InputCellEditor] The
default editor for all cell instances of this class. This value must be a
class, it will be automatically instantiated upon entering edit mode.
See Backgrid.CellEditor
*/
editor: InputCellEditor,
/** @property */
events: {
"click": "enterEditMode"
},
/**
Initializer.
@param {Object} options
@param {Backbone.Model} options.model
@param {Backgrid.Column} options.column
@throws {ReferenceError} If formatter is a string but a formatter class of
said name cannot be found in the Backgrid module.
*/
initialize: function (options) {
this.column = options.column;
if (!(this.column instanceof Column)) {
this.column = new Column(this.column);
}
var column = this.column, model = this.model, $el = this.$el;
var formatter = Backgrid.resolveNameToClass(column.get("formatter") ||
this.formatter, "Formatter");
if (!_.isFunction(formatter.fromRaw) && !_.isFunction(formatter.toRaw)) {
formatter = new formatter();
}
this.formatter = formatter;
this.editor = Backgrid.resolveNameToClass(this.editor, "CellEditor");
this.listenTo(model, "change:" + column.get("name"), function () {
if (!$el.hasClass("editor")) this.render();
});
this.listenTo(model, "backgrid:error", this.renderError);
this.listenTo(column, "change:editable change:sortable change:renderable",
function (column) {
var changed = column.changedAttributes();
for (var key in changed) {
if (changed.hasOwnProperty(key)) {
$el.toggleClass(key, changed[key]);
}
}
});
this.updateStateClassesMaybe();
},
updateStateClassesMaybe: function () {
var model = this.model;
var column = this.column;
var $el = this.$el;
$el.toggleClass("editable", Backgrid.callByNeed(column.editable(), column, model));
$el.toggleClass("sortable", Backgrid.callByNeed(column.sortable(), column, model));
$el.toggleClass("renderable", Backgrid.callByNeed(column.renderable(), column, model));
},
/**
Render a text string in a table cell. The text is converted from the
model's raw value for this cell's column.
*/
render: function () {
var $el = this.$el;
$el.empty();
var model = this.model;
var columnName = this.column.get("name");
$el.text(this.formatter.fromRaw(model.get(columnName), model));
$el.addClass(columnName);
this.updateStateClassesMaybe();
this.delegateEvents();
return this;
},
/**
If this column is editable, a new CellEditor instance is instantiated with
its required parameters. An `editor` CSS class is added to the cell upon
entering edit mode.
This method triggers a Backbone `backgrid:edit` event from the model when
the cell is entering edit mode and an editor instance has been constructed,
but before it is rendered and inserted into the DOM. The cell and the
constructed cell editor instance are sent as event parameters when this
event is triggered.
When this cell has finished switching to edit mode, a Backbone
`backgrid:editing` event is triggered from the model. The cell and the
constructed cell instance are also sent as parameters in the event.
When the model triggers a `backgrid:error` event, it means the editor is
unable to convert the current user input to an apprpriate value for the
model's column, and an `error` CSS class is added to the cell accordingly.
*/
enterEditMode: function () {
var model = this.model;
var column = this.column;
var editable = Backgrid.callByNeed(column.editable(), column, model);
if (editable) {
this.currentEditor = new this.editor({
column: this.column,
model: this.model,
formatter: this.formatter
});
model.trigger("backgrid:edit", model, column, this, this.currentEditor);
// Need to redundantly undelegate events for Firefox
this.undelegateEvents();
this.$el.empty();
this.$el.append(this.currentEditor.$el);
this.currentEditor.render();
this.$el.addClass("editor");
model.trigger("backgrid:editing", model, column, this, this.currentEditor);
}
},
/**
Put an `error` CSS class on the table cell.
*/
renderError: function (model, column) {
if (column == null || column.get("name") == this.column.get("name")) {
this.$el.addClass("error");
}
},
/**
Removes the editor and re-render in display mode.
*/
exitEditMode: function () {
this.$el.removeClass("error");
this.currentEditor.remove();
this.stopListening(this.currentEditor);
delete this.currentEditor;
this.$el.removeClass("editor");
this.render();
},
/**
Clean up this cell.
@chainable
*/
remove: function () {
if (this.currentEditor) {
this.currentEditor.remove.apply(this.currentEditor, arguments);
delete this.currentEditor;
}
return Cell.__super__.remove.apply(this, arguments);
}
});
/**
StringCell displays HTML escaped strings and accepts anything typed in.
@class Backgrid.StringCell
@extends Backgrid.Cell
*/
var StringCell = Backgrid.StringCell = Cell.extend({
/** @property */
className: "string-cell",
formatter: StringFormatter
});
/**
UriCell renders an HTML `<a>` anchor for the value and accepts URIs as user
input values. No type conversion or URL validation is done by the formatter
of this cell. Users who need URL validation are encourage to subclass UriCell
to take advantage of the parsing capabilities of the HTMLAnchorElement
available on HTML5-capable browsers or using a third-party library like
[URI.js](https://github.com/medialize/URI.js).
@class Backgrid.UriCell
@extends Backgrid.Cell
*/
var UriCell = Backgrid.UriCell = Cell.extend({
/** @property */
className: "uri-cell",
/**
@property {string} [title] The title attribute of the generated anchor. It
uses the display value formatted by the `formatter.fromRaw` by default.
*/
title: null,
/**
@property {string} [target="_blank"] The target attribute of the generated
anchor.
*/
target: "_blank",
initialize: function (options) {
UriCell.__super__.initialize.apply(this, arguments);
this.title = options.title || this.title;
this.target = options.target || this.target;
},
render: function () {
this.$el.empty();
var rawValue = this.model.get(this.column.get("name"));
var formattedValue = this.formatter.fromRaw(rawValue, this.model);
this.$el.append($("<a>", {
tabIndex: -1,
href: rawValue,
title: this.title || formattedValue,
target: this.target
}).text(formattedValue));
this.delegateEvents();
return this;
}
});
/**
Like Backgrid.UriCell, EmailCell renders an HTML `<a>` anchor for the
value. The `href` in the anchor is prefixed with `mailto:`. EmailCell will
complain if the user enters a string that doesn't contain the `@` sign.
@class Backgrid.EmailCell
@extends Backgrid.StringCell
*/
var EmailCell = Backgrid.EmailCell = StringCell.extend({
/** @property */
className: "email-cell",
formatter: EmailFormatter,
render: function () {
this.$el.empty();
var model = this.model;
var formattedValue = this.formatter.fromRaw(model.get(this.column.get("name")), model);
this.$el.append($("<a>", {
tabIndex: -1,
href: "mailto:" + formattedValue,
title: formattedValue
}).text(formattedValue));
this.delegateEvents();
return this;
}
});
/**
NumberCell is a generic cell that renders all numbers. Numbers are formatted
using a Backgrid.NumberFormatter.
@class Backgrid.NumberCell
@extends Backgrid.Cell
*/
var NumberCell = Backgrid.NumberCell = Cell.extend({
/** @property */
className: "number-cell",
/**
@property {number} [decimals=2] Must be an integer.
*/
decimals: NumberFormatter.prototype.defaults.decimals,
/** @property {string} [decimalSeparator='.'] */
decimalSeparator: NumberFormatter.prototype.defaults.decimalSeparator,
/** @property {string} [orderSeparator=','] */
orderSeparator: NumberFormatter.prototype.defaults.orderSeparator,
/** @property {Backgrid.CellFormatter} [formatter=Backgrid.NumberFormatter] */
formatter: NumberFormatter,
/**
Initializes this cell and the number formatter.
@param {Object} options
@param {Backbone.Model} options.model
@param {Backgrid.Column} options.column
*/
initialize: function (options) {
NumberCell.__super__.initialize.apply(this, arguments);
var formatter = this.formatter;
formatter.decimals = this.decimals;
formatter.decimalSeparator = this.decimalSeparator;
formatter.orderSeparator = this.orderSeparator;
}
});
/**
An IntegerCell is just a Backgrid.NumberCell with 0 decimals. If a floating
point number is supplied, the number is simply rounded the usual way when
displayed.
@class Backgrid.IntegerCell
@extends Backgrid.NumberCell
*/
var IntegerCell = Backgrid.IntegerCell = NumberCell.extend({
/** @property */
className: "integer-cell",
/**
@property {number} decimals Must be an integer.
*/
decimals: 0
});
/**
A PercentCell is another Backgrid.NumberCell that takes a floating number,
optionally multiplied by a multiplier and display it as a percentage.
@class Backgrid.PercentCell
@extends Backgrid.NumberCell
*/
var PercentCell = Backgrid.PercentCell = NumberCell.extend({
/** @property */
className: "percent-cell",
/** @property {number} [multiplier=1] */
multiplier: PercentFormatter.prototype.defaults.multiplier,
/** @property {string} [symbol='%'] */
symbol: PercentFormatter.prototype.defaults.symbol,
/** @property {Backgrid.CellFormatter} [formatter=Backgrid.PercentFormatter] */
formatter: PercentFormatter,
/**
Initializes this cell and the percent formatter.
@param {Object} options
@param {Backbone.Model} options.model
@param {Backgrid.Column} options.column
*/
initialize: function () {
PercentCell.__super__.initialize.apply(this, arguments);
var formatter = this.formatter;
formatter.multiplier = this.multiplier;
formatter.symbol = this.symbol;
}
});
/**
DatetimeCell is a basic cell that accepts datetime string values in RFC-2822
or W3C's subset of ISO-8601 and displays them in ISO-8601 format. For a much
more sophisticated date time cell with better datetime formatting, take a
look at the Backgrid.Extension.MomentCell extension.
@class Backgrid.DatetimeCell
@extends Backgrid.Cell
See:
- Backgrid.Extension.MomentCell
- Backgrid.DatetimeFormatter
*/
var DatetimeCell = Backgrid.DatetimeCell = Cell.extend({
/** @property */
className: "datetime-cell",
/**
@property {boolean} [includeDate=true]
*/
includeDate: DatetimeFormatter.prototype.defaults.includeDate,
/**
@property {boolean} [includeTime=true]
*/
includeTime: DatetimeFormatter.prototype.defaults.includeTime,
/**
@property {boolean} [includeMilli=false]
*/
includeMilli: DatetimeFormatter.prototype.defaults.includeMilli,
/** @property {Backgrid.CellFormatter} [formatter=Backgrid.DatetimeFormatter] */
formatter: DatetimeFormatter,
/**
Initializes this cell and the datetime formatter.
@param {Object} options
@param {Backbone.Model} options.model
@param {Backgrid.Column} options.column
*/
initialize: function (options) {
DatetimeCell.__super__.initialize.apply(this, arguments);
var formatter = this.formatter;
formatter.includeDate = this.includeDate;
formatter.includeTime = this.includeTime;
formatter.includeMilli = this.includeMilli;
var placeholder = this.includeDate ? "YYYY-MM-DD" : "";
placeholder += (this.includeDate && this.includeTime) ? "T" : "";
placeholder += this.includeTime ? "HH:mm:ss" : "";
placeholder += (this.includeTime && this.includeMilli) ? ".SSS" : "";
this.editor = this.editor.extend({
attributes: _.extend({}, this.editor.prototype.attributes, this.editor.attributes, {
placeholder: placeholder
})
});
}
});
/**
DateCell is a Backgrid.DatetimeCell without the time part.
@class Backgrid.DateCell
@extends Backgrid.DatetimeCell
*/
var DateCell = Backgrid.DateCell = DatetimeCell.extend({
/** @property */
className: "date-cell",
/** @property */
includeTime: false
});
/**
TimeCell is a Backgrid.DatetimeCell without the date part.
@class Backgrid.TimeCell
@extends Backgrid.DatetimeCell
*/
var TimeCell = Backgrid.TimeCell = DatetimeCell.extend({
/** @property */
className: "time-cell",
/** @property */
includeDate: false
});
/**
BooleanCellEditor renders a checkbox as its editor.
@class Backgrid.BooleanCellEditor
@extends Backgrid.CellEditor
*/
var BooleanCellEditor = Backgrid.BooleanCellEditor = CellEditor.extend({
/** @property */
tagName: "input",
/** @property */
attributes: {
tabIndex: -1,
type: "checkbox"
},
/** @property */
events: {
"mousedown": function () {
this.mouseDown = true;
},
"blur": "enterOrExitEditMode",
"mouseup": function () {
this.mouseDown = false;
},
"change": "saveOrCancel",
"keydown": "saveOrCancel"
},
/**
Renders a checkbox and check it if the model value of this column is true,
uncheck otherwise.
*/
render: function () {
var model = this.model;
var val = this.formatter.fromRaw(model.get(this.column.get("name")), model);
this.$el.prop("checked", val);
return this;
},
/**
Event handler. Hack to deal with the case where `blur` is fired before
`change` and `click` on a checkbox.
*/
enterOrExitEditMode: function (e) {
if (!this.mouseDown) {
var model = this.model;
model.trigger("backgrid:edited", model, this.column, new Command(e));
}
},
/**
Event handler. Save the value into the model if the event is `change` or
one of the keyboard navigation key presses. Exit edit mode without saving
if `escape` was pressed.
*/
saveOrCancel: function (e) {
var model = this.model;
var column = this.column;
var formatter = this.formatter;
var command = new Command(e);
// skip ahead to `change` when space is pressed
if (command.passThru() && e.type != "change") return true;
if (command.cancel()) {
e.stopPropagation();
model.trigger("backgrid:edited", model, column, command);
}
var $el = this.$el;
if (command.save() || command.moveLeft() || command.moveRight() || command.moveUp() ||
command.moveDown()) {
e.preventDefault();
e.stopPropagation();
var val = formatter.toRaw($el.prop("checked"), model);
model.set(column.get("name"), val);
model.trigger("backgrid:edited", model, column, command);
}
else if (e.type == "change") {
var val = formatter.toRaw($el.prop("checked"), model);
model.set(column.get("name"), val);
$el.focus();
}
}
});
/**
BooleanCell renders a checkbox both during display mode and edit mode. The
checkbox is checked if the model value is true, unchecked otherwise.
@class Backgrid.BooleanCell
@extends Backgrid.Cell
*/
var BooleanCell = Backgrid.BooleanCell = Cell.extend({
/** @property */
className: "boolean-cell",
/** @property */
editor: BooleanCellEditor,
/** @property */
events: {
"click": "enterEditMode"
},
/**
Renders a checkbox and check it if the model value of this column is true,
uncheck otherwise.
*/
render: function () {
this.$el.empty();
var model = this.model, column = this.column;
var editable = Backgrid.callByNeed(column.editable(), column, model);
this.$el.append($("<input>", {
tabIndex: -1,
type: "checkbox",
checked: this.formatter.fromRaw(model.get(column.get("name")), model),
disabled: !editable
}));
this.delegateEvents();
return this;
}
});
/**
SelectCellEditor renders an HTML `<select>` fragment as the editor.
@class Backgrid.SelectCellEditor
@extends Backgrid.CellEditor
*/
var SelectCellEditor = Backgrid.SelectCellEditor = CellEditor.extend({
/** @property */
tagName: "select",
/** @property */
events: {
"change": "save",
"blur": "close",
"keydown": "close"
},
/** @property {function(Object, ?Object=): string} template */
template: _.template(
'<option value="<%- value %>" <%= selected ? \'selected="selected"\' : "" %>><%- text %></option>',
null,
{
variable : null,
evaluate : /<%([\s\S]+?)%>/g,
interpolate : /<%=([\s\S]+?)%>/g,
escape : /<%-([\s\S]+?)%>/g
}),
setOptionValues: function (optionValues) {
this.optionValues = optionValues;
this.optionValues = _.result(this, "optionValues");
},
setMultiple: function (multiple) {
this.multiple = multiple;
this.$el.prop("multiple", multiple);
},
_renderOptions: function (nvps, selectedValues) {
var options = '';
for (var i = 0; i < nvps.length; i++) {
options = options + this.template({
text: nvps[i][0],
value: nvps[i][1],
selected: _.indexOf(selectedValues, nvps[i][1]) > -1
});
}
return options;
},
/**
Renders the options if `optionValues` is a list of name-value pairs. The
options are contained inside option groups if `optionValues` is a list of
object hashes. The name is rendered at the option text and the value is the
option value. If `optionValues` is a function, it is called without a
parameter.
*/
render: function () {
this.$el.empty();
var optionValues = _.result(this, "optionValues");
var model = this.model;
var selectedValues = this.formatter.fromRaw(model.get(this.column.get("name")), model);
if (!_.isArray(optionValues)) throw new TypeError("optionValues must be an array");
var optionValue = null;
var optionText = null;
var optionValue = null;
var optgroupName = null;
var optgroup = null;
for (var i = 0; i < optionValues.length; i++) {
var optionValue = optionValues[i];
if (_.isArray(optionValue)) {
optionText = optionValue[0];
optionValue = optionValue[1];
this.$el.append(this.template({
text: optionText,
value: optionValue,
selected: _.indexOf(selectedValues, optionValue) > -1
}));
}
else if (_.isObject(optionValue)) {
optgroupName = optionValue.name;
optgroup = $("<optgroup></optgroup>", { label: optgroupName });
optgroup.append(this._renderOptions.call(this, optionValue.values, selectedValues));
this.$el.append(optgroup);
}
else {
throw new TypeError("optionValues elements must be a name-value pair or an object hash of { name: 'optgroup label', value: [option name-value pairs] }");
}
}
this.delegateEvents();
return this;
},
/**
Saves the value of the selected option to the model attribute.
*/
save: function (e) {
var model = this.model;
var column = this.column;
model.set(column.get("name"), this.formatter.toRaw(this.$el.val(), model));
},
/**
Triggers a `backgrid:edited` event from the model so the body can close
this editor.
*/
close: function (e) {
var model = this.model;
var column = this.column;
var command = new Command(e);
if (command.cancel()) {
e.stopPropagation();
model.trigger("backgrid:edited", model, column, new Command(e));
}
else if (command.save() || command.moveLeft() || command.moveRight() ||
command.moveUp() || command.moveDown() || e.type == "blur") {
e.preventDefault();
e.stopPropagation();
this.save(e);
model.trigger("backgrid:edited", model, column, new Command(e));
}
}
});
/**
SelectCell is also a different kind of cell in that upon going into edit mode
the cell renders a list of options to pick from, as opposed to an input box.
SelectCell cannot be referenced by its string name when used in a column
definition because it requires an `optionValues` class attribute to be
defined. `optionValues` can either be a list of name-value pairs, to be
rendered as options, or a list of object hashes which consist of a key *name*
which is the option group name, and a key *values* which is a list of
name-value pairs to be rendered as options under that option group.
In addition, `optionValues` can also be a parameter-less function that
returns one of the above. If the options are static, it is recommended the
returned values to be memoized. `_.memoize()` is a good function to help with
that.
During display mode, the default formatter will normalize the raw model value
to an array of values whether the raw model value is a scalar or an
array. Each value is compared with the `optionValues` values using
Ecmascript's implicit type conversion rules. When exiting edit mode, no type
conversion is performed when saving into the model. This behavior is not
always desirable when the value type is anything other than string. To
control type conversion on the client-side, you should subclass SelectCell to
provide a custom formatter or provide the formatter to your column
definition.
See:
[$.fn.val()](http://api.jquery.com/val/)
@class Backgrid.SelectCell
@extends Backgrid.Cell
*/
var SelectCell = Backgrid.SelectCell = Cell.extend({
/** @property */
className: "select-cell",
/** @property */
editor: SelectCellEditor,
/** @property */
multiple: false,
/** @property */
formatter: SelectFormatter,
/**
@property {Array.<Array>|Array.<{name: string, values: Array.<Array>}>} optionValues
*/
optionValues: undefined,
/** @property */
delimiter: ', ',
/**
Initializer.
@param {Object} options
@param {Backbone.Model} options.model
@param {Backgrid.Column} options.column
@throws {TypeError} If `optionsValues` is undefined.
*/
initialize: function (options) {
SelectCell.__super__.initialize.apply(this, arguments);
this.listenTo(this.model, "backgrid:edit", function (model, column, cell, editor) {
if (column.get("name") == this.column.get("name")) {
editor.setOptionValues(this.optionValues);
editor.setMultiple(this.multiple);
}
});
},
/**
Renders the label using the raw value as key to look up from `optionValues`.
@throws {TypeError} If `optionValues` is malformed.
*/
render: function () {
this.$el.empty();
var optionValues = _.result(this, "optionValues");
var model = this.model;
var rawData = this.formatter.fromRaw(model.get(this.column.get("name")), model);
var selectedText = [];
try {
if (!_.isArray(optionValues) || _.isEmpty(optionValues)) throw new TypeError;
for (var k = 0; k < rawData.length; k++) {
var rawDatum = rawData[k];
for (var i = 0; i < optionValues.length; i++) {
var optionValue = optionValues[i];
if (_.isArray(optionValue)) {
var optionText = optionValue[0];
var optionValue = optionValue[1];
if (optionValue == rawDatum) selectedText.push(optionText);
}
else if (_.isObject(optionValue)) {
var optionGroupValues = optionValue.values;
for (var j = 0; j < optionGroupValues.length; j++) {
var optionGroupValue = optionGroupValues[j];
if (optionGroupValue[1] == rawDatum) {
selectedText.push(optionGroupValue[0]);
}
}
}
else {
throw new TypeError;
}
}
}
this.$el.append(selectedText.join(this.delimiter));
}
catch (ex) {
if (ex instanceof TypeError) {
throw new TypeError("'optionValues' must be of type {Array.<Array>|Array.<{name: string, values: Array.<Array>}>}");
}
throw ex;
}
this.delegateEvents();
return this;
}
});
/*
backgrid
http://github.com/cloudflare/backgrid
Copyright (c) 2013-present Cloudflare, Inc. and contributors
Licensed under the MIT license.
*/
/**
A Column is a placeholder for column metadata.
You usually don't need to create an instance of this class yourself as a
collection of column instances will be created for you from a list of column
attributes in the Backgrid.js view class constructors.
@class Backgrid.Column
@extends Backbone.Model
*/
var Column = Backgrid.Column = Backbone.Model.extend({
/**
@cfg {Object} defaults Column defaults. To override any of these default
values, you can either change the prototype directly to override
Column.defaults globally or extend Column and supply the custom class to
Backgrid.Grid:
// Override Column defaults globally
Column.prototype.defaults.sortable = false;
// Override Column defaults locally
var MyColumn = Column.extend({
defaults: _.defaults({
editable: false
}, Column.prototype.defaults)
});
var grid = new Backgrid.Grid(columns: new Columns([{...}, {...}], {
model: MyColumn
}));
@cfg {string} [defaults.name] The default name of the model attribute.
@cfg {string} [defaults.label] The default label to show in the header.
@cfg {string|Backgrid.Cell} [defaults.cell] The default cell type. If this
is a string, the capitalized form will be used to look up a cell class in
Backbone, i.e.: string => StringCell. If a Cell subclass is supplied, it is
initialized with a hash of parameters. If a Cell instance is supplied, it
is used directly.
@cfg {string|Backgrid.HeaderCell} [defaults.headerCell] The default header
cell type.
@cfg {boolean|string|function(): boolean} [defaults.sortable=true] Whether
this column is sortable. If the value is a string, a method will the same
name will be looked up from the column instance to determine whether the
column should be sortable. The method's signature must be `function
(Backbone.Model): boolean`. The function's context is the column instance.
@cfg {boolean|string|function(): boolean} [defaults.editable=true] Whether
this column is editable. If the value is a string, a method will the same
name will be looked up from the column instance to determine whether the
column should be editable. The method's signature must be `function
(Backbone.Model): boolean`. The function's context is the column instance.
@cfg {boolean|string|function(): boolean} [defaults.renderable=true]
Whether this column is renderable. If the value is a string, a method will
the same name will be looked up from the column instance to determine
whether the column should be renderable. The method's signature must be
`function (Backbone.Model): boolean`. The function's context is the column
instance.
@cfg {Backgrid.CellFormatter | Object | string} [defaults.formatter] The
formatter to use to convert between raw model values and user input.
@cfg {"toggle"|"cycle"} [defaults.sortType="cycle"] Whether sorting will
toggle between ascending and descending order, or cycle between insertion
order, ascending and descending order.
@cfg {(function(Backbone.Model, string): *) | string} [defaults.sortValue]
The function to use to extract a value from the model for comparison during
sorting. If this value is a string, a method with the same name will be
looked up from the column instance.
@cfg {"ascending"|"descending"|null} [defaults.direction=null] The initial
sorting direction for this column. The default is ordered by
Backbone.Model.cid, which usually means the collection is ordered by
insertion order.
*/
defaults: {
name: undefined,
label: undefined,
sortable: true,
editable: true,
renderable: true,
formatter: undefined,
sortType: "cycle",
sortValue: undefined,
direction: null,
cell: undefined,
headerCell: undefined
},
/**
Initializes this Column instance.
@param {Object} attrs
@param {string} attrs.name The model attribute this column is responsible
for.
@param {string|Backgrid.Cell} attrs.cell The cell type to use to render
this column.
@param {string} [attrs.label]
@param {string|Backgrid.HeaderCell} [attrs.headerCell]
@param {boolean|string|function(): boolean} [attrs.sortable=true]
@param {boolean|string|function(): boolean} [attrs.editable=true]
@param {boolean|string|function(): boolean} [attrs.renderable=true]
@param {Backgrid.CellFormatter | Object | string} [attrs.formatter]
@param {"toggle"|"cycle"} [attrs.sortType="cycle"]
@param {(function(Backbone.Model, string): *) | string} [attrs.sortValue]
@throws {TypeError} If attrs.cell or attrs.options are not supplied.
@throws {ReferenceError} If formatter is a string but a formatter class of
said name cannot be found in the Backgrid module.
See:
- Backgrid.Column.defaults
- Backgrid.Cell
- Backgrid.CellFormatter
*/
initialize: function () {
if (!this.has("label")) {
this.set({ label: this.get("name") }, { silent: true });
}
var headerCell = Backgrid.resolveNameToClass(this.get("headerCell"), "HeaderCell");
var cell = Backgrid.resolveNameToClass(this.get("cell"), "Cell");
this.set({cell: cell, headerCell: headerCell}, { silent: true });
},
/**
Returns an appropriate value extraction function from a model for sorting.
If the column model contains an attribute `sortValue`, if it is a string, a
method from the column instance identifified by the `sortValue` string is
returned. If it is a function, it it returned as is. If `sortValue` isn't
found from the column model's attributes, a default value extraction
function is returned which will compare according to the natural order of
the value's type.
@return {function(Backbone.Model, string): *}
*/
sortValue: function () {
var sortValue = this.get("sortValue");
if (_.isString(sortValue)) return this[sortValue];
else if (_.isFunction(sortValue)) return sortValue;
return function (model, colName) {
return model.get(colName);
};
}
/**
If you cannot always determine whether a column should be sortable before
the grid get initialized, you can override this method.
@member Backgrid.Column
@protected
@method sortable
@return {function(Backbone.Model): boolean | boolean}
*/
/**
If you cannot always determine whether a column should be editable before
the grid get initialized, you can override this method.
@member Backgrid.Column
@protected
@method editable
@return {function(Backbone.Model): boolean | boolean}
*/
/**
If you cannot always determine whether a column should be renderable before
the grid get initialized, you can override this method.
@member Backgrid.Column
@protected
@method renderable
@return {function(Backbone.Model): boolean | boolean}
*/
});
_.each(["sortable", "renderable", "editable"], function (key) {
Column.prototype[key] = function () {
var value = this.get(key);
if (_.isString(value)) return this[value];
else if (_.isFunction(value)) return value;
return !!value;
};
});
/**
A Backbone collection of Column instances.
@class Backgrid.Columns
@extends Backbone.Collection
*/
var Columns = Backgrid.Columns = Backbone.Collection.extend({
/**
@property {Backgrid.Column} model
*/
model: Column
});
/*
backgrid
http://github.com/cloudflare/backgrid
Copyright (c) 2013-present Cloudflare, Inc. and contributors
Licensed under the MIT license.
*/
/**
Row is a simple container view that takes a model instance and a list of
column metadata describing how each of the model's attribute is to be
rendered, and apply the appropriate cell to each attribute.
@class Backgrid.Row
@extends Backbone.View
*/
var Row = Backgrid.Row = Backbone.View.extend({
/** @property */
tagName: "tr",
/**
Initializes a row view instance.
@param {Object} options
@param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns Column metadata.
@param {Backbone.Model} options.model The model instance to render.
@throws {TypeError} If options.columns or options.model is undefined.
*/
initialize: function (options) {
var columns = this.columns = options.columns;
if (!(columns instanceof Backbone.Collection)) {
columns = this.columns = new Columns(columns);
}
var cells = this.cells = [];
for (var i = 0; i < columns.length; i++) {
cells.push(this.makeCell(columns.at(i), options));
}
this.listenTo(columns, "add", function (column, columns) {
var i = columns.indexOf(column);
var cell = this.makeCell(column, options);
cells.splice(i, 0, cell);
var $el = this.$el;
if (i === 0) {
$el.prepend(cell.render().$el);
}
else if (i === columns.length - 1) {
$el.append(cell.render().$el);
}
else {
$el.children().eq(i).before(cell.render().$el);
}
});
this.listenTo(columns, "remove", function (column, columns, opts) {
cells[opts.index].remove();
cells.splice(opts.index, 1);
});
},
/**
Factory method for making a cell. Used by #initialize internally. Override
this to provide an appropriate cell instance for a custom Row subclass.
@protected
@param {Backgrid.Column} column
@param {Object} options The options passed to #initialize.
@return {Backgrid.Cell}
*/
makeCell: function (column) {
return new (column.get("cell"))({
column: column,
model: this.model
});
},
/**
Renders a row of cells for this row's model.
*/
render: function () {
this.$el.empty();
var fragment = document.createDocumentFragment();
for (var i = 0; i < this.cells.length; i++) {
fragment.appendChild(this.cells[i].render().el);
}
this.el.appendChild(fragment);
this.delegateEvents();
return this;
},
/**
Clean up this row and its cells.
@chainable
*/
remove: function () {
for (var i = 0; i < this.cells.length; i++) {
var cell = this.cells[i];
cell.remove.apply(cell, arguments);
}
return Backbone.View.prototype.remove.apply(this, arguments);
}
});
/**
EmptyRow is a simple container view that takes a list of column and render a
row with a single column.
@class Backgrid.EmptyRow
@extends Backbone.View
*/
var EmptyRow = Backgrid.EmptyRow = Backbone.View.extend({
/** @property */
tagName: "tr",
/** @property {string|function(): string} */
emptyText: null,
/**
Initializer.
@param {Object} options
@param {string|function(): string} options.emptyText
@param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns Column metadata.
*/
initialize: function (options) {
this.emptyText = options.emptyText;
this.columns = options.columns;
},
/**
Renders an empty row.
*/
render: function () {
this.$el.empty();
var td = document.createElement("td");
td.setAttribute("colspan", this.columns.length);
var span = document.createElement("span");
span.innerHTML = _.result(this, "emptyText");
td.appendChild(span);
this.el.className = "empty";
this.el.appendChild(td);
return this;
}
});
/*
backgrid
http://github.com/cloudflare/backgrid
Copyright (c) 2013-present Cloudflare, Inc. and contributors
Licensed under the MIT license.
*/
/**
HeaderCell is a special cell class that renders a column header cell. If the
column is sortable, a sorter is also rendered and will trigger a table
refresh after sorting.
@class Backgrid.HeaderCell
@extends Backbone.View
*/
var HeaderCell = Backgrid.HeaderCell = Backbone.View.extend({
/** @property */
tagName: "th",
/** @property */
events: {
"click button": "onClick"
},
/**
Initializer.
@param {Object} options
@param {Backgrid.Column|Object} options.column
@throws {TypeError} If options.column or options.collection is undefined.
*/
initialize: function (options) {
this.column = options.column;
if (!(this.column instanceof Column)) {
this.column = new Column(this.column);
}
var column = this.column, collection = this.collection, $el = this.$el;
this.listenTo(column, "change:editable change:sortable change:renderable",
function (column) {
var changed = column.changedAttributes();
for (var key in changed) {
if (changed.hasOwnProperty(key)) {
$el.toggleClass(key, changed[key]);
}
}
});
this.listenTo(column, "change:direction", this.setCellDirection);
this.listenTo(column, "change:name change:label", this.render);
if (Backgrid.callByNeed(column.editable(), column, collection)) $el.addClass("editable");
if (Backgrid.callByNeed(column.sortable(), column, collection)) $el.addClass("sortable");
if (Backgrid.callByNeed(column.renderable(), column, collection)) $el.addClass("renderable");
this.listenTo(collection.fullCollection || collection, "backgrid:sorted", this.removeCellDirection);
},
/**
Event handler for the collection's `backgrid:sorted` event. Removes
all the CSS direction classes.
*/
removeCellDirection: function () {
this.$el.removeClass("ascending").removeClass("descending");
this.column.set("direction", null);
},
/**
Event handler for the column's `change:direction` event. If this
HeaderCell's column is being sorted on, it applies the direction given as a
CSS class to the header cell. Removes all the CSS direction classes
otherwise.
*/
setCellDirection: function (column, direction) {
this.$el.removeClass("ascending").removeClass("descending");
if (column.cid == this.column.cid) this.$el.addClass(direction);
},
/**
Event handler for the `click` event on the cell's anchor. If the column is
sortable, clicking on the anchor will cycle through 3 sorting orderings -
`ascending`, `descending`, and default.
*/
onClick: function (e) {
e.preventDefault();
var column = this.column;
var collection = this.collection;
var event = "backgrid:sort";
function cycleSort(header, col) {
if (column.get("direction") === "ascending") collection.trigger(event, col, "descending");
else if (column.get("direction") === "descending") collection.trigger(event, col, null);
else collection.trigger(event, col, "ascending");
}
function toggleSort(header, col) {
if (column.get("direction") === "ascending") collection.trigger(event, col, "descending");
else collection.trigger(event, col, "ascending");
}
var sortable = Backgrid.callByNeed(column.sortable(), column, this.collection);
if (sortable) {
var sortType = column.get("sortType");
if (sortType === "toggle") toggleSort(this, column);
else cycleSort(this, column);
}
},
/**
Renders a header cell with a sorter, a label, and a class name for this
column.
*/
render: function () {
this.$el.empty();
var column = this.column;
var sortable = Backgrid.callByNeed(column.sortable(), column, this.collection);
var label;
if(sortable){
label = $("<button>").text(column.get("label")).append("<span class='sort-caret' aria-hidden='true'></span>");
} else {
label = document.createTextNode(column.get("label"));
}
this.$el.append(label);
this.$el.addClass(column.get("name"));
this.$el.addClass(column.get("direction"));
this.delegateEvents();
return this;
}
});
/**
HeaderRow is a controller for a row of header cells.
@class Backgrid.HeaderRow
@extends Backgrid.Row
*/
var HeaderRow = Backgrid.HeaderRow = Backgrid.Row.extend({
/**
Initializer.
@param {Object} options
@param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns
@param {Backgrid.HeaderCell} [options.headerCell] Customized default
HeaderCell for all the columns. Supply a HeaderCell class or instance to a
the `headerCell` key in a column definition for column-specific header
rendering.
@throws {TypeError} If options.columns or options.collection is undefined.
*/
initialize: function () {
Backgrid.Row.prototype.initialize.apply(this, arguments);
},
makeCell: function (column, options) {
var headerCell = column.get("headerCell") || options.headerCell || HeaderCell;
headerCell = new headerCell({
column: column,
collection: this.collection
});
return headerCell;
}
});
/**
Header is a special structural view class that renders a table head with a
single row of header cells.
@class Backgrid.Header
@extends Backbone.View
*/
var Header = Backgrid.Header = Backbone.View.extend({
/** @property */
tagName: "thead",
/**
Initializer. Initializes this table head view to contain a single header
row view.
@param {Object} options
@param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns Column metadata.
@param {Backbone.Model} options.model The model instance to render.
@throws {TypeError} If options.columns or options.model is undefined.
*/
initialize: function (options) {
this.columns = options.columns;
if (!(this.columns instanceof Backbone.Collection)) {
this.columns = new Columns(this.columns);
}
this.row = new Backgrid.HeaderRow({
columns: this.columns,
collection: this.collection
});
},
/**
Renders this table head with a single row of header cells.
*/
render: function () {
this.$el.append(this.row.render().$el);
this.delegateEvents();
return this;
},
/**
Clean up this header and its row.
@chainable
*/
remove: function () {
this.row.remove.apply(this.row, arguments);
return Backbone.View.prototype.remove.apply(this, arguments);
}
});
/*
backgrid
http://github.com/cloudflare/backgrid
Copyright (c) 2013-present Cloudflare, Inc. and contributors
Licensed under the MIT license.
*/
/**
Body is the table body which contains the rows inside a table. Body is
responsible for refreshing the rows after sorting, insertion and removal.
@class Backgrid.Body
@extends Backbone.View
*/
var Body = Backgrid.Body = Backbone.View.extend({
/** @property */
tagName: "tbody",
/**
Initializer.
@param {Object} options
@param {Backbone.Collection} options.collection
@param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns
Column metadata.
@param {Backgrid.Row} [options.row=Backgrid.Row] The Row class to use.
@param {string|function(): string} [options.emptyText] The text to display in the empty row.
@throws {TypeError} If options.columns or options.collection is undefined.
See Backgrid.Row.
*/
initialize: function (options) {
this.columns = options.columns;
if (!(this.columns instanceof Backbone.Collection)) {
this.columns = new Columns(this.columns);
}
this.row = options.row || this.row || Row;
this.rows = this.collection.map(function (model) {
var row = new this.row({
columns: this.columns,
model: model
});
return row;
}, this);
this.emptyText = options.emptyText;
this._unshiftEmptyRowMayBe();
var collection = this.collection;
this.listenTo(collection, "add", this.insertRow);
this.listenTo(collection, "remove", this.removeRow);
this.listenTo(collection, "sort", this.refresh);
this.listenTo(collection, "reset", this.refresh);
this.listenTo(collection, "backgrid:sort", this.sort);
this.listenTo(collection, "backgrid:edited", this.moveToNextCell);
this.listenTo(this.columns, "add remove", this.updateEmptyRow);
},
_unshiftEmptyRowMayBe: function () {
if (this.rows.length === 0 && this.emptyText != null) {
this.emptyRow = new EmptyRow({
emptyText: this.emptyText,
columns: this.columns
});
this.rows.unshift(this.emptyRow);
return true
}
},
/**
This method can be called either directly or as a callback to a
[Backbone.Collecton#add](http://backbonejs.org/#Collection-add) event.
When called directly, it accepts a model or an array of models and an
option hash just like
[Backbone.Collection#add](http://backbonejs.org/#Collection-add) and
delegates to it. Once the model is added, a new row is inserted into the
body and automatically rendered.
When called as a callback of an `add` event, splices a new row into the
body and renders it.
@param {Backbone.Model} model The model to render as a row.
@param {Backbone.Collection} collection When called directly, this
parameter is actually the options to
[Backbone.Collection#add](http://backbonejs.org/#Collection-add).
@param {Object} options When called directly, this must be null.
See:
- [Backbone.Collection#add](http://backbonejs.org/#Collection-add)
*/
insertRow: function (model, collection, options) {
if (this.rows[0] instanceof EmptyRow) this.rows.pop().remove();
// insertRow() is called directly
if (!(collection instanceof Backbone.Collection) && !options) {
this.collection.add(model, (options = collection));
return;
}
var row = new this.row({
columns: this.columns,
model: model
});
var index = collection.indexOf(model);
this.rows.splice(index, 0, row);
var $el = this.$el;
var $children = $el.children();
var $rowEl = row.render().$el;
if (index >= $children.length) {
$el.append($rowEl);
}
else {
$children.eq(index).before($rowEl);
}
return this;
},
/**
The method can be called either directly or as a callback to a
[Backbone.Collection#remove](http://backbonejs.org/#Collection-remove)
event.
When called directly, it accepts a model or an array of models and an
option hash just like
[Backbone.Collection#remove](http://backbonejs.org/#Collection-remove) and
delegates to it. Once the model is removed, a corresponding row is removed
from the body.
When called as a callback of a `remove` event, splices into the rows and
removes the row responsible for rendering the model.
@param {Backbone.Model} model The model to remove from the body.
@param {Backbone.Collection} collection When called directly, this
parameter is actually the options to
[Backbone.Collection#remove](http://backbonejs.org/#Collection-remove).
@param {Object} options When called directly, this must be null.
See:
- [Backbone.Collection#remove](http://backbonejs.org/#Collection-remove)
*/
removeRow: function (model, collection, options) {
// removeRow() is called directly
if (!options) {
this.collection.remove(model, (options = collection));
if (this._unshiftEmptyRowMayBe()) {
this.render();
}
return;
}
if (_.isUndefined(options.render) || options.render) {
this.rows[options.index].remove();
}
this.rows.splice(options.index, 1);
if (this._unshiftEmptyRowMayBe()) {
this.render();
}
return this;
},
/**
Rerender the EmptyRow which empties the DOM element, creates the td with the
updated colspan, and appends it back into the DOM
*/
updateEmptyRow: function () {
if (this.emptyRow != null) {
this.emptyRow.render();
}
},
/**
Reinitialize all the rows inside the body and re-render them. Triggers a
Backbone `backgrid:refresh` event from the collection along with the body
instance as its sole parameter when done.
*/
refresh: function () {
for (var i = 0; i < this.rows.length; i++) {
this.rows[i].remove();
}
this.rows = this.collection.map(function (model) {
var row = new this.row({
columns: this.columns,
model: model
});
return row;
}, this);
this._unshiftEmptyRowMayBe();
this.render();
this.collection.trigger("backgrid:refresh", this);
return this;
},
/**
Renders all the rows inside this body. If the collection is empty and
`options.emptyText` is defined and not null in the constructor, an empty
row is rendered, otherwise no row is rendered.
*/
render: function () {
this.$el.empty();
var fragment = document.createDocumentFragment();
for (var i = 0; i < this.rows.length; i++) {
var row = this.rows[i];
fragment.appendChild(row.render().el);
}
this.el.appendChild(fragment);
this.delegateEvents();
return this;
},
/**
Clean up this body and it's rows.
@chainable
*/
remove: function () {
for (var i = 0; i < this.rows.length; i++) {
var row = this.rows[i];
row.remove.apply(row, arguments);
}
return Backbone.View.prototype.remove.apply(this, arguments);
},
/**
If the underlying collection is a Backbone.PageableCollection in
server-mode or infinite-mode, a page of models is fetched after sorting is
done on the server.
If the underlying collection is a Backbone.PageableCollection in
client-mode, or any
[Backbone.Collection](http://backbonejs.org/#Collection) instance, sorting
is done on the client side. If the collection is an instance of a
Backbone.PageableCollection, sorting will be done globally on all the pages
and the current page will then be returned.
Triggers a Backbone `backgrid:sorted` event from the collection when done
with the column, direction and a reference to the collection.
@param {Backgrid.Column|string} column
@param {null|"ascending"|"descending"} direction
See [Backbone.Collection#comparator](http://backbonejs.org/#Collection-comparator)
*/
sort: function (column, direction) {
if (!_.contains(["ascending", "descending", null], direction)) {
throw new RangeError('direction must be one of "ascending", "descending" or `null`');
}
if (_.isString(column)) column = this.columns.findWhere({name: column});
var collection = this.collection;
var order;
if (direction === "ascending") order = -1;
else if (direction === "descending") order = 1;
else order = null;
var comparator = this.makeComparator(column.get("name"), order,
order ?
column.sortValue() :
function (model) {
return model.cid.replace('c', '') * 1;
});
if (Backbone.PageableCollection &&
collection instanceof Backbone.PageableCollection) {
collection.setSorting(order && column.get("name"), order,
{sortValue: column.sortValue()});
if (collection.fullCollection) {
// If order is null, pageable will remove the comparator on both sides,
// in this case the default insertion order comparator needs to be
// attached to get back to the order before sorting.
if (collection.fullCollection.comparator == null) {
collection.fullCollection.comparator = comparator;
}
collection.fullCollection.sort();
collection.trigger("backgrid:sorted", column, direction, collection);
column.set("direction", direction);
}
else collection.fetch({reset: true, success: function () {
collection.trigger("backgrid:sorted", column, direction, collection);
column.set("direction", direction);
}});
}
else {
collection.comparator = comparator;
collection.sort();
collection.trigger("backgrid:sorted", column, direction, collection);
column.set("direction", direction);
}
return this;
},
makeComparator: function (attr, order, func) {
return function (left, right) {
// extract the values from the models
var l = func(left, attr), r = func(right, attr), t;
// if descending order, swap left and right
if (order === 1) t = l, l = r, r = t;
// compare as usual
if (l === r) return 0;
else if (l < r) return -1;
return 1;
};
},
/**
Moves focus to the next renderable and editable cell and return the
currently editing cell to display mode.
Triggers a `backgrid:next` event on the model with the indices of the row
and column the user *intended* to move to, and whether the intended move
was going to go out of bounds. Note that *out of bound* always means an
attempt to go past the end of the last row.
@param {Backbone.Model} model The originating model
@param {Backgrid.Column} column The originating model column
@param {Backgrid.Command} command The Command object constructed from a DOM
event
*/
moveToNextCell: function (model, column, command) {
var i = this.collection.indexOf(model);
var j = this.columns.indexOf(column);
var cell, renderable, editable, m, n;
// return if model being edited in a different grid
if (j === -1) return this;
this.rows[i].cells[j].exitEditMode();
if (command.moveUp() || command.moveDown() || command.moveLeft() ||
command.moveRight() || command.save()) {
var l = this.columns.length;
var maxOffset = l * this.collection.length;
if (command.moveUp() || command.moveDown()) {
m = i + (command.moveUp() ? -1 : 1);
var row = this.rows[m];
if (row) {
cell = row.cells[j];
if (Backgrid.callByNeed(cell.column.editable(), cell.column, model)) {
cell.enterEditMode();
model.trigger("backgrid:next", m, j, false);
}
}
else model.trigger("backgrid:next", m, j, true);
}
else if (command.moveLeft() || command.moveRight()) {
var right = command.moveRight();
for (var offset = i * l + j + (right ? 1 : -1);
offset >= 0 && offset < maxOffset;
right ? offset++ : offset--) {
m = ~~(offset / l);
n = offset - m * l;
cell = this.rows[m].cells[n];
renderable = Backgrid.callByNeed(cell.column.renderable(), cell.column, cell.model);
editable = Backgrid.callByNeed(cell.column.editable(), cell.column, model);
if (renderable && editable) {
cell.enterEditMode();
model.trigger("backgrid:next", m, n, false);
break;
}
}
if (offset == maxOffset) {
model.trigger("backgrid:next", ~~(offset / l), offset - m * l, true);
}
}
}
return this;
}
});
/*
backgrid
http://github.com/cloudflare/backgrid
Copyright (c) 2013-present Cloudflare, Inc. and contributors
Licensed under the MIT license.
*/
/**
A Footer is a generic class that only defines a default tag `tfoot` and
number of required parameters in the initializer.
@abstract
@class Backgrid.Footer
@extends Backbone.View
*/
var Footer = Backgrid.Footer = Backbone.View.extend({
/** @property */
tagName: "tfoot",
/**
Initializer.
@param {Object} options
@param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns
Column metadata.
@param {Backbone.Collection} options.collection
@throws {TypeError} If options.columns or options.collection is undefined.
*/
initialize: function (options) {
this.columns = options.columns;
if (!(this.columns instanceof Backbone.Collection)) {
this.columns = new Backgrid.Columns(this.columns);
}
}
});
/*
backgrid
http://github.com/cloudflare/backgrid
Copyright (c) 2013-present Cloudflare, Inc. and contributors
Licensed under the MIT license.
*/
/**
Grid represents a data grid that has a header, body and an optional footer.
By default, a Grid treats each model in a collection as a row, and each
attribute in a model as a column. To render a grid you must provide a list of
column metadata and a collection to the Grid constructor. Just like any
Backbone.View class, the grid is rendered as a DOM node fragment when you
call render().
var grid = Backgrid.Grid({
columns: [{ name: "id", label: "ID", type: "string" },
// ...
],
collections: books
});
$("#table-container").append(grid.render().el);
Optionally, if you want to customize the rendering of the grid's header and
footer, you may choose to extend Backgrid.Header and Backgrid.Footer, and
then supply that class or an instance of that class to the Grid constructor.
See the documentation for Header and Footer for further details.
var grid = Backgrid.Grid({
columns: [{ name: "id", label: "ID", type: "string" }],
collections: books,
header: Backgrid.Header.extend({
//...
}),
footer: Backgrid.Paginator
});
Finally, if you want to override how the rows are rendered in the table body,
you can supply a Body subclass as the `body` attribute that uses a different
Row class.
@class Backgrid.Grid
@extends Backbone.View
See:
- Backgrid.Column
- Backgrid.Header
- Backgrid.Body
- Backgrid.Row
- Backgrid.Footer
*/
var Grid = Backgrid.Grid = Backbone.View.extend({
/** @property */
tagName: "table",
/** @property */
className: "backgrid",
/** @property */
header: Header,
/** @property */
body: Body,
/** @property */
footer: null,
/**
Initializes a Grid instance.
@param {Object} options
@param {Backbone.Collection.<Backgrid.Columns>|Array.<Backgrid.Column>|Array.<Object>} options.columns Column metadata.
@param {Backbone.Collection} options.collection The collection of tabular model data to display.
@param {string} [options.caption=string] An optional caption to be added to the table.
@param {Backgrid.Header} [options.header=Backgrid.Header] An optional Header class to override the default.
@param {Backgrid.Body} [options.body=Backgrid.Body] An optional Body class to override the default.
@param {Backgrid.Row} [options.row=Backgrid.Row] An optional Row class to override the default.
@param {Backgrid.Footer} [options.footer=Backgrid.Footer] An optional Footer class.
*/
initialize: function (options) {
// Convert the list of column objects here first so the subviews don't have
// to.
if (!(options.columns instanceof Backbone.Collection)) {
options.columns = new Columns(options.columns || this.columns);
}
this.columns = options.columns;
this.caption = options.caption;
var filteredOptions = _.omit(options, ["el", "id", "attributes",
"className", "tagName", "events"]);
// must construct body first so it listens to backgrid:sort first
this.body = options.body || this.body;
this.body = new this.body(filteredOptions);
this.header = options.header || this.header;
if (this.header) {
this.header = new this.header(filteredOptions);
}
this.footer = options.footer || this.footer;
if (this.footer) {
this.footer = new this.footer(filteredOptions);
}
this.listenTo(this.columns, "reset", function () {
if (this.header) {
this.header = new (this.header.remove().constructor)(filteredOptions);
}
this.body = new (this.body.remove().constructor)(filteredOptions);
if (this.footer) {
this.footer = new (this.footer.remove().constructor)(filteredOptions);
}
this.render();
});
},
/**
Delegates to Backgrid.Body#insertRow.
*/
insertRow: function () {
this.body.insertRow.apply(this.body, arguments);
return this;
},
/**
Delegates to Backgrid.Body#removeRow.
*/
removeRow: function () {
this.body.removeRow.apply(this.body, arguments);
return this;
},
/**
Delegates to Backgrid.Columns#add for adding a column. Subviews can listen
to the `add` event from their internal `columns` if rerendering needs to
happen.
@param {Object} [options] Options for `Backgrid.Columns#add`.
*/
insertColumn: function () {
this.columns.add.apply(this.columns, arguments);
return this;
},
/**
Delegates to Backgrid.Columns#remove for removing a column. Subviews can
listen to the `remove` event from the internal `columns` if rerendering
needs to happen.
@param {Object} [options] Options for `Backgrid.Columns#remove`.
*/
removeColumn: function () {
this.columns.remove.apply(this.columns, arguments);
return this;
},
/**
Delegates to Backgrid.Body#sort.
*/
sort: function () {
this.body.sort.apply(this.body, arguments);
return this;
},
/**
Renders the grid's caption, then header, then footer, then finally the body. Triggers a
Backbone `backgrid:rendered` event along with a reference to the grid when
the it has successfully been rendered.
*/
render: function () {
this.$el.empty();
if (this.caption) {
this.$el.append($("<caption>").text(this.caption));
}
if (this.header) {
this.$el.append(this.header.render().$el);
}
if (this.footer) {
this.$el.append(this.footer.render().$el);
}
this.$el.append(this.body.render().$el);
this.delegateEvents();
this.trigger("backgrid:rendered", this);
return this;
},
/**
Clean up this grid and its subviews.
@chainable
*/
remove: function () {
this.header && this.header.remove.apply(this.header, arguments);
this.body.remove.apply(this.body, arguments);
this.footer && this.footer.remove.apply(this.footer, arguments);
return Backbone.View.prototype.remove.apply(this, arguments);
}
});
return Backgrid;
}));
\ No newline at end of file
!function(a,b){"function"==typeof define&&define.amd?define(["underscore","backbone"],function(c,d){return a.Backgrid=b(c,d)}):"object"==typeof exports?module.exports=b(require("underscore"),require("backbone")):a.Backgrid=b(a._,a.Backbone)}(this,function(a,b){"use strict";function c(a,b,c){var d=b-(a+"").length;d=d<0?0:d;for(var e="",f=0;f<d;f++)e+=c;return e+a}var d="\t\n\v\f\r   ᠎              \u2028\u2029\ufeff";if(!String.prototype.trim||d.trim()){d="["+d+"]";var e=new RegExp("^"+d+d+"*"),f=new RegExp(d+d+"*$");String.prototype.trim=function(){if(void 0===this||null===this)throw new TypeError("can't convert "+this+" to object");return String(this).replace(e,"").replace(f,"")}}var g=b.$,h={Extension:{},resolveNameToClass:function(b,c){if(a.isString(b)){var d=a.map(b.split("-"),function(a){return a.slice(0,1).toUpperCase()+a.slice(1)}).join("")+c,e=h[d]||h.Extension[d];if(a.isUndefined(e))throw new ReferenceError("Class '"+d+"' not found");return e}return b},callByNeed:function(){var b=arguments[0];if(!a.isFunction(b))return b;var c=arguments[1],d=[].slice.call(arguments,2);return b.apply(c,d+""?d:[])}};a.extend(h,b.Events);var i=h.Command=function(b){a.extend(this,{altKey:!!b.altKey,char:b.char,charCode:b.charCode,ctrlKey:!!b.ctrlKey,key:b.key,keyCode:b.keyCode,locale:b.locale,location:b.location,metaKey:!!b.metaKey,repeat:!!b.repeat,shiftKey:!!b.shiftKey,which:b.which})};a.extend(i.prototype,{moveUp:function(){return 38==this.keyCode},moveDown:function(){return 40===this.keyCode},moveLeft:function(){return this.shiftKey&&9===this.keyCode},moveRight:function(){return!this.shiftKey&&9===this.keyCode},save:function(){return 13===this.keyCode},cancel:function(){return 27===this.keyCode},passThru:function(){return!(this.moveUp()||this.moveDown()||this.moveLeft()||this.moveRight()||this.save()||this.cancel())}});var j=h.CellFormatter=function(){};a.extend(j.prototype,{fromRaw:function(a,b){return a},toRaw:function(a,b){return a}});var k=h.NumberFormatter=function(b){if(a.extend(this,this.defaults,b||{}),this.decimals<0||this.decimals>20)throw new RangeError("decimals must be between 0 and 20")};k.prototype=new j,a.extend(k.prototype,{defaults:{decimals:2,decimalSeparator:".",orderSeparator:","},HUMANIZED_NUM_RE:/(\d)(?=(?:\d{3})+$)/g,fromRaw:function(b,c){if(a.isNull(b)||a.isUndefined(b))return"";b=parseFloat(b).toFixed(~~this.decimals);var d=b.split("."),e=d[0],f=d[1]?(this.decimalSeparator||".")+d[1]:"";return e.replace(this.HUMANIZED_NUM_RE,"$1"+this.orderSeparator)+f},toRaw:function(b,c){if(b=b.trim(),""===b)return null;for(var d="",e=b.split(this.orderSeparator),f=0;f<e.length;f++)d+=e[f];var g=d.split(this.decimalSeparator);d="";for(var f=0;f<g.length;f++)d=d+g[f]+".";"."===d[d.length-1]&&(d=d.slice(0,d.length-1));var h=1*(1*d).toFixed(~~this.decimals);return a.isNumber(h)&&!a.isNaN(h)?h:void 0}});var l=h.PercentFormatter=function(){h.NumberFormatter.apply(this,arguments)};l.prototype=new h.NumberFormatter,a.extend(l.prototype,{defaults:a.extend({},k.prototype.defaults,{multiplier:1,symbol:"%"}),fromRaw:function(a,b){var c=[].slice.call(arguments,1);return c.unshift(a*this.multiplier),(k.prototype.fromRaw.apply(this,c)||"0")+this.symbol},toRaw:function(b,c){var d=b.split(this.symbol);if(d&&d[0]&&""===d[1]||null==d[1]){var e=k.prototype.toRaw.call(this,d[0]);return a.isUndefined(e)?e:e/this.multiplier}}});var m=h.DatetimeFormatter=function(b){if(a.extend(this,this.defaults,b||{}),!this.includeDate&&!this.includeTime)throw new Error("Either includeDate or includeTime must be true")};m.prototype=new j,a.extend(m.prototype,{defaults:{includeDate:!0,includeTime:!0,includeMilli:!1},DATE_RE:/^([+\-]?\d{4})-(\d{2})-(\d{2})$/,TIME_RE:/^(\d{2}):(\d{2}):(\d{2})(\.(\d{3}))?$/,ISO_SPLITTER_RE:/T|Z| +/,_convert:function(b,d){if(""===(b+"").trim())return null;var e,f=null;if(a.isNumber(b)){var g=new Date(b);e=c(g.getUTCFullYear(),4,0)+"-"+c(g.getUTCMonth()+1,2,0)+"-"+c(g.getUTCDate(),2,0),f=c(g.getUTCHours(),2,0)+":"+c(g.getUTCMinutes(),2,0)+":"+c(g.getUTCSeconds(),2,0)}else{b=b.trim();var h=b.split(this.ISO_SPLITTER_RE)||[];e=this.DATE_RE.test(h[0])?h[0]:"",f=e&&h[1]?h[1]:this.TIME_RE.test(h[0])?h[0]:""}var i=this.DATE_RE.exec(e)||[],j=this.TIME_RE.exec(f)||[];if(d){if(this.includeDate&&a.isUndefined(i[0]))return;if(this.includeTime&&a.isUndefined(j[0]))return;if(!this.includeDate&&e)return;if(!this.includeTime&&f)return}var g=new Date(Date.UTC(1*i[1]||0,1*i[2]-1||0,1*i[3]||0,1*j[1]||null,1*j[2]||null,1*j[3]||null,1*j[5]||null)),k="";return this.includeDate&&(k=c(g.getUTCFullYear(),4,0)+"-"+c(g.getUTCMonth()+1,2,0)+"-"+c(g.getUTCDate(),2,0)),this.includeTime&&(k=k+(this.includeDate?"T":"")+c(g.getUTCHours(),2,0)+":"+c(g.getUTCMinutes(),2,0)+":"+c(g.getUTCSeconds(),2,0),this.includeMilli&&(k=k+"."+c(g.getUTCMilliseconds(),3,0))),this.includeDate&&this.includeTime&&(k+="Z"),k},fromRaw:function(b,c){return a.isNull(b)||a.isUndefined(b)?"":this._convert(b)},toRaw:function(a,b){return this._convert(a,!0)}});var n=h.StringFormatter=function(){};n.prototype=new j,a.extend(n.prototype,{fromRaw:function(b,c){return a.isUndefined(b)||a.isNull(b)?"":b+""}});var o=h.EmailFormatter=function(){};o.prototype=new j,a.extend(o.prototype,{toRaw:function(b,c){var d=b.trim().split("@");if(2===d.length&&a.all(d))return b}});var p=h.SelectFormatter=function(){};p.prototype=new j,a.extend(p.prototype,{fromRaw:function(b,c){return a.isArray(b)?b:null!=b?[b]:[]}});var q=h.CellEditor=b.View.extend({initialize:function(a){this.formatter=a.formatter,this.column=a.column,this.column instanceof B||(this.column=new B(this.column)),this.listenTo(this.model,"backgrid:editing",this.postRender)},postRender:function(a,b){return null!=b&&b.get("name")!=this.column.get("name")||this.$el.focus(),this}}),r=h.InputCellEditor=q.extend({tagName:"input",attributes:{type:"text"},events:{blur:"saveOrCancel",keydown:"saveOrCancel"},initialize:function(a){r.__super__.initialize.apply(this,arguments),a.placeholder&&this.$el.attr("placeholder",a.placeholder)},render:function(){var a=this.model;return this.$el.val(this.formatter.fromRaw(a.get(this.column.get("name")),a)),this},saveOrCancel:function(b){var c=this.formatter,d=this.model,e=this.column,f=new i(b),g="blur"===b.type;if(f.moveUp()||f.moveDown()||f.moveLeft()||f.moveRight()||f.save()||g){b.preventDefault(),b.stopPropagation();var h=this.$el.val(),j=c.toRaw(h,d);a.isUndefined(j)?d.trigger("backgrid:error",d,e,h):(d.set(e.get("name"),j),d.trigger("backgrid:edited",d,e,f))}else f.cancel()&&(b.stopPropagation(),d.trigger("backgrid:edited",d,e,f))},postRender:function(a,b){if(null==b||b.get("name")==this.column.get("name"))if("right"===this.$el.css("text-align")){var c=this.$el.val();this.$el.focus().val(null).val(c)}else this.$el.focus();return this}}),s=h.Cell=b.View.extend({tagName:"td",formatter:j,editor:r,events:{click:"enterEditMode"},initialize:function(b){this.column=b.column,this.column instanceof B||(this.column=new B(this.column));var c=this.column,d=this.model,e=this.$el,f=h.resolveNameToClass(c.get("formatter")||this.formatter,"Formatter");a.isFunction(f.fromRaw)||a.isFunction(f.toRaw)||(f=new f),this.formatter=f,this.editor=h.resolveNameToClass(this.editor,"CellEditor"),this.listenTo(d,"change:"+c.get("name"),function(){e.hasClass("editor")||this.render()}),this.listenTo(d,"backgrid:error",this.renderError),this.listenTo(c,"change:editable change:sortable change:renderable",function(a){var b=a.changedAttributes();for(var c in b)b.hasOwnProperty(c)&&e.toggleClass(c,b[c])}),this.updateStateClassesMaybe()},updateStateClassesMaybe:function(){var a=this.model,b=this.column,c=this.$el;c.toggleClass("editable",h.callByNeed(b.editable(),b,a)),c.toggleClass("sortable",h.callByNeed(b.sortable(),b,a)),c.toggleClass("renderable",h.callByNeed(b.renderable(),b,a))},render:function(){var a=this.$el;a.empty();var b=this.model,c=this.column.get("name");return a.text(this.formatter.fromRaw(b.get(c),b)),a.addClass(c),this.updateStateClassesMaybe(),this.delegateEvents(),this},enterEditMode:function(){var a=this.model,b=this.column,c=h.callByNeed(b.editable(),b,a);c&&(this.currentEditor=new this.editor({column:this.column,model:this.model,formatter:this.formatter}),a.trigger("backgrid:edit",a,b,this,this.currentEditor),this.undelegateEvents(),this.$el.empty(),this.$el.append(this.currentEditor.$el),this.currentEditor.render(),this.$el.addClass("editor"),a.trigger("backgrid:editing",a,b,this,this.currentEditor))},renderError:function(a,b){null!=b&&b.get("name")!=this.column.get("name")||this.$el.addClass("error")},exitEditMode:function(){this.$el.removeClass("error"),this.currentEditor.remove(),this.stopListening(this.currentEditor),delete this.currentEditor,this.$el.removeClass("editor"),this.render()},remove:function(){return this.currentEditor&&(this.currentEditor.remove.apply(this.currentEditor,arguments),delete this.currentEditor),s.__super__.remove.apply(this,arguments)}}),t=h.StringCell=s.extend({className:"string-cell",formatter:n}),u=h.UriCell=s.extend({className:"uri-cell",title:null,target:"_blank",initialize:function(a){u.__super__.initialize.apply(this,arguments),this.title=a.title||this.title,this.target=a.target||this.target},render:function(){this.$el.empty();var a=this.model.get(this.column.get("name")),b=this.formatter.fromRaw(a,this.model);return this.$el.append(g("<a>",{tabIndex:-1,href:a,title:this.title||b,target:this.target}).text(b)),this.delegateEvents(),this}}),v=(h.EmailCell=t.extend({className:"email-cell",formatter:o,render:function(){this.$el.empty();var a=this.model,b=this.formatter.fromRaw(a.get(this.column.get("name")),a);return this.$el.append(g("<a>",{tabIndex:-1,href:"mailto:"+b,title:b}).text(b)),this.delegateEvents(),this}}),h.NumberCell=s.extend({className:"number-cell",decimals:k.prototype.defaults.decimals,decimalSeparator:k.prototype.defaults.decimalSeparator,orderSeparator:k.prototype.defaults.orderSeparator,formatter:k,initialize:function(a){v.__super__.initialize.apply(this,arguments);var b=this.formatter;b.decimals=this.decimals,b.decimalSeparator=this.decimalSeparator,b.orderSeparator=this.orderSeparator}})),w=(h.IntegerCell=v.extend({className:"integer-cell",decimals:0}),h.PercentCell=v.extend({className:"percent-cell",multiplier:l.prototype.defaults.multiplier,symbol:l.prototype.defaults.symbol,formatter:l,initialize:function(){w.__super__.initialize.apply(this,arguments);var a=this.formatter;a.multiplier=this.multiplier,a.symbol=this.symbol}})),x=h.DatetimeCell=s.extend({className:"datetime-cell",includeDate:m.prototype.defaults.includeDate,includeTime:m.prototype.defaults.includeTime,includeMilli:m.prototype.defaults.includeMilli,formatter:m,initialize:function(b){x.__super__.initialize.apply(this,arguments);var c=this.formatter;c.includeDate=this.includeDate,c.includeTime=this.includeTime,c.includeMilli=this.includeMilli;var d=this.includeDate?"YYYY-MM-DD":"";d+=this.includeDate&&this.includeTime?"T":"",d+=this.includeTime?"HH:mm:ss":"",d+=this.includeTime&&this.includeMilli?".SSS":"",this.editor=this.editor.extend({attributes:a.extend({},this.editor.prototype.attributes,this.editor.attributes,{placeholder:d})})}}),y=(h.DateCell=x.extend({className:"date-cell",includeTime:!1}),h.TimeCell=x.extend({className:"time-cell",includeDate:!1}),h.BooleanCellEditor=q.extend({tagName:"input",attributes:{tabIndex:-1,type:"checkbox"},events:{mousedown:function(){this.mouseDown=!0},blur:"enterOrExitEditMode",mouseup:function(){this.mouseDown=!1},change:"saveOrCancel",keydown:"saveOrCancel"},render:function(){var a=this.model,b=this.formatter.fromRaw(a.get(this.column.get("name")),a);return this.$el.prop("checked",b),this},enterOrExitEditMode:function(a){if(!this.mouseDown){var b=this.model;b.trigger("backgrid:edited",b,this.column,new i(a))}},saveOrCancel:function(a){var b=this.model,c=this.column,d=this.formatter,e=new i(a);if(e.passThru()&&"change"!=a.type)return!0;e.cancel()&&(a.stopPropagation(),b.trigger("backgrid:edited",b,c,e));var f=this.$el;if(e.save()||e.moveLeft()||e.moveRight()||e.moveUp()||e.moveDown()){a.preventDefault(),a.stopPropagation();var g=d.toRaw(f.prop("checked"),b);b.set(c.get("name"),g),b.trigger("backgrid:edited",b,c,e)}else if("change"==a.type){var g=d.toRaw(f.prop("checked"),b);b.set(c.get("name"),g),f.focus()}}})),z=(h.BooleanCell=s.extend({className:"boolean-cell",editor:y,events:{click:"enterEditMode"},render:function(){this.$el.empty();var a=this.model,b=this.column,c=h.callByNeed(b.editable(),b,a);return this.$el.append(g("<input>",{tabIndex:-1,type:"checkbox",checked:this.formatter.fromRaw(a.get(b.get("name")),a),disabled:!c})),this.delegateEvents(),this}}),h.SelectCellEditor=q.extend({tagName:"select",events:{change:"save",blur:"close",keydown:"close"},template:a.template('<option value="<%- value %>" <%= selected ? \'selected="selected"\' : "" %>><%- text %></option>',null,{variable:null,evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g}),setOptionValues:function(b){this.optionValues=b,this.optionValues=a.result(this,"optionValues")},setMultiple:function(a){this.multiple=a,this.$el.prop("multiple",a)},_renderOptions:function(b,c){for(var d="",e=0;e<b.length;e++)d+=this.template({text:b[e][0],value:b[e][1],selected:a.indexOf(c,b[e][1])>-1});return d},render:function(){this.$el.empty();var b=a.result(this,"optionValues"),c=this.model,d=this.formatter.fromRaw(c.get(this.column.get("name")),c);if(!a.isArray(b))throw new TypeError("optionValues must be an array");for(var e=null,f=null,e=null,h=null,i=null,j=0;j<b.length;j++){var e=b[j];if(a.isArray(e))f=e[0],e=e[1],this.$el.append(this.template({text:f,value:e,selected:a.indexOf(d,e)>-1}));else{if(!a.isObject(e))throw new TypeError("optionValues elements must be a name-value pair or an object hash of { name: 'optgroup label', value: [option name-value pairs] }");h=e.name,i=g("<optgroup></optgroup>",{label:h}),i.append(this._renderOptions.call(this,e.values,d)),this.$el.append(i)}}return this.delegateEvents(),this},save:function(a){var b=this.model,c=this.column;b.set(c.get("name"),this.formatter.toRaw(this.$el.val(),b))},close:function(a){var b=this.model,c=this.column,d=new i(a);d.cancel()?(a.stopPropagation(),b.trigger("backgrid:edited",b,c,new i(a))):(d.save()||d.moveLeft()||d.moveRight()||d.moveUp()||d.moveDown()||"blur"==a.type)&&(a.preventDefault(),a.stopPropagation(),this.save(a),b.trigger("backgrid:edited",b,c,new i(a)))}})),A=h.SelectCell=s.extend({className:"select-cell",editor:z,multiple:!1,formatter:p,optionValues:void 0,delimiter:", ",initialize:function(a){A.__super__.initialize.apply(this,arguments),this.listenTo(this.model,"backgrid:edit",function(a,b,c,d){b.get("name")==this.column.get("name")&&(d.setOptionValues(this.optionValues),d.setMultiple(this.multiple))})},render:function(){this.$el.empty();var b=a.result(this,"optionValues"),c=this.model,d=this.formatter.fromRaw(c.get(this.column.get("name")),c),e=[];try{if(!a.isArray(b)||a.isEmpty(b))throw new TypeError;for(var f=0;f<d.length;f++)for(var g=d[f],h=0;h<b.length;h++){var i=b[h];if(a.isArray(i)){var j=i[0],i=i[1];i==g&&e.push(j)}else{if(!a.isObject(i))throw new TypeError;for(var k=i.values,l=0;l<k.length;l++){var m=k[l];m[1]==g&&e.push(m[0])}}}this.$el.append(e.join(this.delimiter))}catch(a){if(a instanceof TypeError)throw new TypeError("'optionValues' must be of type {Array.<Array>|Array.<{name: string, values: Array.<Array>}>}");throw a}return this.delegateEvents(),this}}),B=h.Column=b.Model.extend({defaults:{name:void 0,label:void 0,sortable:!0,editable:!0,renderable:!0,formatter:void 0,sortType:"cycle",sortValue:void 0,direction:null,cell:void 0,headerCell:void 0},initialize:function(){this.has("label")||this.set({label:this.get("name")},{silent:!0});var a=h.resolveNameToClass(this.get("headerCell"),"HeaderCell"),b=h.resolveNameToClass(this.get("cell"),"Cell");this.set({cell:b,headerCell:a},{silent:!0})},sortValue:function(){var b=this.get("sortValue");return a.isString(b)?this[b]:a.isFunction(b)?b:function(a,b){return a.get(b)}}});a.each(["sortable","renderable","editable"],function(b){B.prototype[b]=function(){var c=this.get(b);return a.isString(c)?this[c]:a.isFunction(c)?c:!!c}});var C=h.Columns=b.Collection.extend({model:B}),D=h.Row=b.View.extend({tagName:"tr",initialize:function(a){var c=this.columns=a.columns;c instanceof b.Collection||(c=this.columns=new C(c));for(var d=this.cells=[],e=0;e<c.length;e++)d.push(this.makeCell(c.at(e),a));this.listenTo(c,"add",function(b,c){var e=c.indexOf(b),f=this.makeCell(b,a);d.splice(e,0,f);var g=this.$el;0===e?g.prepend(f.render().$el):e===c.length-1?g.append(f.render().$el):g.children().eq(e).before(f.render().$el)}),this.listenTo(c,"remove",function(a,b,c){d[c.index].remove(),d.splice(c.index,1)})},makeCell:function(a){return new(a.get("cell"))({column:a,model:this.model})},render:function(){this.$el.empty();for(var a=document.createDocumentFragment(),b=0;b<this.cells.length;b++)a.appendChild(this.cells[b].render().el);return this.el.appendChild(a),this.delegateEvents(),this},remove:function(){for(var a=0;a<this.cells.length;a++){var c=this.cells[a];c.remove.apply(c,arguments)}return b.View.prototype.remove.apply(this,arguments)}}),E=h.EmptyRow=b.View.extend({tagName:"tr",emptyText:null,initialize:function(a){this.emptyText=a.emptyText,this.columns=a.columns},render:function(){this.$el.empty();var b=document.createElement("td");b.setAttribute("colspan",this.columns.length);var c=document.createElement("span");return c.innerHTML=a.result(this,"emptyText"),b.appendChild(c),this.el.className="empty",this.el.appendChild(b),this}}),F=h.HeaderCell=b.View.extend({tagName:"th",events:{"click button":"onClick"},initialize:function(a){this.column=a.column,this.column instanceof B||(this.column=new B(this.column));var b=this.column,c=this.collection,d=this.$el;this.listenTo(b,"change:editable change:sortable change:renderable",function(a){var b=a.changedAttributes();for(var c in b)b.hasOwnProperty(c)&&d.toggleClass(c,b[c])}),this.listenTo(b,"change:direction",this.setCellDirection),this.listenTo(b,"change:name change:label",this.render),h.callByNeed(b.editable(),b,c)&&d.addClass("editable"),h.callByNeed(b.sortable(),b,c)&&d.addClass("sortable"),h.callByNeed(b.renderable(),b,c)&&d.addClass("renderable"),this.listenTo(c.fullCollection||c,"backgrid:sorted",this.removeCellDirection)},removeCellDirection:function(){this.$el.removeClass("ascending").removeClass("descending"),this.column.set("direction",null)},setCellDirection:function(a,b){this.$el.removeClass("ascending").removeClass("descending"),a.cid==this.column.cid&&this.$el.addClass(b)},onClick:function(a){function b(a,b){"ascending"===d.get("direction")?e.trigger(f,b,"descending"):"descending"===d.get("direction")?e.trigger(f,b,null):e.trigger(f,b,"ascending")}function c(a,b){"ascending"===d.get("direction")?e.trigger(f,b,"descending"):e.trigger(f,b,"ascending")}a.preventDefault();var d=this.column,e=this.collection,f="backgrid:sort",g=h.callByNeed(d.sortable(),d,this.collection);if(g){var i=d.get("sortType");"toggle"===i?c(this,d):b(this,d)}},render:function(){this.$el.empty();var a,b=this.column,c=h.callByNeed(b.sortable(),b,this.collection);return a=c?g("<button>").text(b.get("label")).append("<span class='sort-caret' aria-hidden='true'></span>"):document.createTextNode(b.get("label")),this.$el.append(a),this.$el.addClass(b.get("name")),this.$el.addClass(b.get("direction")),this.delegateEvents(),this}}),G=(h.HeaderRow=h.Row.extend({initialize:function(){h.Row.prototype.initialize.apply(this,arguments)},makeCell:function(a,b){var c=a.get("headerCell")||b.headerCell||F;return c=new c({column:a,collection:this.collection})}}),h.Header=b.View.extend({tagName:"thead",initialize:function(a){this.columns=a.columns,this.columns instanceof b.Collection||(this.columns=new C(this.columns)),this.row=new h.HeaderRow({columns:this.columns,collection:this.collection})},render:function(){return this.$el.append(this.row.render().$el),this.delegateEvents(),this},remove:function(){return this.row.remove.apply(this.row,arguments),b.View.prototype.remove.apply(this,arguments)}})),H=h.Body=b.View.extend({tagName:"tbody",initialize:function(a){this.columns=a.columns,this.columns instanceof b.Collection||(this.columns=new C(this.columns)),this.row=a.row||this.row||D,this.rows=this.collection.map(function(a){var b=new this.row({columns:this.columns,model:a});return b},this),this.emptyText=a.emptyText,this._unshiftEmptyRowMayBe();var c=this.collection;this.listenTo(c,"add",this.insertRow),this.listenTo(c,"remove",this.removeRow),this.listenTo(c,"sort",this.refresh),this.listenTo(c,"reset",this.refresh),this.listenTo(c,"backgrid:sort",this.sort),this.listenTo(c,"backgrid:edited",this.moveToNextCell),this.listenTo(this.columns,"add remove",this.updateEmptyRow)},_unshiftEmptyRowMayBe:function(){if(0===this.rows.length&&null!=this.emptyText)return this.emptyRow=new E({emptyText:this.emptyText,columns:this.columns}),this.rows.unshift(this.emptyRow),!0},insertRow:function(a,c,d){if(this.rows[0]instanceof E&&this.rows.pop().remove(),!(c instanceof b.Collection||d))return void this.collection.add(a,d=c);var e=new this.row({columns:this.columns,model:a}),f=c.indexOf(a);this.rows.splice(f,0,e);var g=this.$el,h=g.children(),i=e.render().$el;return f>=h.length?g.append(i):h.eq(f).before(i),this},removeRow:function(b,c,d){return d?((a.isUndefined(d.render)||d.render)&&this.rows[d.index].remove(),this.rows.splice(d.index,1),this._unshiftEmptyRowMayBe()&&this.render(),this):(this.collection.remove(b,d=c),void(this._unshiftEmptyRowMayBe()&&this.render()))},updateEmptyRow:function(){null!=this.emptyRow&&this.emptyRow.render()},refresh:function(){for(var a=0;a<this.rows.length;a++)this.rows[a].remove();return this.rows=this.collection.map(function(a){var b=new this.row({columns:this.columns,model:a});return b},this),this._unshiftEmptyRowMayBe(),this.render(),this.collection.trigger("backgrid:refresh",this),this},render:function(){this.$el.empty();for(var a=document.createDocumentFragment(),b=0;b<this.rows.length;b++){var c=this.rows[b];a.appendChild(c.render().el)}return this.el.appendChild(a),this.delegateEvents(),this},remove:function(){for(var a=0;a<this.rows.length;a++){var c=this.rows[a];c.remove.apply(c,arguments)}return b.View.prototype.remove.apply(this,arguments)},sort:function(c,d){if(!a.contains(["ascending","descending",null],d))throw new RangeError('direction must be one of "ascending", "descending" or `null`');a.isString(c)&&(c=this.columns.findWhere({name:c}));var e,f=this.collection;e="ascending"===d?-1:"descending"===d?1:null;var g=this.makeComparator(c.get("name"),e,e?c.sortValue():function(a){return 1*a.cid.replace("c","")});return b.PageableCollection&&f instanceof b.PageableCollection?(f.setSorting(e&&c.get("name"),e,{sortValue:c.sortValue()}),f.fullCollection?(null==f.fullCollection.comparator&&(f.fullCollection.comparator=g),f.fullCollection.sort(),f.trigger("backgrid:sorted",c,d,f),c.set("direction",d)):f.fetch({reset:!0,success:function(){f.trigger("backgrid:sorted",c,d,f),c.set("direction",d)}})):(f.comparator=g,f.sort(),f.trigger("backgrid:sorted",c,d,f),c.set("direction",d)),this},makeComparator:function(a,b,c){return function(d,e){var f,g=c(d,a),h=c(e,a);return 1===b&&(f=g,g=h,h=f),g===h?0:g<h?-1:1}},moveToNextCell:function(a,b,c){var d,e,f,g,i,j=this.collection.indexOf(a),k=this.columns.indexOf(b);if(k===-1)return this;if(this.rows[j].cells[k].exitEditMode(),c.moveUp()||c.moveDown()||c.moveLeft()||c.moveRight()||c.save()){var l=this.columns.length,m=l*this.collection.length;if(c.moveUp()||c.moveDown()){g=j+(c.moveUp()?-1:1);var n=this.rows[g];n?(d=n.cells[k],h.callByNeed(d.column.editable(),d.column,a)&&(d.enterEditMode(),a.trigger("backgrid:next",g,k,!1))):a.trigger("backgrid:next",g,k,!0)}else if(c.moveLeft()||c.moveRight()){for(var o=c.moveRight(),p=j*l+k+(o?1:-1);p>=0&&p<m;o?p++:p--)if(g=~~(p/l),i=p-g*l,d=this.rows[g].cells[i],e=h.callByNeed(d.column.renderable(),d.column,d.model),f=h.callByNeed(d.column.editable(),d.column,a),e&&f){d.enterEditMode(),a.trigger("backgrid:next",g,i,!1);break}p==m&&a.trigger("backgrid:next",~~(p/l),p-g*l,!0)}}return this}});h.Footer=b.View.extend({tagName:"tfoot",initialize:function(a){this.columns=a.columns,this.columns instanceof b.Collection||(this.columns=new h.Columns(this.columns))}}),h.Grid=b.View.extend({tagName:"table",className:"backgrid",header:G,body:H,footer:null,initialize:function(c){c.columns instanceof b.Collection||(c.columns=new C(c.columns||this.columns)),this.columns=c.columns,this.caption=c.caption;var d=a.omit(c,["el","id","attributes","className","tagName","events"]);this.body=c.body||this.body,this.body=new this.body(d),this.header=c.header||this.header,this.header&&(this.header=new this.header(d)),this.footer=c.footer||this.footer,this.footer&&(this.footer=new this.footer(d)),this.listenTo(this.columns,"reset",function(){this.header&&(this.header=new(this.header.remove().constructor)(d)),this.body=new(this.body.remove().constructor)(d),this.footer&&(this.footer=new(this.footer.remove().constructor)(d)),this.render()})},insertRow:function(){return this.body.insertRow.apply(this.body,arguments),this},removeRow:function(){return this.body.removeRow.apply(this.body,arguments),this},insertColumn:function(){return this.columns.add.apply(this.columns,arguments),this},removeColumn:function(){return this.columns.remove.apply(this.columns,arguments),this},sort:function(){return this.body.sort.apply(this.body,arguments),this},render:function(){return this.$el.empty(),this.caption&&this.$el.append(g("<caption>").text(this.caption)),this.header&&this.$el.append(this.header.render().$el),this.footer&&this.$el.append(this.footer.render().$el),this.$el.append(this.body.render().$el),this.delegateEvents(),this.trigger("backgrid:rendered",this),this},remove:function(){return this.header&&this.header.remove.apply(this.header,arguments),this.body.remove.apply(this.body,arguments),this.footer&&this.footer.remove.apply(this.footer,arguments),b.View.prototype.remove.apply(this,arguments)}});return h});
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
/**
Tests for course items listing.
**/
describe("OpenAssessment.CourseItemsListingView", function() {
// Stubs
var view = null;
var rootElement = null;
var section = null;
var runtime = {
handlerUrl: function(el, handler) {
return '/' + handler;
}
};
window.XBlock = {
initializeBlock: function(el){}
};
var createCourseItemsListingView = function(template) {
loadFixtures(template);
section = $('.open-response-assessment-block');
rootElement = section.parent();
return new OpenAssessment.CourseItemsListingView(runtime, rootElement);
};
var stubAjax = function(success, responseData) {
spyOn($, 'ajax').and.returnValue(
$.Deferred(function(defer) {
if (success) {
defer.resolveWith(this, [responseData]);
} else {
defer.reject();
}
}).promise()
);
};
var oraCourseItems = {
"block-v1:SomeOrg+ORA101+2017+type@openassessment+block@9d1af6220a4d4ecbafb22a3506effcce": {
"name": "Test ORA 1",
"staff_assessment": false,
"parent": {
"id": "block-v1:SomeOrg+ORA101+2017+type@vertical+block@5570454d5dc4469ca75f36dd792ee316",
"name": "Vertical 1"
},
"responses": {
"training": 0,
"self": 0,
"peer": 1,
"waiting": 0,
"ai": 0,
"done": 0,
"cancelled": 0,
"total": 1,
"staff": 0
}
},
"block-v1:SomeOrg+ORA101+2017+type@openassessment+block@3ec2343a95734a87af494455f52b1141": {
"name": "Test ORA 2",
"staff_assessment": true,
"parent": {
"id": "block-v1:SomeOrg+ORA101+2017+type@vertical+block@90b4edff50bc47d9ba037a3180c44e97",
"name": "Vertical 2"
},
"responses": {
"training": 3,
"self": 0,
"peer": 0,
"waiting": 5,
"ai": 0,
"done": 0,
"cancelled": 0,
"total": 8,
"staff": 0
}
},
"block-v1:SomeOrg+ORA101+2017+type@openassessment+block@40b4edfe60bc47d9ba037a3180c44e97": {
"name": "Test ORA 3",
"staff_assessment": false,
"parent": {
"id": "block-v1:SomeOrg+ORA101+2017+type@openassessment+block@40b4edfe60bc47d9ba037a3180c44e97",
"name": "Vertical 3"
},
"responses": {
"training": 0,
"self": 0,
"peer": 1,
"waiting": 0,
"ai": 0,
"done": 2,
"cancelled": 0,
"total": 3,
"staff": 0
}
}
};
var testData = [];
var ora2responses = {};
$.each(oraCourseItems, function(locationId, oraItem) {
testData.push({
"parent_name": oraItem['parent']['name'],
"name": oraItem['name'],
"url_grade_available_responses": "/grade_available_responses_view",
"staff_assessment": oraItem['staff_assessment'],
"parent_id": oraItem['parent']['id'],
"url_base": "/student_view",
"id": locationId
});
ora2responses[locationId] = oraItem['responses'];
});
beforeEach(function() {
// Create a new stub server
view = createCourseItemsListingView('oa_listing_view.html');
// Add test data
view.oraData = testData;
});
it('shows tables on success callback', function() {
expect(section.find('.open-response-assessment-msg').is(':visible')).toBe(true);
expect(section.find('.open-response-assessment-content').is(':visible')).toBe(false);
spyOn(view, 'showSummaryGrid').and.callThrough();
spyOn(view, 'showOpenResponsesGrid').and.callThrough();
stubAjax(true, ora2responses);
view.refreshGrids();
expect($.ajax).toHaveBeenCalledWith({
url: '/get_ora2_responses',
type: "GET",
dataType: "json"
});
expect(view.showSummaryGrid).toHaveBeenCalled();
expect(view.showOpenResponsesGrid).toHaveBeenCalled();
expect(section.find('.open-response-assessment-msg').is(':visible')).toBe(false);
expect(section.find('.open-response-assessment-content').is(':visible')).toBe(true);
var expectedArr = [3, 3, 12, 3, 2, 0, 5, 2];
var summaryRowValuesArr = [];
section.find('.open-response-assessment-summary td div.ora-summary-value').each(function(i, val) {
summaryRowValuesArr.push(parseInt($(val).text()));
});
expect(_.isEqual(summaryRowValuesArr, expectedArr)).toBe(true);
var rows = $('.open-response-assessment-main-table tbody tr');
expect(rows.length).toBe(3);
var tds = [];
var td = null;
$.each(rows, function(i, val){
td = [];
$(val).find('td').each(function(j, item){
td.push($(item).html());
});
tds.push(td);
});
var expectedTds = [
["Vertical 1", '<a title="Test ORA 1">Test ORA 1</a>',
'1', '0', '1', '0', '0', '0'],
["Vertical 2", '<a title="Test ORA 2">Test ORA 2</a>',
'8', '3', '0', '0', '<a title="5">5</a>', '0'],
["Vertical 3", '<a title="Test ORA 3">Test ORA 3</a>',
'3', '0', '1', '0', '0', '2']
];
expect(_.isEqual(tds, expectedTds)).toBe(true);
});
it('shows error on failure callback', function() {
expect(section.find('.open-response-assessment-msg').is(':visible')).toBe(true);
expect(section.find('.open-response-assessment-content').is(':visible')).toBe(false);
spyOn(view, 'showSummaryGrid').and.callThrough();
spyOn(view, 'showOpenResponsesGrid').and.callThrough();
stubAjax(false, null);
view.refreshGrids();
expect($.ajax).toHaveBeenCalledWith({
url: '/get_ora2_responses',
type: "GET",
dataType: "json"
});
expect(view.showSummaryGrid).not.toHaveBeenCalled();
expect(view.showOpenResponsesGrid).not.toHaveBeenCalled();
expect(section.find('.open-response-assessment-msg').text())
.toEqual('List of Open Assessments is unavailable');
});
it('shows ora block after click on title field', function() {
spyOn(window.XBlock, 'initializeBlock');
spyOn(view, 'displayOraBlock').and.callThrough();
spyOn(view, 'renderBreadcrumbs').and.callThrough();
spyOn(view, 'backToOpenResponsesGrid').and.callThrough();
view.renderGrids(ora2responses);
var items = $('.open-response-assessment-main-table tbody tr:first td a');
var link = items[0];
stubAjax(true, {html: 'test_html'});
$(link).trigger('click');
expect(view.displayOraBlock).toHaveBeenCalledWith(testData[0].url_base, jasmine.any(Object));
expect($.ajax).toHaveBeenCalledWith({
url: testData[0].url_base,
type: "GET",
dataType: "json"
});
expect(view.renderBreadcrumbs).toHaveBeenCalled();
expect(window.XBlock.initializeBlock).toHaveBeenCalled();
expect(section.find('.open-response-assessment-msg').is(':visible')).toBe(false);
expect(section.find('.open-response-assessment-content').is(':visible')).toBe(false);
expect(section.find('.open-response-assessment-item-block').html()).toBe('test_html');
expect(section.find('.open-response-assessment-item').is(':visible')).toBe(true);
var backLinks = section.find('.open-response-assessment-item-breadcrumbs a');
expect(backLinks.length).toBe(1);
expect($(backLinks[0]).attr('title')).toBe('Back to Full List');
$.ajax = jasmine.createSpy().and.returnValue($.Deferred(function(defer) {}).promise());
$(backLinks[0]).trigger('click');
expect(view.backToOpenResponsesGrid).toHaveBeenCalled();
expect(section.find('.open-response-assessment-msg').is(':visible')).toBe(true);
expect(section.find('.open-response-assessment-content').is(':visible')).toBe(false);
expect(section.find('.open-response-assessment-item').is(':visible')).toBe(false);
});
it('shows error with return back button if xblock view is unavailable', function() {
spyOn(view, 'displayOraBlock').and.callThrough();
spyOn(view, 'renderBreadcrumbs').and.callThrough();
spyOn(view, 'backToOpenResponsesGrid').and.callThrough();
view.renderGrids(ora2responses);
var items = $('.open-response-assessment-main-table tbody tr:first td a');
var link = items[0];
stubAjax(false, null);
$(link).trigger('click');
expect(view.displayOraBlock).toHaveBeenCalledWith(testData[0].url_base, jasmine.any(Object));
expect($.ajax).toHaveBeenCalledWith({
url: testData[0].url_base,
type: "GET",
dataType: "json"
});
expect(section.find('.open-response-assessment-msg').text())
.toEqual('Block view is unavailable');
var backLinks = section.find('.open-response-assessment-item-breadcrumbs a');
expect(backLinks.length).toBe(1);
expect($(backLinks[0]).attr('title')).toBe('Back to Full List');
});
it('display grade available responses view after click on staff field', function() {
spyOn(view, 'displayOraBlock').and.callThrough();
view.renderGrids(ora2responses);
var items = $('.open-response-assessment-main-table tbody tr td a');
var link = items[2];
stubAjax(true, {html: 'test_html'});
$(link).trigger('click');
expect(view.displayOraBlock).toHaveBeenCalledWith(testData[0].url_grade_available_responses,
jasmine.any(Object));
expect($.ajax).toHaveBeenCalledWith({
url: testData[0].url_grade_available_responses,
type: "GET",
dataType: "json"
});
});
});
......@@ -103,6 +103,13 @@ describe('OpenAssessment.StaffAreaView', function() {
return view;
};
var createGradeAvailableResponsesView = function() {
var assessmentElement = $('.openassessment').get(0);
var view = new OpenAssessment.BaseView(runtime, assessmentElement, server, {});
view.staffAreaView.installHandlers();
return view;
};
/**
* Initialize the staff area view, then check whether it makes
* an AJAX call to populate itself.
......@@ -763,4 +770,51 @@ describe('OpenAssessment.StaffAreaView', function() {
expect(staffArea.baseView.unsavedWarningEnabled()).toBe(false);
});
});
describe('Grade Available Responses as the separate view', function() {
var staffAreaTab = "staff-grading";
var gradingType = "full-grade";
beforeEach(function() {
loadFixtures('oa_grade_available_responses_separate_view.html');
});
it('exists without any additional buttons', function() {
var view = createGradeAvailableResponsesView(),
staffArea = $('.openassessment__staff-area', view.element),
staffGradingButton = $('.button-staff-grading', view.element),
problemHeader = $('.problem__header', view.element),
gradeValue = $('.staff__grade__value', view.element);
expect(staffArea.length).toBe(1);
expect(staffGradingButton.length).toBe(0);
expect(problemHeader.text()).toBe('Test ABC');
expect(gradeValue.text().trim()).toBe("9 Available and 2 Checked Out");
});
it('can submit a staff grade', function() {
var view = createGradeAvailableResponsesView(),
$assessment, $staffGradeButton;
$staffGradeButton = $('.staff__grade__show-form', view.element);
expect($staffGradeButton).toHaveAttr('aria-expanded', 'false');
showInstructorAssessmentForm(view);
expect($staffGradeButton).toHaveAttr('aria-expanded', 'true');
$assessment = getAssessment(view, staffAreaTab);
// Verify that the submission is shown
expect($('.staff-assessment__display__title', view.element).text().trim()).toBe(
'Response for: mock_user'
);
// Fill in and submit the assessment
fillAssessment($assessment, gradingType);
server.staffGradeFormTemplate = 'oa_staff_grade_learners_assessment_2.html';
submitAssessment(view.staffAreaView, staffAreaTab);
verifyAssessType(view.staffAreaView, 'full-grade');
// Verify that the assessment form has been removed
expect($('.staff__grade__form', view.element).html().trim()).toBe('');
expect($staffGradeButton).toHaveAttr('aria-expanded', 'false');
verifyFocused($staffGradeButton[0]);
});
});
});
......@@ -253,7 +253,7 @@ describe("OpenAssessment.Server", function() {
type: "POST",
data: JSON.stringify({
feedback_text: "test feedback",
feedback_options: options,
feedback_options: options
}),
contentType : jsonContentType
});
......
......@@ -384,5 +384,22 @@ function OpenAssessmentBlock(runtime, element, data) {
var server = new OpenAssessment.Server(runtime, element);
var view = new OpenAssessment.BaseView(runtime, element, server, data);
view.load();
}
/* XBlock JavaScript entry point for OpenAssessmentXBlock. */
/* jshint unused:false */
function CourseOpenResponsesListingBlock(runtime, element, data) {
var view = new OpenAssessment.CourseItemsListingView(runtime, element);
view.refreshGrids();
}
/* XBlock JavaScript entry point for OpenAssessmentXBlock. */
/* jshint unused:false */
function StaffAssessmentBlock(runtime, element, data) {
/**
Render auxiliary view which displays the staff grading area
**/
var server = new OpenAssessment.Server(runtime, element);
var view = new OpenAssessment.BaseView(runtime, element, server, data);
view.staffAreaView.installHandlers();
}
(function(OpenAssessment) {
'use strict';
OpenAssessment.CourseItemsListingView = function(runtime, element) {
var self = this;
var $section = $(element);
var block = $section.find('.open-response-assessment-block');
var itemViewEnabled = (parseInt(block.data('item-view-enabled')) === 1) && XBlock;
this.$section = $section;
this.runtime = runtime;
this.oraData = $.parseJSON($("#open-response-assessment-items").text());
$section.find(".open-response-assessment-content").hide();
$section.find('.open-response-assessment-item').hide();
$section.find('.open-response-assessment-msg').show();
var AssessmentCell = Backgrid.UriCell.extend({
staff: false,
render: function() {
this.$el.empty();
var url = this.model.get(this.staff ? 'url_grade_available_responses' : 'url_base');
var rawValue = this.model.get(this.column.get("name"));
var staffAssessment = this.model.get('staff_assessment');
var formattedValue = this.formatter.fromRaw(rawValue, this.model);
var link = null;
if (itemViewEnabled && (!this.staff || (this.staff && staffAssessment))) {
link = $("<a>", {
text: formattedValue,
title: this.title || formattedValue
});
this.$el.append(link);
link.on("click", $.proxy(self, "displayOraBlock", url));
} else {
this.$el.append(formattedValue);
}
this.delegateEvents();
return this;
}
});
var StaffCell = AssessmentCell.extend({
staff: true
});
this._columns = [
{
name: 'parent_name', label: gettext("Parent Section"), label_summary: gettext("Parent Sections"),
cell: "string", num: false, editable: false
},
{
name: 'name', label: gettext("Assessment"), label_summary: gettext("Assessments"),
cell: AssessmentCell, num: false, editable: false
},
{
name: 'total', label: gettext("Total Responses"), label_summary: gettext("Total Responses"),
cell: "string", num: true, editable: false
},
{
name: 'training', label: gettext("Training"), label_summary: gettext("Training"),
cell: "string", num: true, editable: false
},
{
name: 'peer', label: gettext("Peer"), label_summary: gettext("Peer"),
cell: "string", num: true, editable: false
},
{
name: 'self', label: gettext("Self"), label_summary: gettext("Self"),
cell: "string", num: true, editable: false
},
{
name: 'waiting', label: gettext("Staff"), label_summary: gettext("Staff"),
cell: StaffCell, num: true, editable: false
},
{
name: 'done',
label: gettext("Final Grade Received"),
label_summary: gettext("Final Grade Received"),
cell: "string",
num: true,
editable: false
}
];
};
OpenAssessment.CourseItemsListingView.prototype.refreshGrids = function(force) {
force = force || false;
var self = this;
var $section = this.$section;
var block = $section.find('.open-response-assessment-block');
var dataUrl = this.runtime.handlerUrl($section, 'get_ora2_responses');
var dataRendered = parseInt(block.data('rendered'));
if (!dataRendered || force) {
return $.Deferred(
function(defer) {
$.ajax({
type: 'GET',
dataType: 'json',
url: dataUrl
}).done(function(data) {
self.renderGrids(data);
defer.resolve();
}).fail(function(data, textStatus) {
$section.find('.open-response-assessment-msg')
.text(gettext('List of Open Assessments is unavailable'));
defer.rejectWith(this, [textStatus]);
});
}
).promise();
}
};
OpenAssessment.CourseItemsListingView.prototype.renderGrids = function(data) {
var self = this;
var $section = this.$section;
var block = $section.find('.open-response-assessment-block');
var oraSteps = ['training', 'peer', 'self', 'waiting', 'done'];
$.each(self.oraData, function(i, oraItem) {
var total = 0;
var itemId = oraItem.id;
$.each(oraSteps, function(j, step) {
self.oraData[i][step] = 0;
});
if (itemId in data) {
_.extend(self.oraData[i], data[itemId]);
}
$.each(oraSteps, function(j, step) {
total += self.oraData[i][step];
});
self.oraData[i].total = total;
});
block.data('rendered', 1);
$section.find('.open-response-assessment-msg').hide();
self.showSummaryGrid(self.oraData);
self.showOpenResponsesGrid(self.oraData);
};
OpenAssessment.CourseItemsListingView.prototype.showSummaryGrid = function(data) {
var $section = this.$section;
var summaryData = [];
var summaryDataMap = {};
$section.find(".open-response-assessment-summary").empty();
$.each(this._columns, function(index, v) {
var realName = v.name === 'waiting' ? 'staff' : v.name;
summaryData.push({
title: v.label_summary,
value: 0,
num: v.num,
class: realName
});
summaryDataMap[realName] = index;
});
$.each(data, function(index, obj) {
var staffGradeRequired = obj.staff_assessment;
$.each(obj, function(key, value) {
var idx = 0;
var realKey = key;
if (key === 'waiting' && staffGradeRequired) {
realKey = 'staff';
}
if (realKey in summaryDataMap) {
idx = summaryDataMap[realKey];
if (summaryData[idx].num) {
summaryData[idx].value += value;
} else {
summaryData[idx].value += 1;
}
}
});
});
var templateData = _.template($('#open-response-assessment-summary-tpl').text());
$section.find(".open-response-assessment-summary").append(templateData({
oraSummary: summaryData
}));
};
OpenAssessment.CourseItemsListingView.prototype.showOpenResponsesGrid = function(data) {
var $section = this.$section;
$section.find('.open-response-assessment-content').show();
var collection = new Backbone.Collection(data);
$section.find(".open-response-assessment-main-table").empty();
var grid = new Backgrid.Grid({
columns: this._columns,
collection: collection
});
$section.find(".open-response-assessment-main-table").append(grid.render().el);
};
OpenAssessment.CourseItemsListingView.prototype.displayOraBlock = function(url) {
var $section = this.$section;
var self = this;
$section.find(".open-response-assessment-content").hide();
$section.find('.open-response-assessment-msg').text(gettext('Please wait')).show();
return $.Deferred(
function(defer) {
$.ajax({
type: 'GET',
dataType: 'json',
url: url
}).done(function(data) {
var el = $section.find('.open-response-assessment-item');
var block = el.find('.open-response-assessment-item-block');
$section.find('.open-response-assessment-msg').hide();
el.show();
self.renderBreadcrumbs();
block.html(data.html);
XBlock.initializeBlock($(block).find('.xblock')[0]);
defer.resolve();
}).fail(function(data, textStatus) {
$section.find('.open-response-assessment-item').show();
$section.find('.open-response-assessment-msg')
.text(gettext('Block view is unavailable'));
self.renderBreadcrumbs();
defer.rejectWith(this, [textStatus]);
});
}
).promise();
};
OpenAssessment.CourseItemsListingView.prototype.renderBreadcrumbs = function() {
var $section = this.$section;
var breadcrumbs = $section.find(".open-response-assessment-item-breadcrumbs");
var text = gettext('Back to Full List');
var fullListItem = $("<a>", {
html: '&larr;&nbsp;' + text,
title: text
});
breadcrumbs.append(fullListItem);
fullListItem.on("click", $.proxy(this, "backToOpenResponsesGrid"));
};
OpenAssessment.CourseItemsListingView.prototype.backToOpenResponsesGrid = function() {
var $section = this.$section;
$section.find(".open-response-assessment-item-breadcrumbs").empty();
$section.find(".open-response-assessment-item-block").empty();
$section.find('.open-response-assessment-item').hide();
$section.find('.open-response-assessment-msg').text(gettext('Please wait')).show();
this.refreshGrids(true);
};
})(OpenAssessment);
......@@ -24,7 +24,7 @@ OpenAssessment.FileUploader = function() {
data: file,
async: false,
processData: false,
contentType: file.type,
contentType: file.type
}).done(
function() {
// Log an analytics event
......
......@@ -81,6 +81,7 @@
@import 'oa/elements/layout'; // applied layouts and deliberate class-based breakpoints
@import 'oa/elements/staff'; // open assessment staff-centric UI
@import 'oa/views/oa-base'; // open assessment base view
@import 'oa/views/oa-course-items-listing'; // open response assessment tab for instructor dashboard
// openassessment: contextual
@import 'oa/contexts/ie'; // open assessment-specific Internet Explorer-specific styling
......
.open-response-assessment-block {
table {
table-layout: fixed;
}
.open-response-assessment-msg {
margin-bottom: 20px;
}
.open-response-assessment-content,
.open-response-assessment-item
{
display: none;
}
.open-response-assessment-summary {
td {
border: none;
}
}
.open-response-assessment-item-breadcrumbs {
padding-bottom: 20px;
a {
cursor: pointer;
}
}
.open-response-assessment-main-table {
th {
background-color: #ffffff;
text-align: left;
button {
background: none;
border: none;
box-shadow: none;
outline: none;
font-size: 14px;
}
a {
color: #000000 !important;
}
}
td {
a {
cursor: pointer;
}
}
tbody tr:nth-child(odd) {
background-color: #f9f9f9;
}
}
.ora-summary-title {
color: #0079bc;
font-weight: bold;
text-transform: uppercase;
font-size: 0.8em;
}
.ora-summary-value {
font-size: 2.2em;
padding-top: 3px;
}
.backgrid {
.peer, .self, .staff, .waiting {
width: 65px;
}
.training {
width: 90px;
}
.total {
width: 150px;
}
.done {
width: 190px;
}
}
}
# -*- coding: utf-8 -*-
"""
Tests for course items listing handlers.
"""
import json
from mock import patch
from .base import scenario, XBlockHandlerTestCase, SubmitAssessmentsMixin
class TestCourseItemsListingHandlers(XBlockHandlerTestCase, SubmitAssessmentsMixin):
"""
Test for course items listing handlers.
"""
@scenario('data/basic_scenario.xml', user_id='Bob')
def test_non_staff_access(self, xblock):
"""
Test non-staff access for endpoint that return items statistics
"""
response = self.request(xblock, 'get_ora2_responses', json.dumps({}),
request_method='GET')
self.assertIn('You do not have permission', response)
@scenario('data/basic_scenario.xml', user_id='Bob')
def test_staff_access(self, xblock):
"""
Test staff access for endpoint that return items statistics
"""
self.set_staff_access(xblock)
xblock.xmodule_runtime.course_id = 'test_course'
return_data = [{'id': 'test_1', 'title': 'title_1'},
{'id': 'test_2', 'title': 'title_2'}]
with patch("openassessment.data.OraAggregateData.collect_ora2_responses", return_value=return_data):
response = self.request(xblock, 'get_ora2_responses', json.dumps({}),
request_method='GET', response_format='json')
self.assertEqual(response, return_data)
......@@ -2,12 +2,15 @@
Tests the Open Assessment XBlock functionality.
"""
import ddt
import json
from collections import namedtuple
import datetime as dt
from freezegun import freeze_time
import pytz
from mock import Mock, patch, MagicMock, PropertyMock
from lxml import etree
from StringIO import StringIO
from openassessment.xblock import openassessmentblock
from openassessment.xblock.resolve_dates import DISTANT_PAST, DISTANT_FUTURE
......@@ -59,6 +62,85 @@ class TestOpenAssessment(XBlockHandlerTestCase):
self.assertIsNotNone(grade_response)
self.assertIn("step--grade", grade_response.body)
def _staff_assessment_view_helper(self, xblock):
"""
Helper for "staff_assessment_view" tests
"""
xblock_fragment = self.runtime.render(xblock, "grade_available_responses_view")
body_html = xblock_fragment.body_html()
self.assertIn("StaffAssessmentBlock", body_html)
self.assertIn("openassessment__title", body_html)
return body_html
@scenario('data/staff_grade_scenario.xml')
def test_staff_assessment_view(self, xblock):
"""OA XBlock returns some HTML for case if Staff Assessment is configured.
View basic test for verifying auxiliary view which displays the staff grading area.
"""
body_html = self._staff_assessment_view_helper(xblock)
self.assertIn("openassessment__staff-area", body_html)
self.assertIn("ui-staff__content", body_html)
self.assertNotIn("openassessment__staff-area-unavailable", body_html)
@scenario('data/basic_scenario.xml')
def test_staff_assessment_view_staff_assessment_not_configured(self, xblock):
"""OA XBlock returns some HTML for case if Staff Assessment is not configured.
View basic test for verifying auxiliary view which displays the staff grading area.
"""
body_html = self._staff_assessment_view_helper(xblock)
self.assertNotIn("ui-staff__content", body_html)
self.assertIn("openassessment__staff-area-unavailable", body_html)
@scenario('data/basic_scenario.xml')
def test_ora_blocks_listing_view(self, xblock):
"""
Test view for listing all courses OA blocks.
"""
xblock_fragment = self.runtime.render(xblock, "ora_blocks_listing_view")
body_html = xblock_fragment.body_html()
self.assertIn("CourseOpenResponsesListingBlock", body_html)
parser = etree.HTMLParser()
tree = etree.parse(StringIO(body_html), parser)
xpath_query_to_get_main_section = "//section[contains(@class, 'open-response-assessment-block')]"
xpath_query_to_get_course_items = "//script[contains(@id, 'open-response-assessment-items')]"
sections = tree.xpath(xpath_query_to_get_main_section)
self.assertEqual(len(sections), 1)
self.assertEquals(sections[0].get('data-item-view-enabled'), '0')
scripts = tree.xpath(xpath_query_to_get_course_items)
self.assertEqual(len(scripts), 1)
self.assertEqual(scripts[0].text, '[]')
defined_ora_items = [{'id': 'test-id1', 'val': 'test-val1'},
{'id': 'test-id2', 'val': 'test-val2'}]
xblock_fragment = self.runtime.render(xblock, "ora_blocks_listing_view", context={
'ora_items': defined_ora_items,
'ora_item_view_enabled': True
})
body_html = xblock_fragment.body_html()
parser = etree.HTMLParser()
tree = etree.parse(StringIO(body_html), parser)
sections = tree.xpath(xpath_query_to_get_main_section)
self.assertEqual(len(sections), 1)
self.assertEquals(sections[0].get('data-item-view-enabled'), '1')
scripts = tree.xpath(xpath_query_to_get_course_items)
self.assertEqual(len(scripts), 1)
items = json.loads(scripts[0].text)
self.assertEqual(items, defined_ora_items)
@scenario('data/empty_prompt.xml')
def test_prompt_intentionally_empty(self, xblock):
# Verify that prompts intentionally left empty don't create DOM elements
......
......@@ -3,6 +3,8 @@
"version": "0.2.0",
"repository": "https://github.com/edx/edx-ora2.git",
"dependencies": {
"backbone": "~1.2.3",
"backgrid ": "~0.3.8",
"edx-ui-toolkit": "1.5.1",
"moment": "^2.15.1",
"moment-timezone": "~0.5.5",
......
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