shim.js 12.7 KB
Newer Older
1 2
;(function (define, undefined) {
'use strict';
3
define([
4
    'jquery', 'underscore', 'annotator_1.2.9', 'js/edxnotes/utils/utils'
5
], function ($, _, Annotator, Utils) {
6 7 8 9 10 11 12 13 14 15 16 17 18 19
    var _t = Annotator._t;

    /**
     * We currently run JQuery 1.7.2 in Jasmine tests and LMS.
     * AnnotatorJS 1.2.9. uses two calls to addBack (in the two functions
     * 'isAnnotator' and 'onHighlightMouseover') which was only defined in
     * JQuery 1.8.0. In LMS, it works without throwing an error because
     * JQuery.UI 1.10.0 adds support to jQuery<1.8 by augmenting '$.fn' with
     * that missing function. It is not the case for all Jasmine unit tests,
     * so we add it here if necessary.
     **/
    if (!$.fn.addBack) {
        $.fn.addBack = function (selector) {
            return this.add(
polesye committed
20
                selector === null ? this.prevObject : this.prevObject.filter(selector)
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
            );
        };
    }

    /**
     * The original _setupDynamicStyle uses a very expensive call to
     * Util.maxZIndex(...) that sets the z-index of .annotator-adder,
     * .annotator-outer, .annotator-notice, .annotator-filter. We set these
     * values in annotator.min.css instead and do nothing here.
     */
    Annotator.prototype._setupDynamicStyle = function() { };

    Annotator.frozenSrc = null;

    /**
     * Modifies Annotator.Plugin.Auth.haveValidToken to make it work with a new
     * token format.
     **/
    Annotator.Plugin.Auth.prototype.haveValidToken = function() {
        return (
polesye committed
41 42 43 44 45
            this._unsafeToken &&
            this._unsafeToken.sub &&
            this._unsafeToken.exp &&
            this._unsafeToken.iat &&
            this.timeToExpiry() > 0
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
        );
    };

    /**
     * Modifies Annotator.Plugin.Auth.timeToExpiry to make it work with a new
     * token format.
     **/
    Annotator.Plugin.Auth.prototype.timeToExpiry = function() {
        var now = new Date().getTime() / 1000,
            expiry = this._unsafeToken.exp,
            timeToExpiry = expiry - now;

        return (timeToExpiry > 0) ? timeToExpiry : 0;
    };

cahrens committed
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88

    Annotator.Plugin.Tags.prototype.updateField = _.compose(
        function() {
            // Add screen reader label for edit mode. Note that the id of the tags element will not always be "1".
            // It depends on the number of annotatable components on the page.
            var tagsField = $("li.annotator-item >input", this.annotator.editor.element).attr('id');
            if ($("label.sr[for='"+ tagsField + "']", this.annotator.editor.element).length === 0) {
                $('<label class="sr" for='+ tagsField +'>' + _t('Tags (space-separated)') + '</label>').insertBefore(
                    $('#'+tagsField, this.annotator.editor.element)
                );
            }
            return this;
        },
        Annotator.Plugin.Tags.prototype.updateField
    );

    Annotator.Plugin.Tags.prototype.updateViewer = _.compose(
        function() {
            // Add ARIA information for viewing mode.
            $('div.annotator-tags', this.wrapper).attr({
                'role': 'region',
                'aria-label': 'tags'
            });
            return this;
        },
        Annotator.Plugin.Tags.prototype.updateViewer
    );

89
    /**
90 91 92 93
     * Modifies Annotator.highlightRange to add "tabindex=0" and role="link"
     * attributes to the <span class="annotator-hl"> markup that encloses the
     * note. These are then focusable via the TAB key and are accessible to
     * screen readers.
94 95 96
     **/
    Annotator.prototype.highlightRange = _.compose(
        function (results) {
97 98 99 100
            $('.annotator-hl', this.wrapper).attr({
                'tabindex': 0,
                'role': 'link'
            });
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
            return results;
        },
        Annotator.prototype.highlightRange
    );

    /**
     * Modifies Annotator.destroy to unbind click.edxnotes:freeze from the
     * document and reset isFrozen to default value, false.
     **/
    Annotator.prototype.destroy = _.compose(
        Annotator.prototype.destroy,
        function () {
            // We are destroying the instance that has the popup visible, revert to default,
            // unfreeze all instances and set their isFrozen to false
            if (this === Annotator.frozenSrc) {
                this.unfreezeAll();
            } else {
                // Unfreeze only this instance and unbound associated 'click.edxnotes:freeze' handler
                $(document).off('click.edxnotes:freeze' + this.uid);
                this.isFrozen = false;
            }

            if (this.logger && this.logger.destroy) {
                this.logger.destroy();
            }
            // Unbind onNoteClick from click
            this.viewer.element.off('click', this.onNoteClick);
polesye committed
128
            this.wrapper.off('click', '.annotator-hl');
129 130 131 132
        }
    );

    /**
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
     * Modifies Annotator.Viewer.html template to make viewer div focusable.
     * Also adds a close button and necessary i18n attributes to all buttons.
    **/
        Annotator.Viewer.prototype.html = {
        element: [
            '<div class="annotator-outer annotator-viewer">',
                '<ul class="annotator-widget annotator-listing" tabindex="-1"></ul>',
            '</div>'
        ].join(''),
        item: [
            '<li class="annotator-annotation annotator-item">',
                '<span class="annotator-controls">',
                    '<a href="#" title="', _t('View as webpage'), '" class="annotator-link">',
                        _t('View as webpage'),
                    '</a>',
                    '<button class="annotator-edit">',
                        _t('Edit'),
                        '<span class="sr">', _t('Note'), '</span>',
                    '</button>',
                    '<button class="annotator-delete">',
                        _t('Delete'),
                        '<span class="sr">', _t('Note'), '</span>',
                    '</button>',
                    '<button class="annotator-close">',
                        _t('Close'),
                        '<span class="sr">', _t('Note'), '</span>',
                    '</button>',
                '</span>',
            '</li>'
        ].join('')
    };
164 165

    /**
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
     * Overrides Annotator._setupViewer to add a "click" event on viewer and to
     * improve line breaks.
     **/
    Annotator.prototype._setupViewer = function () {
        var self = this;
        this.viewer = new Annotator.Viewer({readOnly: this.options.readOnly});
        this.viewer.element.on('click', _.bind(this.onNoteClick, this));
        this.viewer.hide()
            .on("edit", this.onEditAnnotation)
            .on("delete", this.onDeleteAnnotation)
            .addField({
                load: function (field, annotation) {
                    if (annotation.text) {
                        $(field).html(Utils.nl2br(Annotator.Util.escape(annotation.text)));
                    } else {
                        $(field).html('<i>' + _t('No Comment') + '</i>');
                    }
183
                    return self.publish('annotationViewerTextField', [field, annotation]);
184 185 186 187 188 189 190 191 192 193 194 195
                }
            })
            .element.appendTo(this.wrapper).bind({
                "mouseover": this.clearViewerHideTimer,
                "mouseout":  this.startViewerHideTimer
            });
        return this;
    };

    Annotator.Editor.prototype.isShown = Annotator.Viewer.prototype.isShown;

    /**
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
     * Modifies Annotator.Editor.html template to add tabindex = -1 to
     * form.annotator-widget and reverse order of Save and Cancel buttons.
     **/
    Annotator.Editor.prototype.html = [
        '<div class="annotator-outer annotator-editor">',
            '<form class="annotator-widget" tabindex="-1">',
                '<ul class="annotator-listing"></ul>',
                '<div class="annotator-controls">',
                    '<button class="annotator-save">',
                        _t('Save'),
                        '<span class="sr">', _t('Note'), '</span>',
                    '</button>',
                    '<button class="annotator-cancel">',
                        _t('Cancel'),
                        '<span class="sr">', _t('Note'), '</span>',
                    '</button>',
                '</div>',
            '</form>',
        '</div>'
    ].join('');


    /**
     * Modifies Annotator.Editor.show, in the case of a keydown event, to remove
     * focus from Save button and put it on form.annotator-widget instead.
cahrens committed
221 222
     *
     * Also add a sr label for note textarea.
223 224 225
     **/
    Annotator.Editor.prototype.show = _.compose(
        function (event) {
cahrens committed
226 227 228 229 230 231 232 233 234
            // Add screen reader label for the note area. Note that the id of the tags element will not always be "0".
            // It depends on the number of annotatable components on the page.
            var noteField = $("li.annotator-item >textarea", this.element).attr('id');
            if ($("label.sr[for='"+ noteField + "']", this.element).length === 0) {
                $('<label class="sr" for='+ noteField +'>' + _t('Note') + '</label>').insertBefore(
                    $('#'+noteField, this.element)
                );
            }

235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
            if (event.type === 'keydown') {
                this.element.find('.annotator-save').removeClass(this.classes.focus);
                this.element.find('form.annotator-widget').focus();
            }
        },
        Annotator.Editor.prototype.show
    );

    /**
     * Removes the textarea keydown event handler as it triggers 'processKeypress'
     * which hides the viewer on ESC and saves on ENTER. We will define different
     * behaviors for these in /plugins/accessibility.js
     **/
    delete Annotator.Editor.prototype.events["textarea keydown"];

    /**
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
     * Modifies Annotator.onHighlightMouseover to avoid showing the viewer if the
     * editor is opened.
     **/
    Annotator.prototype.onHighlightMouseover = _.wrap(
        Annotator.prototype.onHighlightMouseover,
        function (func, event) {
            // Do nothing if the editor is opened.
            if (this.editor.isShown()) {
                return false;
            }
            return func.call(this, event);
        },
        Annotator.prototype._setupViewer
    );

polesye committed
266 267 268 269 270 271 272 273 274 275 276 277
    /**
     * Modifies Annotator._setupWrapper to add a "click" event on '.annotator-hl'.
     **/
    Annotator.prototype._setupWrapper = _.compose(
        function () {
            this.element.on('click', '.annotator-hl', _.bind(this.onHighlightClick, this));
            return this;
        },
        Annotator.prototype._setupWrapper
    );

    $.extend(true, Annotator.prototype, {
278 279 280 281
        isFrozen: false,
        uid: _.uniqueId(),

        onHighlightClick: function (event) {
polesye committed
282 283 284
            event.stopPropagation();
            if (!this.editor.isShown()) {
                this.unfreezeAll();
285
                this.onHighlightMouseover.call(this, event);
polesye committed
286 287
                Annotator.frozenSrc = this;
                this.freezeAll();
288 289 290 291
            }
        },

        onNoteClick: function (event) {
292
            var target = $(event.target);
293 294
            event.stopPropagation();
            Annotator.Util.preventEventDefault(event);
295 296

            if (!(target.is('.annotator-delete') || target.is('.annotator-close'))) {
297 298
                Annotator.frozenSrc = this;
                this.freezeAll();
299 300
            } else if (target.is('.annotator-close')) {
                this.viewer.hide();
301 302 303 304 305 306 307 308 309 310 311 312
            }
        },

        freeze: function () {
            if (!this.isFrozen) {
                // Remove default events
                this.removeEvents();
                this.viewer.element.unbind('mouseover mouseout');
                this.uid = _.uniqueId();
                $(document).on('click.edxnotes:freeze' + this.uid, _.bind(this.unfreeze, this));
                this.isFrozen = true;
            }
polesye committed
313
            return this;
314 315 316 317 318 319 320 321 322 323 324
        },

        unfreeze: function () {
            if (this.isFrozen) {
                // Add default events
                this.addEvents();
                this.viewer.element.bind({
                    'mouseover': this.clearViewerHideTimer,
                    'mouseout':  this.startViewerHideTimer
                });
                this.viewer.hide();
polesye committed
325
                $(document).off('click.edxnotes:freeze' + this.uid);
326 327 328
                this.isFrozen = false;
                Annotator.frozenSrc = null;
            }
polesye committed
329
            return this;
330 331 332 333
        },

        freezeAll: function () {
            _.invoke(Annotator._instances, 'freeze');
polesye committed
334
            return this;
335 336 337 338
        },

        unfreezeAll: function () {
            _.invoke(Annotator._instances, 'unfreeze');
polesye committed
339
            return this;
340 341 342 343 344 345
        },

        showFrozenViewer: function (annotations, location) {
            this.showViewer(annotations, location);
            this.freezeAll();
            return this;
346 347 348 349
        }
    });
});
}).call(this, define || RequireJS.define);