etherpad-lite/src/static/js/broadcast_slider.js

643 lines
20 KiB
JavaScript
Raw Normal View History

/**
* This code is mostly from the old Etherpad. Please help us to comment this code.
* This helps other people to understand this code better and helps them to improve it.
* TL;DR COMMENTS ON THIS FILE ARE HIGHLY APPRECIATED
*/
/**
* Copyright 2009 Google Inc.
2011-07-07 18:59:34 +01:00
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
2011-07-07 18:59:34 +01:00
*
* http://www.apache.org/licenses/LICENSE-2.0
2011-07-07 18:59:34 +01:00
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// These parameters were global, now they are injected. A reference to the
// Timeslider controller would probably be more appropriate.
2012-03-17 13:36:42 +01:00
var _ = require('./underscore');
var padmodals = require('./pad_modals').padmodals;
require("./jquery.class");
/**
* A class for anything which can be hung off of the slider bar.
* I.e. this is for the handle, or saved-revisions (stars).
* TODO:
* - handle mousedowns/clicks
* - handle drags
*/
$.Class("SliderHandleUI",
{//statics
},
{//instance
/**
* Construct the SliderHandle.
* @param {SliderUI} slider The slider from which this handle will be hung.
* @param {Number} position The initial position for this handle.
*/
init: function (slider, position, type) {
console.log("New SliderHandle(%d, %s)", position, type);
this.slider = slider;
this.position = position;
this.events = {};
//create the element:
this.element = $("<div class='slider-handle'></div>");
this.element.addClass(type);
//handle events
this.element.mouseup(this._dispatchEvent);
this.element.mousedown(this._dispatchEvent);
},
on: function (eventname, callback, context) {
if (!(eventname in this.events))
this.events[eventname] = [];
this.events[eventname].push({handler:callback, context: context});
},
_dispatchEvent: function (evt) {
if (eventname in this.events)
for (var i in this.events[eventname])
{
e = this.events[eventname][i];
e.handler(evt, e.context);
}
},
render: function () {
this.element.css('left', this.position * this.slider.getTickSize());
},
setPosition: function (position) {
this.position = position;
this.render();
}
}
);
SliderHandleUI("SliderSavedRevisionUI",
{//statics
},
{//instance
init: function(slider, revision) {
this._super(slider, revision.revNum, 'star');
this.revision = revision;
},
}
);
$.Class("SliderUI",
{//statics
},
{//instance
init: function (timeslider, root_element) {
this.timeslider = timeslider;
console.log("New SliderUI, head_revision = %d", this.timeslider.head_revision);
// parse the various elements we need:
this.elements = {};
this.loadElements(root_element);
this.handles=[];
this.main_handle = this.attachHandle(new SliderHandleUI(this, this.timeslider.head_revision, 'handle'));
this.loadSavedRevisions();
this.render();
//events:
_this = this;
$(window).resize(function() {_this.render.call(_this)});
this.elements['slider-bar'].mousedown(function(evt) {
var revision = Math.floor((evt.clientX-$(this).offset().left) / _this.getTickSize());
_this.goToRevision(revision);
});
},
loadElements: function (root_element) {
this.elements['root'] = root_element;
//this.elements['slider-handle'] = root_element.first("#ui-slider-handle");
this.elements['slider-bar'] = root_element.find("#ui-slider-bar");
this.elements['slider'] = root_element.find("#timeslider-slider");
this.elements['button-left'] = root_element.find("#leftstep");
this.elements['button-right'] = root_element.find("#rightstep");
this.elements['button-play'] = root_element.find("#playpause_button");
this.elements['timestamp'] = root_element.find("#timer");
this.elements['revision-label'] = root_element.find("#revision_label");
this.elements['revision-date'] = root_element.find("#revision_date");
this.elements['authors'] = root_element.first("#authorsList");
},
loadSavedRevisions: function () {
for (var r in this.timeslider.savedRevisions) {
var rev = this.timeslider.savedRevisions[r];
this.attachHandle(new SliderSavedRevisionUI(this, rev));
};
},
render: function () {
for(var h in this.handles)
this.handles[h].render();
},
attachHandle: function (handle) {
this.handles.push(handle);
this.elements['slider'].append(handle.element);
return handle;
},
getTickSize: function () {
return (this.elements['slider-bar'].width()) / (this.timeslider.head_revision * 1.0);
},
goToRevision: function (revNum) {
//TODO: this should actually do an async jump to revision (with all the server fetching
//and changeset rendering that that implies), and perform the setPosition in a callback.
if (revNum <= 0 || revNum > this.timeslider.head_revision)
revNum = this.timeslider.latest_revision;
console.log("GO TO REVISION", revNum)
this.main_handle.setPosition(revNum);
},
}
);
function loadBroadcastSliderJS(tsclient, fireWhenAllScriptsAreLoaded)
{
var BroadcastSlider;
2011-07-07 18:59:34 +01:00
(function()
{ // wrap this code in its own namespace
tsui = new SliderUI(tsclient, $("#timeslider-top"));
// if there was a revision specified in the 'location.hash', jump to it.
if (window.location.hash.length > 1) {
var rev = Number(window.location.hash.substr(1));
if(!isNaN(rev))
tsui.goToRevision(rev);
}
var sliderLength = 1000;
var sliderPos = 0;
var sliderActive = false;
var slidercallbacks = [];
var savedRevisions = [];
var sliderPlaying = false;
clientVars = tsclient.clientVars;
function disableSelection(element)
{
2011-07-07 18:59:34 +01:00
element.onselectstart = function()
{
return false;
};
element.unselectable = "on";
element.style.MozUserSelect = "none";
element.style.cursor = "default";
}
2011-07-07 18:59:34 +01:00
var _callSliderCallbacks = function(newval)
{
sliderPos = newval;
for (var i = 0; i < slidercallbacks.length; i++)
{
slidercallbacks[i](newval);
}
}
2011-07-07 18:59:34 +01:00
var updateSliderElements = function()
{
for (var i = 0; i < savedRevisions.length; i++)
{
var position = parseInt(savedRevisions[i].attr('pos'));
//tsui._setElementPosition(savedRevisions[i], position);
}
//tsui._setElementPosition(tsui.elements['slider-handle'], sliderPos);
}
2011-07-07 18:59:34 +01:00
var addSavedRevision = function(position, info)
{
var newSavedRevision = $('<div></div>');
newSavedRevision.addClass("star");
newSavedRevision.attr('pos', position);
newSavedRevision.css('position', 'absolute');
//tsui._setElementPosition(newSavedRevision, position);
$("#timeslider-slider").append(newSavedRevision);
2011-07-07 18:59:34 +01:00
newSavedRevision.mouseup(function(evt)
{
BroadcastSlider.setSliderPosition(position);
});
savedRevisions.push(newSavedRevision);
};
2011-07-07 18:59:34 +01:00
var removeSavedRevision = function(position)
{
var element = $("div.star [pos=" + position + "]");
savedRevisions.remove(element);
element.remove();
return element;
};
/* Begin small 'API' */
function onSlider(callback)
{
slidercallbacks.push(callback);
}
function getSliderPosition()
{
return sliderPos;
}
function setSliderPosition(newpos)
{
newpos = Number(newpos);
if (newpos < 0 || newpos > sliderLength) return;
2013-02-06 23:35:58 +00:00
if(!newpos){
newpos = 0; // stops it from displaying NaN if newpos isn't set
}
window.location.hash = "#" + newpos;
$("#ui-slider-handle").css('left', newpos * ($("#ui-slider-bar").width() - 2) / (sliderLength * 1.0));
2011-07-07 18:59:34 +01:00
$("a.tlink").map(function()
{
$(this).attr('href', $(this).attr('thref').replace("%revision%", newpos));
});
2012-12-19 19:55:31 +01:00
$("#revision_label").html(html10n.get("timeslider.version", { "version": newpos}));
if (newpos == 0)
{
$("#leftstar").css('opacity', .5);
$("#leftstep").css('opacity', .5);
}
else
{
$("#leftstar").css('opacity', 1);
$("#leftstep").css('opacity', 1);
}
if (newpos == sliderLength)
{
$("#rightstar").css('opacity', .5);
$("#rightstep").css('opacity', .5);
}
else
{
$("#rightstar").css('opacity', 1);
$("#rightstep").css('opacity', 1);
}
sliderPos = newpos;
_callSliderCallbacks(newpos);
}
function getSliderLength()
{
return sliderLength;
}
function setSliderLength(newlength)
{
sliderLength = newlength;
updateSliderElements();
}
// just take over the whole slider screen with a reconnect message
function showReconnectUI()
{
2012-07-14 15:54:44 +02:00
padmodals.showModal("disconnected");
}
2012-03-24 20:35:45 +01:00
var fixPadHeight = _.throttle(function(){
var height = $('#timeslider-top').height();
$('#editorcontainerbox').css({marginTop: height});
}, 600);
function setAuthors(authors)
{
2012-03-24 20:35:45 +01:00
var authorsList = $("#authorsList");
authorsList.empty();
var numAnonymous = 0;
var numNamed = 0;
2012-03-25 15:48:31 +02:00
var colorsAnonymous = [];
2012-03-17 13:36:42 +01:00
_.each(authors, function(author)
{
2012-03-25 15:48:31 +02:00
var authorColor = clientVars.colorPalette[author.colorId] || author.colorId;
if (author.name)
{
2012-03-24 20:35:45 +01:00
if (numNamed !== 0) authorsList.append(', ');
2012-03-25 15:48:31 +02:00
$('<span />')
.text(author.name || "unnamed")
.css('background-color', authorColor)
.addClass('author')
.appendTo(authorsList);
numNamed++;
}
else
{
numAnonymous++;
2012-03-25 15:48:31 +02:00
if(authorColor) colorsAnonymous.push(authorColor);
}
});
if (numAnonymous > 0)
{
2013-07-23 12:43:30 +02:00
var anonymousAuthorString = html10n.get("timeslider.unnamedauthors", { num: numAnonymous });
2012-03-24 20:35:45 +01:00
if (numNamed !== 0){
authorsList.append(' + ' + anonymousAuthorString);
} else {
authorsList.append(anonymousAuthorString);
}
2012-03-25 15:48:31 +02:00
if(colorsAnonymous.length > 0){
authorsList.append(' (');
_.each(colorsAnonymous, function(color, i){
if( i > 0 ) authorsList.append(' ');
2012-04-15 19:18:29 +02:00
$('<span>&nbsp;</span>')
2012-03-25 15:48:31 +02:00
.css('background-color', color)
.addClass('author author-anonymous')
.appendTo(authorsList);
});
authorsList.append(')');
}
}
if (authors.length == 0)
{
2012-12-19 19:55:31 +01:00
authorsList.append(html10n.get("timeslider.toolbar.authorsList"));
}
2012-03-24 20:35:45 +01:00
fixPadHeight();
}
BroadcastSlider = {
onSlider: onSlider,
getSliderPosition: getSliderPosition,
setSliderPosition: setSliderPosition,
getSliderLength: getSliderLength,
setSliderLength: setSliderLength,
2011-07-07 18:59:34 +01:00
isSliderActive: function()
{
return sliderActive;
},
playpause: playpause,
addSavedRevision: addSavedRevision,
showReconnectUI: showReconnectUI,
setAuthors: setAuthors
}
function playButtonUpdater()
{
if (sliderPlaying)
{
if (getSliderPosition() + 1 > sliderLength)
{
$("#playpause_button_icon").toggleClass('pause');
sliderPlaying = false;
return;
}
setSliderPosition(getSliderPosition() + 1);
setTimeout(playButtonUpdater, 100);
}
}
function playpause()
{
$("#playpause_button_icon").toggleClass('pause');
if (!sliderPlaying)
{
if (getSliderPosition() == sliderLength) setSliderPosition(0);
sliderPlaying = true;
playButtonUpdater();
}
else
{
sliderPlaying = false;
}
}
// assign event handlers to html UI elements after page load
//$(window).load(function ()
2011-07-07 18:59:34 +01:00
fireWhenAllScriptsAreLoaded.push(function()
{
disableSelection($("#playpause_button")[0]);
disableSelection($("#timeslider")[0]);
$(document).keyup(function(e)
{
var code = -1;
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
if (code == 37)
{ // left
if (!e.shiftKey)
{
setSliderPosition(getSliderPosition() - 1);
}
else
{
var nextStar = 0; // default to first revision in document
for (var i = 0; i < savedRevisions.length; i++)
{
var pos = parseInt(savedRevisions[i].attr('pos'));
if (pos < getSliderPosition() && nextStar < pos) nextStar = pos;
}
setSliderPosition(nextStar);
}
}
else if (code == 39)
{
if (!e.shiftKey)
{
setSliderPosition(getSliderPosition() + 1);
}
else
{
var nextStar = sliderLength; // default to last revision in document
for (var i = 0; i < savedRevisions.length; i++)
{
var pos = parseInt(savedRevisions[i].attr('pos'));
if (pos > getSliderPosition() && nextStar > pos) nextStar = pos;
}
setSliderPosition(nextStar);
}
}
else if (code == 32) playpause();
});
/*$(window).resize(function()
{
tsui.render();
updateSliderElements();
});
*/
/*$("#ui-slider-bar").mousedown(function(evt)
{
setSliderPosition(Math.floor((evt.clientX - $("#ui-slider-bar").offset().left) * sliderLength / 742));
$("#ui-slider-handle").css('left', (evt.clientX - $("#ui-slider-bar").offset().left));
$("#ui-slider-handle").trigger(evt);
});
*/
// Slider dragging
2011-07-07 18:59:34 +01:00
$("#ui-slider-handle").mousedown(function(evt)
{
this.startLoc = evt.clientX;
this.currentLoc = parseInt($(this).css('left'));
var self = this;
sliderActive = true;
2011-07-07 18:59:34 +01:00
$(document).mousemove(function(evt2)
{
$(self).css('pointer', 'move')
var newloc = self.currentLoc + (evt2.clientX - self.startLoc);
if (newloc < 0) newloc = 0;
if (newloc > ($("#ui-slider-bar").width() - 2)) newloc = ($("#ui-slider-bar").width() - 2);
2012-12-19 19:55:31 +01:00
$("#revision_label").html(html10n.get("timeslider.version", { "version": Math.floor(newloc * sliderLength / ($("#ui-slider-bar").width() - 2))}));
$(self).css('left', newloc);
if (getSliderPosition() != Math.floor(newloc * sliderLength / ($("#ui-slider-bar").width() - 2))) _callSliderCallbacks(Math.floor(newloc * sliderLength / ($("#ui-slider-bar").width() - 2)))
});
2011-07-07 18:59:34 +01:00
$(document).mouseup(function(evt2)
{
$(document).unbind('mousemove');
$(document).unbind('mouseup');
sliderActive = false;
var newloc = self.currentLoc + (evt2.clientX - self.startLoc);
if (newloc < 0) newloc = 0;
if (newloc > ($("#ui-slider-bar").width() - 2)) newloc = ($("#ui-slider-bar").width() - 2);
$(self).css('left', newloc);
// if(getSliderPosition() != Math.floor(newloc * sliderLength / ($("#ui-slider-bar").width()-2)))
setSliderPosition(Math.floor(newloc * sliderLength / ($("#ui-slider-bar").width() - 2)))
2013-01-24 16:48:40 +00:00
if(parseInt($(self).css('left')) < 2){
$(self).css('left', '2px');
}else{
self.currentLoc = parseInt($(self).css('left'));
}
});
})
// play/pause toggling
2011-07-07 18:59:34 +01:00
$("#playpause_button").mousedown(function(evt)
{
var self = this;
2011-06-20 15:37:41 +01:00
$(self).css('background-image', 'url(/static/img/crushed_button_depressed.png)');
2011-07-07 18:59:34 +01:00
$(self).mouseup(function(evt2)
{
2011-06-20 15:37:41 +01:00
$(self).css('background-image', 'url(/static/img/crushed_button_undepressed.png)');
$(self).unbind('mouseup');
BroadcastSlider.playpause();
});
2011-07-07 18:59:34 +01:00
$(document).mouseup(function(evt2)
{
2011-06-20 15:37:41 +01:00
$(self).css('background-image', 'url(/static/img/crushed_button_undepressed.png)');
$(document).unbind('mouseup');
});
});
// next/prev saved revision and changeset
2011-07-07 18:59:34 +01:00
$('.stepper').mousedown(function(evt)
{
var self = this;
var origcss = $(self).css('background-position');
if (!origcss)
{
origcss = $(self).css('background-position-x') + " " + $(self).css('background-position-y');
}
var origpos = parseInt(origcss.split(" ")[1]);
var newpos = (origpos - 43);
if (newpos < 0) newpos += 87;
var newcss = (origcss.split(" ")[0] + " " + newpos + "px");
if ($(self).css('opacity') != 1.0) newcss = origcss;
$(self).css('background-position', newcss)
2011-07-07 18:59:34 +01:00
$(self).mouseup(function(evt2)
{
$(self).css('background-position', origcss);
$(self).unbind('mouseup');
$(document).unbind('mouseup');
if ($(self).attr("id") == ("leftstep"))
{
setSliderPosition(getSliderPosition() - 1);
}
else if ($(self).attr("id") == ("rightstep"))
{
setSliderPosition(getSliderPosition() + 1);
}
else if ($(self).attr("id") == ("leftstar"))
{
var nextStar = 0; // default to first revision in document
for (var i = 0; i < savedRevisions.length; i++)
{
var pos = parseInt(savedRevisions[i].attr('pos'));
if (pos < getSliderPosition() && nextStar < pos) nextStar = pos;
}
setSliderPosition(nextStar);
}
else if ($(self).attr("id") == ("rightstar"))
{
var nextStar = sliderLength; // default to last revision in document
for (var i = 0; i < savedRevisions.length; i++)
{
var pos = parseInt(savedRevisions[i].attr('pos'));
if (pos > getSliderPosition() && nextStar > pos) nextStar = pos;
}
setSliderPosition(nextStar);
}
});
2011-07-07 18:59:34 +01:00
$(document).mouseup(function(evt2)
{
$(self).css('background-position', origcss);
$(self).unbind('mouseup');
$(document).unbind('mouseup');
});
})
if (clientVars)
{
$("#timeslider").show();
var startPos = clientVars.collab_client_vars.rev;
/*if(window.location.hash.length > 1)
{
var hashRev = Number(window.location.hash.substr(1));
if(!isNaN(hashRev))
{
// this is necessary because of the socket.io-event which loads the changesets
setTimeout(function() { setSliderPosition(hashRev); }, 1);
}
}
*/
//setSliderLength(clientVars.collab_client_vars.rev);
//setSliderPosition(clientVars.collab_client_vars.rev);
/*
_.eacheach(clientVars.savedRevisions, function(revision)
{
addSavedRevision(revision.revNum, revision);
})
*/
}
});
})();
2011-07-07 18:59:34 +01:00
BroadcastSlider.onSlider(function(loc)
{
$("#viewlatest").html(loc == BroadcastSlider.getSliderLength() ? "Viewing latest content" : "View latest content");
})
return BroadcastSlider;
}
exports.loadBroadcastSliderJS = loadBroadcastSliderJS;